diff --git a/go/src/arena/arena.go b/go/src/arena/arena.go new file mode 100644 index 0000000000000000000000000000000000000000..35b2fbd2aadd8cf69db74a254715afb592e50833 --- /dev/null +++ b/go/src/arena/arena.go @@ -0,0 +1,108 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build goexperiment.arenas + +/* +The arena package provides the ability to allocate memory for a collection +of Go values and free that space manually all at once, safely. The purpose +of this functionality is to improve efficiency: manually freeing memory +before a garbage collection delays that cycle. Less frequent cycles means +the CPU cost of the garbage collector is incurred less frequently. + +This functionality in this package is mostly captured in the Arena type. +Arenas allocate large chunks of memory for Go values, so they're likely to +be inefficient for allocating only small amounts of small Go values. They're +best used in bulk, on the order of MiB of memory allocated on each use. + +Note that by allowing for this limited form of manual memory allocation +that use-after-free bugs are possible with regular Go values. This package +limits the impact of these use-after-free bugs by preventing reuse of freed +memory regions until the garbage collector is able to determine that it is +safe. Typically, a use-after-free bug will result in a fault and a helpful +error message, but this package reserves the right to not force a fault on +freed memory. That means a valid implementation of this package is to just +allocate all memory the way the runtime normally would, and in fact, it +reserves the right to occasionally do so for some Go values. +*/ +package arena + +import ( + "internal/reflectlite" + "unsafe" +) + +// Arena represents a collection of Go values allocated and freed together. +// Arenas are useful for improving efficiency as they may be freed back to +// the runtime manually, though any memory obtained from freed arenas must +// not be accessed once that happens. An Arena is automatically freed once +// it is no longer referenced, so it must be kept alive (see runtime.KeepAlive) +// until any memory allocated from it is no longer needed. +// +// An Arena must never be used concurrently by multiple goroutines. +type Arena struct { + a unsafe.Pointer +} + +// NewArena allocates a new arena. +func NewArena() *Arena { + return &Arena{a: runtime_arena_newArena()} +} + +// Free frees the arena (and all objects allocated from the arena) so that +// memory backing the arena can be reused fairly quickly without garbage +// collection overhead. Applications must not call any method on this +// arena after it has been freed. +func (a *Arena) Free() { + runtime_arena_arena_Free(a.a) + a.a = nil +} + +// New creates a new *T in the provided arena. The *T must not be used after +// the arena is freed. Accessing the value after free may result in a fault, +// but this fault is also not guaranteed. +func New[T any](a *Arena) *T { + return runtime_arena_arena_New(a.a, reflectlite.TypeOf((*T)(nil))).(*T) +} + +// MakeSlice creates a new []T with the provided capacity and length. The []T must +// not be used after the arena is freed. Accessing the underlying storage of the +// slice after free may result in a fault, but this fault is also not guaranteed. +func MakeSlice[T any](a *Arena, len, cap int) []T { + var sl []T + runtime_arena_arena_Slice(a.a, &sl, cap) + return sl[:len] +} + +// Clone makes a shallow copy of the input value that is no longer bound to any +// arena it may have been allocated from, returning the copy. If it was not +// allocated from an arena, it is returned untouched. This function is useful +// to more easily let an arena-allocated value out-live its arena. +// T must be a pointer, a slice, or a string, otherwise this function will panic. +func Clone[T any](s T) T { + return runtime_arena_heapify(s).(T) +} + +//go:linkname reflect_arena_New reflect.arena_New +func reflect_arena_New(a *Arena, typ any) any { + return runtime_arena_arena_New(a.a, typ) +} + +//go:linkname runtime_arena_newArena +func runtime_arena_newArena() unsafe.Pointer + +//go:linkname runtime_arena_arena_New +func runtime_arena_arena_New(arena unsafe.Pointer, typ any) any + +// Mark as noescape to avoid escaping the slice header. +// +//go:noescape +//go:linkname runtime_arena_arena_Slice +func runtime_arena_arena_Slice(arena unsafe.Pointer, slice any, cap int) + +//go:linkname runtime_arena_arena_Free +func runtime_arena_arena_Free(arena unsafe.Pointer) + +//go:linkname runtime_arena_heapify +func runtime_arena_heapify(any) any diff --git a/go/src/arena/arena_test.go b/go/src/arena/arena_test.go new file mode 100644 index 0000000000000000000000000000000000000000..017c33c502a7183c7e64f839ac3b36d0cf82396b --- /dev/null +++ b/go/src/arena/arena_test.go @@ -0,0 +1,42 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build goexperiment.arenas + +package arena_test + +import ( + "arena" + "testing" +) + +type T1 struct { + n int +} +type T2 [1 << 20]byte // 1MiB + +func TestSmoke(t *testing.T) { + a := arena.NewArena() + defer a.Free() + + tt := arena.New[T1](a) + tt.n = 1 + + ts := arena.MakeSlice[T1](a, 99, 100) + if len(ts) != 99 { + t.Errorf("Slice() len = %d, want 99", len(ts)) + } + if cap(ts) != 100 { + t.Errorf("Slice() cap = %d, want 100", cap(ts)) + } + ts[1].n = 42 +} + +func TestSmokeLarge(t *testing.T) { + a := arena.NewArena() + defer a.Free() + for i := 0; i < 10*64; i++ { + _ = arena.New[T2](a) + } +} diff --git a/go/src/bufio/bufio.go b/go/src/bufio/bufio.go new file mode 100644 index 0000000000000000000000000000000000000000..141a9a1a2a2305f070ec7ecf38ca16152ee2aeb9 --- /dev/null +++ b/go/src/bufio/bufio.go @@ -0,0 +1,842 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer +// object, creating another object (Reader or Writer) that also implements +// the interface but provides buffering and some help for textual I/O. +package bufio + +import ( + "bytes" + "errors" + "io" + "strings" + "unicode/utf8" +) + +const ( + defaultBufSize = 4096 +) + +var ( + ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte") + ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune") + ErrBufferFull = errors.New("bufio: buffer full") + ErrNegativeCount = errors.New("bufio: negative count") +) + +// Buffered input. + +// Reader implements buffering for an io.Reader object. +// A new Reader is created by calling [NewReader] or [NewReaderSize]; +// alternatively the zero value of a Reader may be used after calling [Reset] +// on it. +type Reader struct { + buf []byte + rd io.Reader // reader provided by the client + r, w int // buf read and write positions + err error + lastByte int // last byte read for UnreadByte; -1 means invalid + lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid +} + +const minReadBufferSize = 16 +const maxConsecutiveEmptyReads = 100 + +// NewReaderSize returns a new [Reader] whose buffer has at least the specified +// size. If the argument io.Reader is already a [Reader] with large enough +// size, it returns the underlying [Reader]. +func NewReaderSize(rd io.Reader, size int) *Reader { + // Is it already a Reader? + b, ok := rd.(*Reader) + if ok && len(b.buf) >= size { + return b + } + r := new(Reader) + r.reset(make([]byte, max(size, minReadBufferSize)), rd) + return r +} + +// NewReader returns a new [Reader] whose buffer has the default size. +func NewReader(rd io.Reader) *Reader { + return NewReaderSize(rd, defaultBufSize) +} + +// Size returns the size of the underlying buffer in bytes. +func (b *Reader) Size() int { return len(b.buf) } + +// Reset discards any buffered data, resets all state, and switches +// the buffered reader to read from r. +// Calling Reset on the zero value of [Reader] initializes the internal buffer +// to the default size. +// Calling b.Reset(b) (that is, resetting a [Reader] to itself) does nothing. +func (b *Reader) Reset(r io.Reader) { + // If a Reader r is passed to NewReader, NewReader will return r. + // Different layers of code may do that, and then later pass r + // to Reset. Avoid infinite recursion in that case. + if b == r { + return + } + if b.buf == nil { + b.buf = make([]byte, defaultBufSize) + } + b.reset(b.buf, r) +} + +func (b *Reader) reset(buf []byte, r io.Reader) { + *b = Reader{ + buf: buf, + rd: r, + lastByte: -1, + lastRuneSize: -1, + } +} + +var errNegativeRead = errors.New("bufio: reader returned negative count from Read") + +// fill reads a new chunk into the buffer. +func (b *Reader) fill() { + // Slide existing data to beginning. + if b.r > 0 { + copy(b.buf, b.buf[b.r:b.w]) + b.w -= b.r + b.r = 0 + } + + if b.w >= len(b.buf) { + panic("bufio: tried to fill full buffer") + } + + // Read new data: try a limited number of times. + for i := maxConsecutiveEmptyReads; i > 0; i-- { + n, err := b.rd.Read(b.buf[b.w:]) + if n < 0 { + panic(errNegativeRead) + } + b.w += n + if err != nil { + b.err = err + return + } + if n > 0 { + return + } + } + b.err = io.ErrNoProgress +} + +func (b *Reader) readErr() error { + err := b.err + b.err = nil + return err +} + +// Peek returns the next n bytes without advancing the reader. The bytes stop +// being valid at the next read call. If necessary, Peek will read more bytes +// into the buffer in order to make n bytes available. If Peek returns fewer +// than n bytes, it also returns an error explaining why the read is short. +// The error is [ErrBufferFull] if n is larger than b's buffer size. +// +// Calling Peek prevents a [Reader.UnreadByte] or [Reader.UnreadRune] call from succeeding +// until the next read operation. +func (b *Reader) Peek(n int) ([]byte, error) { + if n < 0 { + return nil, ErrNegativeCount + } + + b.lastByte = -1 + b.lastRuneSize = -1 + + for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil { + b.fill() // b.w-b.r < len(b.buf) => buffer is not full + } + + if n > len(b.buf) { + return b.buf[b.r:b.w], ErrBufferFull + } + + // 0 <= n <= len(b.buf) + var err error + if avail := b.w - b.r; avail < n { + // not enough data in buffer + n = avail + err = b.readErr() + if err == nil { + err = ErrBufferFull + } + } + return b.buf[b.r : b.r+n], err +} + +// Discard skips the next n bytes, returning the number of bytes discarded. +// +// If Discard skips fewer than n bytes, it also returns an error. +// If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without +// reading from the underlying io.Reader. +func (b *Reader) Discard(n int) (discarded int, err error) { + if n < 0 { + return 0, ErrNegativeCount + } + if n == 0 { + return + } + + b.lastByte = -1 + b.lastRuneSize = -1 + + remain := n + for { + skip := b.Buffered() + if skip == 0 { + b.fill() + skip = b.Buffered() + } + if skip > remain { + skip = remain + } + b.r += skip + remain -= skip + if remain == 0 { + return n, nil + } + if b.err != nil { + return n - remain, b.readErr() + } + } +} + +// Read reads data into p. +// It returns the number of bytes read into p. +// The bytes are taken from at most one Read on the underlying [Reader], +// hence n may be less than len(p). +// To read exactly len(p) bytes, use io.ReadFull(b, p). +// If the underlying [Reader] can return a non-zero count with io.EOF, +// then this Read method can do so as well; see the [io.Reader] docs. +func (b *Reader) Read(p []byte) (n int, err error) { + n = len(p) + if n == 0 { + if b.Buffered() > 0 { + return 0, nil + } + return 0, b.readErr() + } + if b.r == b.w { + if b.err != nil { + return 0, b.readErr() + } + if len(p) >= len(b.buf) { + // Large read, empty buffer. + // Read directly into p to avoid copy. + n, b.err = b.rd.Read(p) + if n < 0 { + panic(errNegativeRead) + } + if n > 0 { + b.lastByte = int(p[n-1]) + b.lastRuneSize = -1 + } + return n, b.readErr() + } + // One read. + // Do not use b.fill, which will loop. + b.r = 0 + b.w = 0 + n, b.err = b.rd.Read(b.buf) + if n < 0 { + panic(errNegativeRead) + } + if n == 0 { + return 0, b.readErr() + } + b.w += n + } + + // copy as much as we can + // Note: if the slice panics here, it is probably because + // the underlying reader returned a bad count. See issue 49795. + n = copy(p, b.buf[b.r:b.w]) + b.r += n + b.lastByte = int(b.buf[b.r-1]) + b.lastRuneSize = -1 + return n, nil +} + +// ReadByte reads and returns a single byte. +// If no byte is available, returns an error. +func (b *Reader) ReadByte() (byte, error) { + b.lastRuneSize = -1 + for b.r == b.w { + if b.err != nil { + return 0, b.readErr() + } + b.fill() // buffer is empty + } + c := b.buf[b.r] + b.r++ + b.lastByte = int(c) + return c, nil +} + +// UnreadByte unreads the last byte. Only the most recently read byte can be unread. +// +// UnreadByte returns an error if the most recent method called on the +// [Reader] was not a read operation. Notably, [Reader.Peek], [Reader.Discard], and [Reader.WriteTo] are not +// considered read operations. +func (b *Reader) UnreadByte() error { + if b.lastByte < 0 || b.r == 0 && b.w > 0 { + return ErrInvalidUnreadByte + } + // b.r > 0 || b.w == 0 + if b.r > 0 { + b.r-- + } else { + // b.r == 0 && b.w == 0 + b.w = 1 + } + b.buf[b.r] = byte(b.lastByte) + b.lastByte = -1 + b.lastRuneSize = -1 + return nil +} + +// ReadRune reads a single UTF-8 encoded Unicode character and returns the +// rune and its size in bytes. If the encoded rune is invalid, it consumes one byte +// and returns unicode.ReplacementChar (U+FFFD) with a size of 1. +func (b *Reader) ReadRune() (r rune, size int, err error) { + for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil && b.w-b.r < len(b.buf) { + b.fill() // b.w-b.r < len(buf) => buffer is not full + } + b.lastRuneSize = -1 + if b.r == b.w { + return 0, 0, b.readErr() + } + r, size = utf8.DecodeRune(b.buf[b.r:b.w]) + b.r += size + b.lastByte = int(b.buf[b.r-1]) + b.lastRuneSize = size + return r, size, nil +} + +// UnreadRune unreads the last rune. If the most recent method called on +// the [Reader] was not a [Reader.ReadRune], [Reader.UnreadRune] returns an error. (In this +// regard it is stricter than [Reader.UnreadByte], which will unread the last byte +// from any read operation.) +func (b *Reader) UnreadRune() error { + if b.lastRuneSize < 0 || b.r < b.lastRuneSize { + return ErrInvalidUnreadRune + } + b.r -= b.lastRuneSize + b.lastByte = -1 + b.lastRuneSize = -1 + return nil +} + +// Buffered returns the number of bytes that can be read from the current buffer. +func (b *Reader) Buffered() int { return b.w - b.r } + +// ReadSlice reads until the first occurrence of delim in the input, +// returning a slice pointing at the bytes in the buffer. +// The bytes stop being valid at the next read. +// If ReadSlice encounters an error before finding a delimiter, +// it returns all the data in the buffer and the error itself (often io.EOF). +// ReadSlice fails with error [ErrBufferFull] if the buffer fills without a delim. +// Because the data returned from ReadSlice will be overwritten +// by the next I/O operation, most clients should use +// [Reader.ReadBytes] or ReadString instead. +// ReadSlice returns err != nil if and only if line does not end in delim. +func (b *Reader) ReadSlice(delim byte) (line []byte, err error) { + s := 0 // search start index + for { + // Search buffer. + if i := bytes.IndexByte(b.buf[b.r+s:b.w], delim); i >= 0 { + i += s + line = b.buf[b.r : b.r+i+1] + b.r += i + 1 + break + } + + // Pending error? + if b.err != nil { + line = b.buf[b.r:b.w] + b.r = b.w + err = b.readErr() + break + } + + // Buffer full? + if b.Buffered() >= len(b.buf) { + b.r = b.w + line = b.buf + err = ErrBufferFull + break + } + + s = b.w - b.r // do not rescan area we scanned before + + b.fill() // buffer is not full + } + + // Handle last byte, if any. + if i := len(line) - 1; i >= 0 { + b.lastByte = int(line[i]) + b.lastRuneSize = -1 + } + + return +} + +// ReadLine is a low-level line-reading primitive. Most callers should use +// [Reader.ReadBytes]('\n') or [Reader.ReadString]('\n') instead or use a [Scanner]. +// +// ReadLine tries to return a single line, not including the end-of-line bytes. +// If the line was too long for the buffer then isPrefix is set and the +// beginning of the line is returned. The rest of the line will be returned +// from future calls. isPrefix will be false when returning the last fragment +// of the line. The returned buffer is only valid until the next call to +// ReadLine. ReadLine either returns a non-nil line or it returns an error, +// never both. +// +// The text returned from ReadLine does not include the line end ("\r\n" or "\n"). +// No indication or error is given if the input ends without a final line end. +// Calling [Reader.UnreadByte] after ReadLine will always unread the last byte read +// (possibly a character belonging to the line end) even if that byte is not +// part of the line returned by ReadLine. +func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) { + line, err = b.ReadSlice('\n') + if err == ErrBufferFull { + // Handle the case where "\r\n" straddles the buffer. + if len(line) > 0 && line[len(line)-1] == '\r' { + // Put the '\r' back on buf and drop it from line. + // Let the next call to ReadLine check for "\r\n". + if b.r == 0 { + // should be unreachable + panic("bufio: tried to rewind past start of buffer") + } + b.r-- + line = line[:len(line)-1] + } + return line, true, nil + } + + if len(line) == 0 { + if err != nil { + line = nil + } + return + } + err = nil + + if line[len(line)-1] == '\n' { + drop := 1 + if len(line) > 1 && line[len(line)-2] == '\r' { + drop = 2 + } + line = line[:len(line)-drop] + } + return +} + +// collectFragments reads until the first occurrence of delim in the input. It +// returns (slice of full buffers, remaining bytes before delim, total number +// of bytes in the combined first two elements, error). +// The complete result is equal to +// `bytes.Join(append(fullBuffers, finalFragment), nil)`, which has a +// length of `totalLen`. The result is structured in this way to allow callers +// to minimize allocations and copies. +func (b *Reader) collectFragments(delim byte) (fullBuffers [][]byte, finalFragment []byte, totalLen int, err error) { + var frag []byte + // Use ReadSlice to look for delim, accumulating full buffers. + for { + var e error + frag, e = b.ReadSlice(delim) + if e == nil { // got final fragment + break + } + if e != ErrBufferFull { // unexpected error + err = e + break + } + + // Make a copy of the buffer. + buf := bytes.Clone(frag) + fullBuffers = append(fullBuffers, buf) + totalLen += len(buf) + } + + totalLen += len(frag) + return fullBuffers, frag, totalLen, err +} + +// ReadBytes reads until the first occurrence of delim in the input, +// returning a slice containing the data up to and including the delimiter. +// If ReadBytes encounters an error before finding a delimiter, +// it returns the data read before the error and the error itself (often io.EOF). +// ReadBytes returns err != nil if and only if the returned data does not end in +// delim. +// For simple uses, a Scanner may be more convenient. +func (b *Reader) ReadBytes(delim byte) ([]byte, error) { + full, frag, n, err := b.collectFragments(delim) + // Allocate new buffer to hold the full pieces and the fragment. + buf := make([]byte, n) + n = 0 + // Copy full pieces and fragment in. + for i := range full { + n += copy(buf[n:], full[i]) + } + copy(buf[n:], frag) + return buf, err +} + +// ReadString reads until the first occurrence of delim in the input, +// returning a string containing the data up to and including the delimiter. +// If ReadString encounters an error before finding a delimiter, +// it returns the data read before the error and the error itself (often io.EOF). +// ReadString returns err != nil if and only if the returned data does not end in +// delim. +// For simple uses, a Scanner may be more convenient. +func (b *Reader) ReadString(delim byte) (string, error) { + full, frag, n, err := b.collectFragments(delim) + // Allocate new buffer to hold the full pieces and the fragment. + var buf strings.Builder + buf.Grow(n) + // Copy full pieces and fragment in. + for _, fb := range full { + buf.Write(fb) + } + buf.Write(frag) + return buf.String(), err +} + +// WriteTo implements io.WriterTo. +// This may make multiple calls to the [Reader.Read] method of the underlying [Reader]. +// If the underlying reader supports the [Reader.WriteTo] method, +// this calls the underlying [Reader.WriteTo] without buffering. +func (b *Reader) WriteTo(w io.Writer) (n int64, err error) { + b.lastByte = -1 + b.lastRuneSize = -1 + + if b.r < b.w { + n, err = b.writeBuf(w) + if err != nil { + return + } + } + + if r, ok := b.rd.(io.WriterTo); ok { + m, err := r.WriteTo(w) + n += m + return n, err + } + + if w, ok := w.(io.ReaderFrom); ok { + m, err := w.ReadFrom(b.rd) + n += m + return n, err + } + + if b.w-b.r < len(b.buf) { + b.fill() // buffer not full + } + + for b.r < b.w { + // b.r < b.w => buffer is not empty + m, err := b.writeBuf(w) + n += m + if err != nil { + return n, err + } + b.fill() // buffer is empty + } + + if b.err == io.EOF { + b.err = nil + } + + return n, b.readErr() +} + +var errNegativeWrite = errors.New("bufio: writer returned negative count from Write") + +// writeBuf writes the [Reader]'s buffer to the writer. +func (b *Reader) writeBuf(w io.Writer) (int64, error) { + n, err := w.Write(b.buf[b.r:b.w]) + if n < 0 { + panic(errNegativeWrite) + } + b.r += n + return int64(n), err +} + +// buffered output + +// Writer implements buffering for an [io.Writer] object. +// If an error occurs writing to a [Writer], no more data will be +// accepted and all subsequent writes, and [Writer.Flush], will return the error. +// After all data has been written, the client should call the +// [Writer.Flush] method to guarantee all data has been forwarded to +// the underlying [io.Writer]. +type Writer struct { + err error + buf []byte + n int + wr io.Writer +} + +// NewWriterSize returns a new [Writer] whose buffer has at least the specified +// size. If the argument io.Writer is already a [Writer] with large enough +// size, it returns the underlying [Writer]. +func NewWriterSize(w io.Writer, size int) *Writer { + // Is it already a Writer? + b, ok := w.(*Writer) + if ok && len(b.buf) >= size { + return b + } + if size <= 0 { + size = defaultBufSize + } + return &Writer{ + buf: make([]byte, size), + wr: w, + } +} + +// NewWriter returns a new [Writer] whose buffer has the default size. +// If the argument io.Writer is already a [Writer] with large enough buffer size, +// it returns the underlying [Writer]. +func NewWriter(w io.Writer) *Writer { + return NewWriterSize(w, defaultBufSize) +} + +// Size returns the size of the underlying buffer in bytes. +func (b *Writer) Size() int { return len(b.buf) } + +// Reset discards any unflushed buffered data, clears any error, and +// resets b to write its output to w. +// Calling Reset on the zero value of [Writer] initializes the internal buffer +// to the default size. +// Calling w.Reset(w) (that is, resetting a [Writer] to itself) does nothing. +func (b *Writer) Reset(w io.Writer) { + // If a Writer w is passed to NewWriter, NewWriter will return w. + // Different layers of code may do that, and then later pass w + // to Reset. Avoid infinite recursion in that case. + if b == w { + return + } + if b.buf == nil { + b.buf = make([]byte, defaultBufSize) + } + b.err = nil + b.n = 0 + b.wr = w +} + +// Flush writes any buffered data to the underlying [io.Writer]. +func (b *Writer) Flush() error { + if b.err != nil { + return b.err + } + if b.n == 0 { + return nil + } + n, err := b.wr.Write(b.buf[0:b.n]) + if n < b.n && err == nil { + err = io.ErrShortWrite + } + if err != nil { + if n > 0 && n < b.n { + copy(b.buf[0:b.n-n], b.buf[n:b.n]) + } + b.n -= n + b.err = err + return err + } + b.n = 0 + return nil +} + +// Available returns how many bytes are unused in the buffer. +func (b *Writer) Available() int { return len(b.buf) - b.n } + +// AvailableBuffer returns an empty buffer with b.Available() capacity. +// This buffer is intended to be appended to and +// passed to an immediately succeeding [Writer.Write] call. +// The buffer is only valid until the next write operation on b. +func (b *Writer) AvailableBuffer() []byte { + return b.buf[b.n:][:0] +} + +// Buffered returns the number of bytes that have been written into the current buffer. +func (b *Writer) Buffered() int { return b.n } + +// Write writes the contents of p into the buffer. +// It returns the number of bytes written. +// If nn < len(p), it also returns an error explaining +// why the write is short. +func (b *Writer) Write(p []byte) (nn int, err error) { + for len(p) > b.Available() && b.err == nil { + var n int + if b.Buffered() == 0 { + // Large write, empty buffer. + // Write directly from p to avoid copy. + n, b.err = b.wr.Write(p) + } else { + n = copy(b.buf[b.n:], p) + b.n += n + b.Flush() + } + nn += n + p = p[n:] + } + if b.err != nil { + return nn, b.err + } + n := copy(b.buf[b.n:], p) + b.n += n + nn += n + return nn, nil +} + +// WriteByte writes a single byte. +func (b *Writer) WriteByte(c byte) error { + if b.err != nil { + return b.err + } + if b.Available() <= 0 && b.Flush() != nil { + return b.err + } + b.buf[b.n] = c + b.n++ + return nil +} + +// WriteRune writes a single Unicode code point, returning +// the number of bytes written and any error. +func (b *Writer) WriteRune(r rune) (size int, err error) { + // Compare as uint32 to correctly handle negative runes. + if uint32(r) < utf8.RuneSelf { + err = b.WriteByte(byte(r)) + if err != nil { + return 0, err + } + return 1, nil + } + if b.err != nil { + return 0, b.err + } + n := b.Available() + if n < utf8.UTFMax { + if b.Flush(); b.err != nil { + return 0, b.err + } + n = b.Available() + if n < utf8.UTFMax { + // Can only happen if buffer is silly small. + return b.WriteString(string(r)) + } + } + size = utf8.EncodeRune(b.buf[b.n:], r) + b.n += size + return size, nil +} + +// WriteString writes a string. +// It returns the number of bytes written. +// If the count is less than len(s), it also returns an error explaining +// why the write is short. +func (b *Writer) WriteString(s string) (int, error) { + var sw io.StringWriter + tryStringWriter := true + + nn := 0 + for len(s) > b.Available() && b.err == nil { + var n int + if b.Buffered() == 0 && sw == nil && tryStringWriter { + // Check at most once whether b.wr is a StringWriter. + sw, tryStringWriter = b.wr.(io.StringWriter) + } + if b.Buffered() == 0 && tryStringWriter { + // Large write, empty buffer, and the underlying writer supports + // WriteString: forward the write to the underlying StringWriter. + // This avoids an extra copy. + n, b.err = sw.WriteString(s) + } else { + n = copy(b.buf[b.n:], s) + b.n += n + b.Flush() + } + nn += n + s = s[n:] + } + if b.err != nil { + return nn, b.err + } + n := copy(b.buf[b.n:], s) + b.n += n + nn += n + return nn, nil +} + +// ReadFrom implements [io.ReaderFrom]. If the underlying writer +// supports the ReadFrom method, this calls the underlying ReadFrom. +// If there is buffered data and an underlying ReadFrom, this fills +// the buffer and writes it before calling ReadFrom. +func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) { + if b.err != nil { + return 0, b.err + } + readerFrom, readerFromOK := b.wr.(io.ReaderFrom) + var m int + for { + if b.Available() == 0 { + if err1 := b.Flush(); err1 != nil { + return n, err1 + } + } + if readerFromOK && b.Buffered() == 0 { + nn, err := readerFrom.ReadFrom(r) + b.err = err + n += nn + return n, err + } + nr := 0 + for nr < maxConsecutiveEmptyReads { + m, err = r.Read(b.buf[b.n:]) + if m != 0 || err != nil { + break + } + nr++ + } + if nr == maxConsecutiveEmptyReads { + return n, io.ErrNoProgress + } + b.n += m + n += int64(m) + if err != nil { + break + } + } + if err == io.EOF { + // If we filled the buffer exactly, flush preemptively. + if b.Available() == 0 { + err = b.Flush() + } else { + err = nil + } + } + return n, err +} + +// buffered input and output + +// ReadWriter stores pointers to a [Reader] and a [Writer]. +// It implements [io.ReadWriter]. +type ReadWriter struct { + *Reader + *Writer +} + +// NewReadWriter allocates a new [ReadWriter] that dispatches to r and w. +func NewReadWriter(r *Reader, w *Writer) *ReadWriter { + return &ReadWriter{r, w} +} diff --git a/go/src/bufio/bufio_test.go b/go/src/bufio/bufio_test.go new file mode 100644 index 0000000000000000000000000000000000000000..742e195425690332dcf32487df3834e04a4a38ea --- /dev/null +++ b/go/src/bufio/bufio_test.go @@ -0,0 +1,1999 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bufio_test + +import ( + . "bufio" + "bytes" + "errors" + "fmt" + "internal/asan" + "io" + "math/rand" + "strconv" + "strings" + "testing" + "testing/iotest" + "time" + "unicode/utf8" +) + +// Reads from a reader and rot13s the result. +type rot13Reader struct { + r io.Reader +} + +func newRot13Reader(r io.Reader) *rot13Reader { + r13 := new(rot13Reader) + r13.r = r + return r13 +} + +func (r13 *rot13Reader) Read(p []byte) (int, error) { + n, err := r13.r.Read(p) + for i := 0; i < n; i++ { + c := p[i] | 0x20 // lowercase byte + if 'a' <= c && c <= 'm' { + p[i] += 13 + } else if 'n' <= c && c <= 'z' { + p[i] -= 13 + } + } + return n, err +} + +// Call ReadByte to accumulate the text of a file +func readBytes(buf *Reader) string { + var b [1000]byte + nb := 0 + for { + c, err := buf.ReadByte() + if err == io.EOF { + break + } + if err == nil { + b[nb] = c + nb++ + } else if err != iotest.ErrTimeout { + panic("Data: " + err.Error()) + } + } + return string(b[0:nb]) +} + +func TestReaderSimple(t *testing.T) { + data := "hello world" + b := NewReader(strings.NewReader(data)) + if s := readBytes(b); s != "hello world" { + t.Errorf("simple hello world test failed: got %q", s) + } + + b = NewReader(newRot13Reader(strings.NewReader(data))) + if s := readBytes(b); s != "uryyb jbeyq" { + t.Errorf("rot13 hello world test failed: got %q", s) + } +} + +type readMaker struct { + name string + fn func(io.Reader) io.Reader +} + +var readMakers = []readMaker{ + {"full", func(r io.Reader) io.Reader { return r }}, + {"byte", iotest.OneByteReader}, + {"half", iotest.HalfReader}, + {"data+err", iotest.DataErrReader}, + {"timeout", iotest.TimeoutReader}, +} + +// Call ReadString (which ends up calling everything else) +// to accumulate the text of a file. +func readLines(b *Reader) string { + s := "" + for { + s1, err := b.ReadString('\n') + if err == io.EOF { + break + } + if err != nil && err != iotest.ErrTimeout { + panic("GetLines: " + err.Error()) + } + s += s1 + } + return s +} + +// Call Read to accumulate the text of a file +func reads(buf *Reader, m int) string { + var b [1000]byte + nb := 0 + for { + n, err := buf.Read(b[nb : nb+m]) + nb += n + if err == io.EOF { + break + } + } + return string(b[0:nb]) +} + +type bufReader struct { + name string + fn func(*Reader) string +} + +var bufreaders = []bufReader{ + {"1", func(b *Reader) string { return reads(b, 1) }}, + {"2", func(b *Reader) string { return reads(b, 2) }}, + {"3", func(b *Reader) string { return reads(b, 3) }}, + {"4", func(b *Reader) string { return reads(b, 4) }}, + {"5", func(b *Reader) string { return reads(b, 5) }}, + {"7", func(b *Reader) string { return reads(b, 7) }}, + {"bytes", readBytes}, + {"lines", readLines}, +} + +const minReadBufferSize = 16 + +var bufsizes = []int{ + 0, minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096, +} + +func TestReader(t *testing.T) { + var texts [31]string + str := "" + all := "" + for i := 0; i < len(texts)-1; i++ { + texts[i] = str + "\n" + all += texts[i] + str += string(rune(i%26 + 'a')) + } + texts[len(texts)-1] = all + + for h := 0; h < len(texts); h++ { + text := texts[h] + for i := 0; i < len(readMakers); i++ { + for j := 0; j < len(bufreaders); j++ { + for k := 0; k < len(bufsizes); k++ { + readmaker := readMakers[i] + bufreader := bufreaders[j] + bufsize := bufsizes[k] + read := readmaker.fn(strings.NewReader(text)) + buf := NewReaderSize(read, bufsize) + s := bufreader.fn(buf) + if s != text { + t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q", + readmaker.name, bufreader.name, bufsize, text, s) + } + } + } + } + } +} + +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + return 0, nil +} + +func TestZeroReader(t *testing.T) { + var z zeroReader + r := NewReader(z) + + c := make(chan error) + go func() { + _, err := r.ReadByte() + c <- err + }() + + select { + case err := <-c: + if err == nil { + t.Error("error expected") + } else if err != io.ErrNoProgress { + t.Error("unexpected error:", err) + } + case <-time.After(time.Second): + t.Error("test timed out (endless loop in ReadByte?)") + } +} + +// A StringReader delivers its data one string segment at a time via Read. +type StringReader struct { + data []string + step int +} + +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 = io.EOF + } + return +} + +func readRuneSegments(t *testing.T, segments []string) { + got := "" + want := strings.Join(segments, "") + r := NewReader(&StringReader{data: segments}) + for { + r, _, err := r.ReadRune() + if err != nil { + if err != io.EOF { + return + } + break + } + got += string(r) + } + if got != want { + t.Errorf("segments=%v got=%s want=%s", segments, got, want) + } +} + +var segmentList = [][]string{ + {}, + {""}, + {"日", "本語"}, + {"\u65e5", "\u672c", "\u8a9e"}, + {"\U000065e5", "\U0000672c", "\U00008a9e"}, + {"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"}, + {"Hello", ", ", "World", "!"}, + {"Hello", ", ", "", "World", "!"}, +} + +func TestReadRune(t *testing.T) { + for _, s := range segmentList { + readRuneSegments(t, s) + } +} + +func TestUnreadRune(t *testing.T) { + segments := []string{"Hello, world:", "日本語"} + r := NewReader(&StringReader{data: segments}) + got := "" + want := strings.Join(segments, "") + // Normal execution. + for { + r1, _, err := r.ReadRune() + if err != nil { + if err != io.EOF { + t.Error("unexpected error on ReadRune:", err) + } + break + } + got += string(r1) + // Put it back and read it again. + if err = r.UnreadRune(); err != nil { + t.Fatal("unexpected error on UnreadRune:", err) + } + r2, _, err := r.ReadRune() + if err != nil { + t.Fatal("unexpected error reading after unreading:", err) + } + if r1 != r2 { + t.Fatalf("incorrect rune after unread: got %c, want %c", r1, r2) + } + } + if got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +func TestNoUnreadRuneAfterPeek(t *testing.T) { + br := NewReader(strings.NewReader("example")) + br.ReadRune() + br.Peek(1) + if err := br.UnreadRune(); err == nil { + t.Error("UnreadRune didn't fail after Peek") + } +} + +func TestNoUnreadByteAfterPeek(t *testing.T) { + br := NewReader(strings.NewReader("example")) + br.ReadByte() + br.Peek(1) + if err := br.UnreadByte(); err == nil { + t.Error("UnreadByte didn't fail after Peek") + } +} + +func TestNoUnreadRuneAfterDiscard(t *testing.T) { + br := NewReader(strings.NewReader("example")) + br.ReadRune() + br.Discard(1) + if err := br.UnreadRune(); err == nil { + t.Error("UnreadRune didn't fail after Discard") + } +} + +func TestNoUnreadByteAfterDiscard(t *testing.T) { + br := NewReader(strings.NewReader("example")) + br.ReadByte() + br.Discard(1) + if err := br.UnreadByte(); err == nil { + t.Error("UnreadByte didn't fail after Discard") + } +} + +func TestNoUnreadRuneAfterWriteTo(t *testing.T) { + br := NewReader(strings.NewReader("example")) + br.WriteTo(io.Discard) + if err := br.UnreadRune(); err == nil { + t.Error("UnreadRune didn't fail after WriteTo") + } +} + +func TestNoUnreadByteAfterWriteTo(t *testing.T) { + br := NewReader(strings.NewReader("example")) + br.WriteTo(io.Discard) + if err := br.UnreadByte(); err == nil { + t.Error("UnreadByte didn't fail after WriteTo") + } +} + +func TestUnreadByte(t *testing.T) { + segments := []string{"Hello, ", "world"} + r := NewReader(&StringReader{data: segments}) + got := "" + want := strings.Join(segments, "") + // Normal execution. + for { + b1, err := r.ReadByte() + if err != nil { + if err != io.EOF { + t.Error("unexpected error on ReadByte:", err) + } + break + } + got += string(b1) + // Put it back and read it again. + if err = r.UnreadByte(); err != nil { + t.Fatal("unexpected error on UnreadByte:", err) + } + b2, err := r.ReadByte() + if err != nil { + t.Fatal("unexpected error reading after unreading:", err) + } + if b1 != b2 { + t.Fatalf("incorrect byte after unread: got %q, want %q", b1, b2) + } + } + if got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +func TestUnreadByteMultiple(t *testing.T) { + segments := []string{"Hello, ", "world"} + data := strings.Join(segments, "") + for n := 0; n <= len(data); n++ { + r := NewReader(&StringReader{data: segments}) + // Read n bytes. + for i := 0; i < n; i++ { + b, err := r.ReadByte() + if err != nil { + t.Fatalf("n = %d: unexpected error on ReadByte: %v", n, err) + } + if b != data[i] { + t.Fatalf("n = %d: incorrect byte returned from ReadByte: got %q, want %q", n, b, data[i]) + } + } + // Unread one byte if there is one. + if n > 0 { + if err := r.UnreadByte(); err != nil { + t.Errorf("n = %d: unexpected error on UnreadByte: %v", n, err) + } + } + // Test that we cannot unread any further. + if err := r.UnreadByte(); err == nil { + t.Errorf("n = %d: expected error on UnreadByte", n) + } + } +} + +func TestUnreadByteOthers(t *testing.T) { + // A list of readers to use in conjunction with UnreadByte. + var readers = []func(*Reader, byte) ([]byte, error){ + (*Reader).ReadBytes, + (*Reader).ReadSlice, + func(r *Reader, delim byte) ([]byte, error) { + data, err := r.ReadString(delim) + return []byte(data), err + }, + // ReadLine doesn't fit the data/pattern easily + // so we leave it out. It should be covered via + // the ReadSlice test since ReadLine simply calls + // ReadSlice, and it's that function that handles + // the last byte. + } + + // Try all readers with UnreadByte. + for rno, read := range readers { + // Some input data that is longer than the minimum reader buffer size. + const n = 10 + var buf bytes.Buffer + for i := 0; i < n; i++ { + buf.WriteString("abcdefg") + } + + r := NewReaderSize(&buf, minReadBufferSize) + readTo := func(delim byte, want string) { + data, err := read(r, delim) + if err != nil { + t.Fatalf("#%d: unexpected error reading to %c: %v", rno, delim, err) + } + if got := string(data); got != want { + t.Fatalf("#%d: got %q, want %q", rno, got, want) + } + } + + // Read the data with occasional UnreadByte calls. + for i := 0; i < n; i++ { + readTo('d', "abcd") + for j := 0; j < 3; j++ { + if err := r.UnreadByte(); err != nil { + t.Fatalf("#%d: unexpected error on UnreadByte: %v", rno, err) + } + readTo('d', "d") + } + readTo('g', "efg") + } + + // All data should have been read. + _, err := r.ReadByte() + if err != io.EOF { + t.Errorf("#%d: got error %v; want EOF", rno, err) + } + } +} + +// Test that UnreadRune fails if the preceding operation was not a ReadRune. +func TestUnreadRuneError(t *testing.T) { + buf := make([]byte, 3) // All runes in this test are 3 bytes long + r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}}) + if r.UnreadRune() == nil { + t.Error("expected error on UnreadRune from fresh buffer") + } + _, _, err := r.ReadRune() + if err != nil { + t.Error("unexpected error on ReadRune (1):", err) + } + if err = r.UnreadRune(); err != nil { + t.Error("unexpected error on UnreadRune (1):", err) + } + if r.UnreadRune() == nil { + t.Error("expected error after UnreadRune (1)") + } + // Test error after Read. + _, _, err = r.ReadRune() // reset state + if err != nil { + t.Error("unexpected error on ReadRune (2):", err) + } + _, err = r.Read(buf) + if err != nil { + t.Error("unexpected error on Read (2):", err) + } + if r.UnreadRune() == nil { + t.Error("expected error after Read (2)") + } + // Test error after ReadByte. + _, _, err = r.ReadRune() // reset state + if err != nil { + t.Error("unexpected error on ReadRune (2):", err) + } + for range buf { + _, err = r.ReadByte() + if err != nil { + t.Error("unexpected error on ReadByte (2):", err) + } + } + if r.UnreadRune() == nil { + t.Error("expected error after ReadByte") + } + // Test error after UnreadByte. + _, _, err = r.ReadRune() // reset state + if err != nil { + t.Error("unexpected error on ReadRune (3):", err) + } + _, err = r.ReadByte() + if err != nil { + t.Error("unexpected error on ReadByte (3):", err) + } + err = r.UnreadByte() + if err != nil { + t.Error("unexpected error on UnreadByte (3):", err) + } + if r.UnreadRune() == nil { + t.Error("expected error after UnreadByte (3)") + } + // Test error after ReadSlice. + _, _, err = r.ReadRune() // reset state + if err != nil { + t.Error("unexpected error on ReadRune (4):", err) + } + _, err = r.ReadSlice(0) + if err != io.EOF { + t.Error("unexpected error on ReadSlice (4):", err) + } + if r.UnreadRune() == nil { + t.Error("expected error after ReadSlice (4)") + } +} + +func TestUnreadRuneAtEOF(t *testing.T) { + // UnreadRune/ReadRune should error at EOF (was a bug; used to panic) + r := NewReader(strings.NewReader("x")) + r.ReadRune() + r.ReadRune() + r.UnreadRune() + _, _, err := r.ReadRune() + if err == nil { + t.Error("expected error at EOF") + } else if err != io.EOF { + t.Error("expected EOF; got", err) + } +} + +func TestReadWriteRune(t *testing.T) { + const NRune = 1000 + byteBuf := new(bytes.Buffer) + w := NewWriter(byteBuf) + // Write the runes out using WriteRune + buf := make([]byte, utf8.UTFMax) + for r := rune(0); r < NRune; r++ { + size := utf8.EncodeRune(buf, r) + nbytes, err := w.WriteRune(r) + if err != nil { + t.Fatalf("WriteRune(0x%x) error: %s", r, err) + } + if nbytes != size { + t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes) + } + } + w.Flush() + + r := NewReader(byteBuf) + // Read them back with ReadRune + for r1 := rune(0); r1 < NRune; r1++ { + size := utf8.EncodeRune(buf, r1) + nr, nbytes, err := r.ReadRune() + if nr != r1 || nbytes != size || err != nil { + t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err) + } + } +} + +func TestWriteInvalidRune(t *testing.T) { + // Invalid runes, including negative ones, should be written as the + // replacement character. + for _, r := range []rune{-1, utf8.MaxRune + 1} { + var buf strings.Builder + w := NewWriter(&buf) + w.WriteRune(r) + w.Flush() + if s := buf.String(); s != "\uFFFD" { + t.Errorf("WriteRune(%d) wrote %q, not replacement character", r, s) + } + } +} + +func TestReadStringAllocs(t *testing.T) { + if asan.Enabled { + t.Skip("test allocates more with -asan; see #70079") + } + r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n") + buf := NewReader(r) + allocs := testing.AllocsPerRun(100, func() { + r.Seek(0, io.SeekStart) + buf.Reset(r) + + _, err := buf.ReadString('\n') + if err != nil { + t.Fatal(err) + } + }) + if allocs != 1 { + t.Errorf("Unexpected number of allocations, got %f, want 1", allocs) + } +} + +func TestWriter(t *testing.T) { + var data [8192]byte + + for i := 0; i < len(data); i++ { + data[i] = byte(' ' + i%('~'-' ')) + } + w := new(bytes.Buffer) + for i := 0; i < len(bufsizes); i++ { + for j := 0; j < len(bufsizes); j++ { + nwrite := bufsizes[i] + bs := bufsizes[j] + + // Write nwrite bytes using buffer size bs. + // Check that the right amount makes it out + // and that the data is correct. + + w.Reset() + buf := NewWriterSize(w, bs) + context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs) + n, e1 := buf.Write(data[0:nwrite]) + if e1 != nil || n != nwrite { + t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1) + continue + } + if e := buf.Flush(); e != nil { + t.Errorf("%s: buf.Flush = %v", context, e) + } + + written := w.Bytes() + if len(written) != nwrite { + t.Errorf("%s: %d bytes written", context, len(written)) + } + for l := 0; l < len(written); l++ { + if written[l] != data[l] { + t.Errorf("wrong bytes written") + t.Errorf("want=%q", data[:len(written)]) + t.Errorf("have=%q", written) + } + } + } + } +} + +func TestWriterAppend(t *testing.T) { + got := new(bytes.Buffer) + var want []byte + rn := rand.New(rand.NewSource(0)) + w := NewWriterSize(got, 64) + for i := 0; i < 100; i++ { + // Obtain a buffer to append to. + b := w.AvailableBuffer() + if w.Available() != cap(b) { + t.Fatalf("Available() = %v, want %v", w.Available(), cap(b)) + } + + // While not recommended, it is valid to append to a shifted buffer. + // This forces Write to copy the input. + if rn.Intn(8) == 0 && cap(b) > 0 { + b = b[1:1:cap(b)] + } + + // Append a random integer of varying width. + n := int64(rn.Intn(1 << rn.Intn(30))) + want = append(strconv.AppendInt(want, n, 10), ' ') + b = append(strconv.AppendInt(b, n, 10), ' ') + w.Write(b) + } + w.Flush() + + if !bytes.Equal(got.Bytes(), want) { + t.Errorf("output mismatch:\ngot %s\nwant %s", got.Bytes(), want) + } +} + +// Check that write errors are returned properly. + +type errorWriterTest struct { + n, m int + err error + expect error +} + +func (w errorWriterTest) Write(p []byte) (int, error) { + return len(p) * w.n / w.m, w.err +} + +var errorWriterTests = []errorWriterTest{ + {0, 1, nil, io.ErrShortWrite}, + {1, 2, nil, io.ErrShortWrite}, + {1, 1, nil, nil}, + {0, 1, io.ErrClosedPipe, io.ErrClosedPipe}, + {1, 2, io.ErrClosedPipe, io.ErrClosedPipe}, + {1, 1, io.ErrClosedPipe, io.ErrClosedPipe}, +} + +func TestWriteErrors(t *testing.T) { + for _, w := range errorWriterTests { + buf := NewWriter(w) + _, e := buf.Write([]byte("hello world")) + if e != nil { + t.Errorf("Write hello to %v: %v", w, e) + continue + } + // Two flushes, to verify the error is sticky. + for i := 0; i < 2; i++ { + e = buf.Flush() + if e != w.expect { + t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect) + } + } + } +} + +func TestNewReaderSizeIdempotent(t *testing.T) { + const BufSize = 1000 + b := NewReaderSize(strings.NewReader("hello world"), BufSize) + // Does it recognize itself? + b1 := NewReaderSize(b, BufSize) + if b1 != b { + t.Error("NewReaderSize did not detect underlying Reader") + } + // Does it wrap if existing buffer is too small? + b2 := NewReaderSize(b, 2*BufSize) + if b2 == b { + t.Error("NewReaderSize did not enlarge buffer") + } +} + +func TestNewWriterSizeIdempotent(t *testing.T) { + const BufSize = 1000 + b := NewWriterSize(new(bytes.Buffer), BufSize) + // Does it recognize itself? + b1 := NewWriterSize(b, BufSize) + if b1 != b { + t.Error("NewWriterSize did not detect underlying Writer") + } + // Does it wrap if existing buffer is too small? + b2 := NewWriterSize(b, 2*BufSize) + if b2 == b { + t.Error("NewWriterSize did not enlarge buffer") + } +} + +func TestWriteString(t *testing.T) { + const BufSize = 8 + buf := new(strings.Builder) + b := NewWriterSize(buf, BufSize) + b.WriteString("0") // easy + b.WriteString("123456") // still easy + b.WriteString("7890") // easy after flush + b.WriteString("abcdefghijklmnopqrstuvwxy") // hard + b.WriteString("z") + if err := b.Flush(); err != nil { + t.Error("WriteString", err) + } + s := "01234567890abcdefghijklmnopqrstuvwxyz" + if buf.String() != s { + t.Errorf("WriteString wants %q gets %q", s, buf.String()) + } +} + +func TestWriteStringStringWriter(t *testing.T) { + const BufSize = 8 + { + tw := &teststringwriter{} + b := NewWriterSize(tw, BufSize) + b.WriteString("1234") + tw.check(t, "", "") + b.WriteString("56789012") // longer than BufSize + tw.check(t, "12345678", "") // but not enough (after filling the partially-filled buffer) + b.Flush() + tw.check(t, "123456789012", "") + } + { + tw := &teststringwriter{} + b := NewWriterSize(tw, BufSize) + b.WriteString("123456789") // long string, empty buffer: + tw.check(t, "", "123456789") // use WriteString + } + { + tw := &teststringwriter{} + b := NewWriterSize(tw, BufSize) + b.WriteString("abc") + tw.check(t, "", "") + b.WriteString("123456789012345") // long string, non-empty buffer + tw.check(t, "abc12345", "6789012345") // use Write and then WriteString since the remaining part is still longer than BufSize + } + { + tw := &teststringwriter{} + b := NewWriterSize(tw, BufSize) + b.Write([]byte("abc")) // same as above, but use Write instead of WriteString + tw.check(t, "", "") + b.WriteString("123456789012345") + tw.check(t, "abc12345", "6789012345") // same as above + } +} + +type teststringwriter struct { + write string + writeString string +} + +func (w *teststringwriter) Write(b []byte) (int, error) { + w.write += string(b) + return len(b), nil +} + +func (w *teststringwriter) WriteString(s string) (int, error) { + w.writeString += s + return len(s), nil +} + +func (w *teststringwriter) check(t *testing.T, write, writeString string) { + t.Helper() + if w.write != write { + t.Errorf("write: expected %q, got %q", write, w.write) + } + if w.writeString != writeString { + t.Errorf("writeString: expected %q, got %q", writeString, w.writeString) + } +} + +func TestBufferFull(t *testing.T) { + const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party" + buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize) + line, err := buf.ReadSlice('!') + if string(line) != "And now, hello, " || err != ErrBufferFull { + t.Errorf("first ReadSlice(,) = %q, %v", line, err) + } + line, err = buf.ReadSlice('!') + if string(line) != "world!" || err != nil { + t.Errorf("second ReadSlice(,) = %q, %v", line, err) + } +} + +func TestPeek(t *testing.T) { + p := make([]byte, 10) + // string is 16 (minReadBufferSize) long. + buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize) + if s, err := buf.Peek(1); string(s) != "a" || err != nil { + t.Fatalf("want %q got %q, err=%v", "a", string(s), err) + } + if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { + t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err) + } + if _, err := buf.Peek(-1); err != ErrNegativeCount { + t.Fatalf("want ErrNegativeCount got %v", err) + } + if s, err := buf.Peek(32); string(s) != "abcdefghijklmnop" || err != ErrBufferFull { + t.Fatalf("want %q, ErrBufFull got %q, err=%v", "abcdefghijklmnop", string(s), err) + } + if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil { + t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err) + } + if s, err := buf.Peek(1); string(s) != "d" || err != nil { + t.Fatalf("want %q got %q, err=%v", "d", string(s), err) + } + if s, err := buf.Peek(2); string(s) != "de" || err != nil { + t.Fatalf("want %q got %q, err=%v", "de", string(s), err) + } + if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil { + t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err) + } + if s, err := buf.Peek(4); string(s) != "ghij" || err != nil { + t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err) + } + if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil { + t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err) + } + if s, err := buf.Peek(0); string(s) != "" || err != nil { + t.Fatalf("want %q got %q, err=%v", "", string(s), err) + } + if _, err := buf.Peek(1); err != io.EOF { + t.Fatalf("want EOF got %v", err) + } + + // Test for issue 3022, not exposing a reader's error on a successful Peek. + buf = NewReaderSize(dataAndEOFReader("abcd"), 32) + if s, err := buf.Peek(2); string(s) != "ab" || err != nil { + t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) + } + if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { + t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) + } + if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { + t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) + } + if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { + t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) + } +} + +type dataAndEOFReader string + +func (r dataAndEOFReader) Read(p []byte) (int, error) { + return copy(p, r), io.EOF +} + +func TestPeekThenUnreadRune(t *testing.T) { + // This sequence used to cause a crash. + r := NewReader(strings.NewReader("x")) + r.ReadRune() + r.Peek(1) + r.UnreadRune() + r.ReadRune() // Used to panic here +} + +var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy") +var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy") +var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n") + +// TestReader wraps a []byte and returns reads of a specific length. +type testReader struct { + data []byte + stride int +} + +func (t *testReader) Read(buf []byte) (n int, err error) { + n = t.stride + if n > len(t.data) { + n = len(t.data) + } + if n > len(buf) { + n = len(buf) + } + copy(buf, t.data) + t.data = t.data[n:] + if len(t.data) == 0 { + err = io.EOF + } + return +} + +func testReadLine(t *testing.T, input []byte) { + for stride := 1; stride < 2; stride++ { + done := 0 + reader := testReader{input, stride} + l := NewReaderSize(&reader, len(input)+1) + for { + line, isPrefix, err := l.ReadLine() + if len(line) > 0 && err != nil { + t.Errorf("ReadLine returned both data and error: %s", err) + } + if isPrefix { + t.Errorf("ReadLine returned prefix") + } + if err != nil { + if err != io.EOF { + t.Fatalf("Got unknown error: %s", err) + } + break + } + if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) { + t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line) + } + done += len(line) + } + if done != len(testOutput) { + t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride) + } + } +} + +func TestReadLine(t *testing.T) { + testReadLine(t, testInput) + testReadLine(t, testInputrn) +} + +func TestLineTooLong(t *testing.T) { + data := make([]byte, 0) + for i := 0; i < minReadBufferSize*5/2; i++ { + data = append(data, '0'+byte(i%10)) + } + buf := bytes.NewReader(data) + l := NewReaderSize(buf, minReadBufferSize) + line, isPrefix, err := l.ReadLine() + if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil { + t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err) + } + data = data[len(line):] + line, isPrefix, err = l.ReadLine() + if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil { + t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err) + } + data = data[len(line):] + line, isPrefix, err = l.ReadLine() + if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil { + t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err) + } + line, isPrefix, err = l.ReadLine() + if isPrefix || err == nil { + t.Errorf("expected no more lines: %x %s", line, err) + } +} + +func TestReadAfterLines(t *testing.T) { + line1 := "this is line1" + restData := "this is line2\nthis is line 3\n" + inbuf := bytes.NewReader([]byte(line1 + "\n" + restData)) + outbuf := new(strings.Builder) + maxLineLength := len(line1) + len(restData)/2 + l := NewReaderSize(inbuf, maxLineLength) + line, isPrefix, err := l.ReadLine() + if isPrefix || err != nil || string(line) != line1 { + t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line)) + } + n, err := io.Copy(outbuf, l) + if int(n) != len(restData) || err != nil { + t.Errorf("bad result for Read: n=%d err=%v", n, err) + } + if outbuf.String() != restData { + t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData) + } +} + +func TestReadEmptyBuffer(t *testing.T) { + l := NewReaderSize(new(bytes.Buffer), minReadBufferSize) + line, isPrefix, err := l.ReadLine() + if err != io.EOF { + t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) + } +} + +func TestLinesAfterRead(t *testing.T) { + l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize) + _, err := io.ReadAll(l) + if err != nil { + t.Error(err) + return + } + + line, isPrefix, err := l.ReadLine() + if err != io.EOF { + t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) + } +} + +func TestReadLineNonNilLineOrError(t *testing.T) { + r := NewReader(strings.NewReader("line 1\n")) + for i := 0; i < 2; i++ { + l, _, err := r.ReadLine() + if l != nil && err != nil { + t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both", + i+1, l, err) + } + } +} + +type readLineResult struct { + line []byte + isPrefix bool + err error +} + +var readLineNewlinesTests = []struct { + input string + expect []readLineResult +}{ + {"012345678901234\r\n012345678901234\r\n", []readLineResult{ + {[]byte("012345678901234"), true, nil}, + {nil, false, nil}, + {[]byte("012345678901234"), true, nil}, + {nil, false, nil}, + {nil, false, io.EOF}, + }}, + {"0123456789012345\r012345678901234\r", []readLineResult{ + {[]byte("0123456789012345"), true, nil}, + {[]byte("\r012345678901234"), true, nil}, + {[]byte("\r"), false, nil}, + {nil, false, io.EOF}, + }}, +} + +func TestReadLineNewlines(t *testing.T) { + for _, e := range readLineNewlinesTests { + testReadLineNewlines(t, e.input, e.expect) + } +} + +func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) { + b := NewReaderSize(strings.NewReader(input), minReadBufferSize) + for i, e := range expect { + line, isPrefix, err := b.ReadLine() + if !bytes.Equal(line, e.line) { + t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line) + return + } + if isPrefix != e.isPrefix { + t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix) + return + } + if err != e.err { + t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err) + return + } + } +} + +func createTestInput(n int) []byte { + input := make([]byte, n) + for i := range input { + // 101 and 251 are arbitrary prime numbers. + // The idea is to create an input sequence + // which doesn't repeat too frequently. + input[i] = byte(i % 251) + if i%101 == 0 { + input[i] ^= byte(i / 101) + } + } + return input +} + +func TestReaderWriteTo(t *testing.T) { + input := createTestInput(8192) + r := NewReader(onlyReader{bytes.NewReader(input)}) + w := new(bytes.Buffer) + if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) { + t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input)) + } + + for i, val := range w.Bytes() { + if val != input[i] { + t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i]) + } + } +} + +type errorWriterToTest struct { + rn, wn int + rerr, werr error + expected error +} + +func (r errorWriterToTest) Read(p []byte) (int, error) { + return len(p) * r.rn, r.rerr +} + +func (w errorWriterToTest) Write(p []byte) (int, error) { + return len(p) * w.wn, w.werr +} + +var errorWriterToTests = []errorWriterToTest{ + {1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe}, + {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe}, + {0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrUnexpectedEOF}, + {0, 1, io.EOF, nil, nil}, +} + +func TestReaderWriteToErrors(t *testing.T) { + for i, rw := range errorWriterToTests { + r := NewReader(rw) + if _, err := r.WriteTo(rw); err != rw.expected { + t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected) + } + } +} + +func TestWriterReadFrom(t *testing.T) { + ws := []func(io.Writer) io.Writer{ + func(w io.Writer) io.Writer { return onlyWriter{w} }, + func(w io.Writer) io.Writer { return w }, + } + + rs := []func(io.Reader) io.Reader{ + iotest.DataErrReader, + func(r io.Reader) io.Reader { return r }, + } + + for ri, rfunc := range rs { + for wi, wfunc := range ws { + input := createTestInput(8192) + b := new(strings.Builder) + w := NewWriter(wfunc(b)) + r := rfunc(bytes.NewReader(input)) + if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) { + t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input)) + continue + } + if err := w.Flush(); err != nil { + t.Errorf("Flush returned %v", err) + continue + } + if got, want := b.String(), string(input); got != want { + t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want) + } + } + } +} + +type errorReaderFromTest struct { + rn, wn int + rerr, werr error + expected error +} + +func (r errorReaderFromTest) Read(p []byte) (int, error) { + return len(p) * r.rn, r.rerr +} + +func (w errorReaderFromTest) Write(p []byte) (int, error) { + return len(p) * w.wn, w.werr +} + +var errorReaderFromTests = []errorReaderFromTest{ + {0, 1, io.EOF, nil, nil}, + {1, 1, io.EOF, nil, nil}, + {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe}, + {0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe}, + {1, 0, nil, io.ErrShortWrite, io.ErrShortWrite}, +} + +func TestWriterReadFromErrors(t *testing.T) { + for i, rw := range errorReaderFromTests { + w := NewWriter(rw) + if _, err := w.ReadFrom(rw); err != rw.expected { + t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected) + } + } +} + +// TestWriterReadFromCounts tests that using io.Copy to copy into a +// bufio.Writer does not prematurely flush the buffer. For example, when +// buffering writes to a network socket, excessive network writes should be +// avoided. +func TestWriterReadFromCounts(t *testing.T) { + var w0 writeCountingDiscard + b0 := NewWriterSize(&w0, 1234) + b0.WriteString(strings.Repeat("x", 1000)) + if w0 != 0 { + t.Fatalf("write 1000 'x's: got %d writes, want 0", w0) + } + b0.WriteString(strings.Repeat("x", 200)) + if w0 != 0 { + t.Fatalf("write 1200 'x's: got %d writes, want 0", w0) + } + io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))}) + if w0 != 0 { + t.Fatalf("write 1230 'x's: got %d writes, want 0", w0) + } + io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))}) + if w0 != 1 { + t.Fatalf("write 1239 'x's: got %d writes, want 1", w0) + } + + var w1 writeCountingDiscard + b1 := NewWriterSize(&w1, 1234) + b1.WriteString(strings.Repeat("x", 1200)) + b1.Flush() + if w1 != 1 { + t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1) + } + b1.WriteString(strings.Repeat("x", 89)) + if w1 != 1 { + t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1) + } + io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))}) + if w1 != 1 { + t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1) + } + io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))}) + if w1 != 2 { + t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1) + } + b1.Flush() + if w1 != 3 { + t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1) + } +} + +// A writeCountingDiscard is like io.Discard and counts the number of times +// Write is called on it. +type writeCountingDiscard int + +func (w *writeCountingDiscard) Write(p []byte) (int, error) { + *w++ + return len(p), nil +} + +type negativeReader int + +func (r *negativeReader) Read([]byte) (int, error) { return -1, nil } + +func TestNegativeRead(t *testing.T) { + // should panic with a description pointing at the reader, not at itself. + // (should NOT panic with slice index error, for example.) + b := NewReader(new(negativeReader)) + defer func() { + switch err := recover().(type) { + case nil: + t.Fatal("read did not panic") + case error: + if !strings.Contains(err.Error(), "reader returned negative count from Read") { + t.Fatalf("wrong panic: %v", err) + } + default: + t.Fatalf("unexpected panic value: %T(%v)", err, err) + } + }() + b.Read(make([]byte, 100)) +} + +var errFake = errors.New("fake error") + +type errorThenGoodReader struct { + didErr bool + nread int +} + +func (r *errorThenGoodReader) Read(p []byte) (int, error) { + r.nread++ + if !r.didErr { + r.didErr = true + return 0, errFake + } + return len(p), nil +} + +func TestReaderClearError(t *testing.T) { + r := &errorThenGoodReader{} + b := NewReader(r) + buf := make([]byte, 1) + if _, err := b.Read(nil); err != nil { + t.Fatalf("1st nil Read = %v; want nil", err) + } + if _, err := b.Read(buf); err != errFake { + t.Fatalf("1st Read = %v; want errFake", err) + } + if _, err := b.Read(nil); err != nil { + t.Fatalf("2nd nil Read = %v; want nil", err) + } + if _, err := b.Read(buf); err != nil { + t.Fatalf("3rd Read with buffer = %v; want nil", err) + } + if r.nread != 2 { + t.Errorf("num reads = %d; want 2", r.nread) + } +} + +// Test for golang.org/issue/5947 +func TestWriterReadFromWhileFull(t *testing.T) { + buf := new(bytes.Buffer) + w := NewWriterSize(buf, 10) + + // Fill buffer exactly. + n, err := w.Write([]byte("0123456789")) + if n != 10 || err != nil { + t.Fatalf("Write returned (%v, %v), want (10, nil)", n, err) + } + + // Use ReadFrom to read in some data. + n2, err := w.ReadFrom(strings.NewReader("abcdef")) + if n2 != 6 || err != nil { + t.Fatalf("ReadFrom returned (%v, %v), want (6, nil)", n2, err) + } +} + +type emptyThenNonEmptyReader struct { + r io.Reader + n int +} + +func (r *emptyThenNonEmptyReader) Read(p []byte) (int, error) { + if r.n <= 0 { + return r.r.Read(p) + } + r.n-- + return 0, nil +} + +// Test for golang.org/issue/7611 +func TestWriterReadFromUntilEOF(t *testing.T) { + buf := new(bytes.Buffer) + w := NewWriterSize(buf, 5) + + // Partially fill buffer + n, err := w.Write([]byte("0123")) + if n != 4 || err != nil { + t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err) + } + + // Use ReadFrom to read in some data. + r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 3} + n2, err := w.ReadFrom(r) + if n2 != 4 || err != nil { + t.Fatalf("ReadFrom returned (%v, %v), want (4, nil)", n2, err) + } + w.Flush() + if got, want := buf.String(), "0123abcd"; got != want { + t.Fatalf("buf.Bytes() returned %q, want %q", got, want) + } +} + +func TestWriterReadFromErrNoProgress(t *testing.T) { + buf := new(bytes.Buffer) + w := NewWriterSize(buf, 5) + + // Partially fill buffer + n, err := w.Write([]byte("0123")) + if n != 4 || err != nil { + t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err) + } + + // Use ReadFrom to read in some data. + r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 100} + n2, err := w.ReadFrom(r) + if n2 != 0 || err != io.ErrNoProgress { + t.Fatalf("buf.Bytes() returned (%v, %v), want (0, io.ErrNoProgress)", n2, err) + } +} + +type readFromWriter struct { + buf []byte + writeBytes int + readFromBytes int +} + +func (w *readFromWriter) Write(p []byte) (int, error) { + w.buf = append(w.buf, p...) + w.writeBytes += len(p) + return len(p), nil +} + +func (w *readFromWriter) ReadFrom(r io.Reader) (int64, error) { + b, err := io.ReadAll(r) + w.buf = append(w.buf, b...) + w.readFromBytes += len(b) + return int64(len(b)), err +} + +// Test that calling (*Writer).ReadFrom with a partially-filled buffer +// fills the buffer before switching over to ReadFrom. +func TestWriterReadFromWithBufferedData(t *testing.T) { + const bufsize = 16 + + input := createTestInput(64) + rfw := &readFromWriter{} + w := NewWriterSize(rfw, bufsize) + + const writeSize = 8 + if n, err := w.Write(input[:writeSize]); n != writeSize || err != nil { + t.Errorf("w.Write(%v bytes) = %v, %v; want %v, nil", writeSize, n, err, writeSize) + } + n, err := w.ReadFrom(bytes.NewReader(input[writeSize:])) + if wantn := len(input[writeSize:]); int(n) != wantn || err != nil { + t.Errorf("io.Copy(w, %v bytes) = %v, %v; want %v, nil", wantn, n, err, wantn) + } + if err := w.Flush(); err != nil { + t.Errorf("w.Flush() = %v, want nil", err) + } + + if got, want := rfw.writeBytes, bufsize; got != want { + t.Errorf("wrote %v bytes with Write, want %v", got, want) + } + if got, want := rfw.readFromBytes, len(input)-bufsize; got != want { + t.Errorf("wrote %v bytes with ReadFrom, want %v", got, want) + } +} + +func TestReadZero(t *testing.T) { + for _, size := range []int{100, 2} { + t.Run(fmt.Sprintf("bufsize=%d", size), func(t *testing.T) { + r := io.MultiReader(strings.NewReader("abc"), &emptyThenNonEmptyReader{r: strings.NewReader("def"), n: 1}) + br := NewReaderSize(r, size) + want := func(s string, wantErr error) { + p := make([]byte, 50) + n, err := br.Read(p) + if err != wantErr || n != len(s) || string(p[:n]) != s { + t.Fatalf("read(%d) = %q, %v, want %q, %v", len(p), string(p[:n]), err, s, wantErr) + } + t.Logf("read(%d) = %q, %v", len(p), string(p[:n]), err) + } + want("abc", nil) + want("", nil) + want("def", nil) + want("", io.EOF) + }) + } +} + +func TestReaderReset(t *testing.T) { + checkAll := func(r *Reader, want string) { + t.Helper() + all, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + if string(all) != want { + t.Errorf("ReadAll returned %q, want %q", all, want) + } + } + + r := NewReader(strings.NewReader("foo foo")) + buf := make([]byte, 3) + r.Read(buf) + if string(buf) != "foo" { + t.Errorf("buf = %q; want foo", buf) + } + + r.Reset(strings.NewReader("bar bar")) + checkAll(r, "bar bar") + + *r = Reader{} // zero out the Reader + r.Reset(strings.NewReader("bar bar")) + checkAll(r, "bar bar") + + // Wrap a reader and then Reset to that reader. + r.Reset(strings.NewReader("recur")) + r2 := NewReader(r) + checkAll(r2, "recur") + r.Reset(strings.NewReader("recur2")) + r2.Reset(r) + checkAll(r2, "recur2") +} + +func TestWriterReset(t *testing.T) { + var buf1, buf2, buf3, buf4, buf5 strings.Builder + w := NewWriter(&buf1) + w.WriteString("foo") + + w.Reset(&buf2) // and not flushed + w.WriteString("bar") + w.Flush() + if buf1.String() != "" { + t.Errorf("buf1 = %q; want empty", buf1.String()) + } + if buf2.String() != "bar" { + t.Errorf("buf2 = %q; want bar", buf2.String()) + } + + *w = Writer{} // zero out the Writer + w.Reset(&buf3) // and not flushed + w.WriteString("bar") + w.Flush() + if buf1.String() != "" { + t.Errorf("buf1 = %q; want empty", buf1.String()) + } + if buf3.String() != "bar" { + t.Errorf("buf3 = %q; want bar", buf3.String()) + } + + // Wrap a writer and then Reset to that writer. + w.Reset(&buf4) + w2 := NewWriter(w) + w2.WriteString("recur") + w2.Flush() + if buf4.String() != "recur" { + t.Errorf("buf4 = %q, want %q", buf4.String(), "recur") + } + w.Reset(&buf5) + w2.Reset(w) + w2.WriteString("recur2") + w2.Flush() + if buf5.String() != "recur2" { + t.Errorf("buf5 = %q, want %q", buf5.String(), "recur2") + } +} + +func TestReaderDiscard(t *testing.T) { + tests := []struct { + name string + r io.Reader + bufSize int // 0 means 16 + peekSize int + + n int // input to Discard + + want int // from Discard + wantErr error // from Discard + + wantBuffered int + }{ + { + name: "normal case", + r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"), + peekSize: 16, + n: 6, + want: 6, + wantBuffered: 10, + }, + { + name: "discard causing read", + r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"), + n: 6, + want: 6, + wantBuffered: 10, + }, + { + name: "discard all without peek", + r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"), + n: 26, + want: 26, + wantBuffered: 0, + }, + { + name: "discard more than end", + r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"), + n: 27, + want: 26, + wantErr: io.EOF, + wantBuffered: 0, + }, + // Any error from filling shouldn't show up until we + // get past the valid bytes. Here we return 5 valid bytes at the same time + // as an error, but test that we don't see the error from Discard. + { + name: "fill error, discard less", + r: newScriptedReader(func(p []byte) (n int, err error) { + if len(p) < 5 { + panic("unexpected small read") + } + return 5, errors.New("5-then-error") + }), + n: 4, + want: 4, + wantErr: nil, + wantBuffered: 1, + }, + { + name: "fill error, discard equal", + r: newScriptedReader(func(p []byte) (n int, err error) { + if len(p) < 5 { + panic("unexpected small read") + } + return 5, errors.New("5-then-error") + }), + n: 5, + want: 5, + wantErr: nil, + wantBuffered: 0, + }, + { + name: "fill error, discard more", + r: newScriptedReader(func(p []byte) (n int, err error) { + if len(p) < 5 { + panic("unexpected small read") + } + return 5, errors.New("5-then-error") + }), + n: 6, + want: 5, + wantErr: errors.New("5-then-error"), + wantBuffered: 0, + }, + // Discard of 0 shouldn't cause a read: + { + name: "discard zero", + r: newScriptedReader(), // will panic on Read + n: 0, + want: 0, + wantErr: nil, + wantBuffered: 0, + }, + { + name: "discard negative", + r: newScriptedReader(), // will panic on Read + n: -1, + want: 0, + wantErr: ErrNegativeCount, + wantBuffered: 0, + }, + } + for _, tt := range tests { + br := NewReaderSize(tt.r, tt.bufSize) + if tt.peekSize > 0 { + peekBuf, err := br.Peek(tt.peekSize) + if err != nil { + t.Errorf("%s: Peek(%d): %v", tt.name, tt.peekSize, err) + continue + } + if len(peekBuf) != tt.peekSize { + t.Errorf("%s: len(Peek(%d)) = %v; want %v", tt.name, tt.peekSize, len(peekBuf), tt.peekSize) + continue + } + } + discarded, err := br.Discard(tt.n) + if ge, we := fmt.Sprint(err), fmt.Sprint(tt.wantErr); discarded != tt.want || ge != we { + t.Errorf("%s: Discard(%d) = (%v, %v); want (%v, %v)", tt.name, tt.n, discarded, ge, tt.want, we) + continue + } + if bn := br.Buffered(); bn != tt.wantBuffered { + t.Errorf("%s: after Discard, Buffered = %d; want %d", tt.name, bn, tt.wantBuffered) + } + } + +} + +func TestReaderSize(t *testing.T) { + if got, want := NewReader(nil).Size(), DefaultBufSize; got != want { + t.Errorf("NewReader's Reader.Size = %d; want %d", got, want) + } + if got, want := NewReaderSize(nil, 1234).Size(), 1234; got != want { + t.Errorf("NewReaderSize's Reader.Size = %d; want %d", got, want) + } +} + +func TestWriterSize(t *testing.T) { + if got, want := NewWriter(nil).Size(), DefaultBufSize; got != want { + t.Errorf("NewWriter's Writer.Size = %d; want %d", got, want) + } + if got, want := NewWriterSize(nil, 1234).Size(), 1234; got != want { + t.Errorf("NewWriterSize's Writer.Size = %d; want %d", got, want) + } +} + +// An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have. +type onlyReader struct { + io.Reader +} + +// An onlyWriter only implements io.Writer, no matter what other methods the underlying implementation may have. +type onlyWriter struct { + io.Writer +} + +// A scriptedReader is an io.Reader that executes its steps sequentially. +type scriptedReader []func(p []byte) (n int, err error) + +func (sr *scriptedReader) Read(p []byte) (n int, err error) { + if len(*sr) == 0 { + panic("too many Read calls on scripted Reader. No steps remain.") + } + step := (*sr)[0] + *sr = (*sr)[1:] + return step(p) +} + +func newScriptedReader(steps ...func(p []byte) (n int, err error)) io.Reader { + sr := scriptedReader(steps) + return &sr +} + +// eofReader returns the number of bytes read and io.EOF for the read that consumes the last of the content. +type eofReader struct { + buf []byte +} + +func (r *eofReader) Read(p []byte) (int, error) { + read := copy(p, r.buf) + r.buf = r.buf[read:] + + switch read { + case 0, len(r.buf): + // As allowed in the documentation, this will return io.EOF + // in the same call that consumes the last of the data. + // https://godoc.org/io#Reader + return read, io.EOF + } + + return read, nil +} + +func TestPartialReadEOF(t *testing.T) { + src := make([]byte, 10) + eofR := &eofReader{buf: src} + r := NewReader(eofR) + + // Start by reading 5 of the 10 available bytes. + dest := make([]byte, 5) + read, err := r.Read(dest) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if n := len(dest); read != n { + t.Fatalf("read %d bytes; wanted %d bytes", read, n) + } + + // The Reader should have buffered all the content from the io.Reader. + if n := len(eofR.buf); n != 0 { + t.Fatalf("got %d bytes left in bufio.Reader source; want 0 bytes", n) + } + // To prove the point, check that there are still 5 bytes available to read. + if n := r.Buffered(); n != 5 { + t.Fatalf("got %d bytes buffered in bufio.Reader; want 5 bytes", n) + } + + // This is the second read of 0 bytes. + read, err = r.Read([]byte{}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if read != 0 { + t.Fatalf("read %d bytes; want 0 bytes", read) + } +} + +type writerWithReadFromError struct{} + +func (w writerWithReadFromError) ReadFrom(r io.Reader) (int64, error) { + return 0, errors.New("writerWithReadFromError error") +} + +func (w writerWithReadFromError) Write(b []byte) (n int, err error) { + return 10, nil +} + +func TestWriterReadFromMustSetUnderlyingError(t *testing.T) { + var wr = NewWriter(writerWithReadFromError{}) + if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil { + t.Fatal("expected ReadFrom returns error, got nil") + } + if _, err := wr.Write([]byte("123")); err == nil { + t.Fatal("expected Write returns error, got nil") + } +} + +type writeErrorOnlyWriter struct{} + +func (w writeErrorOnlyWriter) Write(p []byte) (n int, err error) { + return 0, errors.New("writeErrorOnlyWriter error") +} + +// Ensure that previous Write errors are immediately returned +// on any ReadFrom. See golang.org/issue/35194. +func TestWriterReadFromMustReturnUnderlyingError(t *testing.T) { + var wr = NewWriter(writeErrorOnlyWriter{}) + s := "test1" + wantBuffered := len(s) + if _, err := wr.WriteString(s); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if err := wr.Flush(); err == nil { + t.Error("expected flush error, got nil") + } + if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil { + t.Fatal("expected error, got nil") + } + if buffered := wr.Buffered(); buffered != wantBuffered { + t.Fatalf("Buffered = %v; want %v", buffered, wantBuffered) + } +} + +func BenchmarkReaderCopyOptimal(b *testing.B) { + // Optimal case is where the underlying reader implements io.WriterTo + srcBuf := bytes.NewBuffer(make([]byte, 8192)) + src := NewReader(srcBuf) + dstBuf := new(bytes.Buffer) + dst := onlyWriter{dstBuf} + for i := 0; i < b.N; i++ { + srcBuf.Reset() + src.Reset(srcBuf) + dstBuf.Reset() + io.Copy(dst, src) + } +} + +func BenchmarkReaderCopyUnoptimal(b *testing.B) { + // Unoptimal case is where the underlying reader doesn't implement io.WriterTo + srcBuf := bytes.NewBuffer(make([]byte, 8192)) + src := NewReader(onlyReader{srcBuf}) + dstBuf := new(bytes.Buffer) + dst := onlyWriter{dstBuf} + for i := 0; i < b.N; i++ { + srcBuf.Reset() + src.Reset(onlyReader{srcBuf}) + dstBuf.Reset() + io.Copy(dst, src) + } +} + +func BenchmarkReaderCopyNoWriteTo(b *testing.B) { + srcBuf := bytes.NewBuffer(make([]byte, 8192)) + srcReader := NewReader(srcBuf) + src := onlyReader{srcReader} + dstBuf := new(bytes.Buffer) + dst := onlyWriter{dstBuf} + for i := 0; i < b.N; i++ { + srcBuf.Reset() + srcReader.Reset(srcBuf) + dstBuf.Reset() + io.Copy(dst, src) + } +} + +func BenchmarkReaderWriteToOptimal(b *testing.B) { + const bufSize = 16 << 10 + buf := make([]byte, bufSize) + r := bytes.NewReader(buf) + srcReader := NewReaderSize(onlyReader{r}, 1<<10) + if _, ok := io.Discard.(io.ReaderFrom); !ok { + b.Fatal("io.Discard doesn't support ReaderFrom") + } + for i := 0; i < b.N; i++ { + r.Seek(0, io.SeekStart) + srcReader.Reset(onlyReader{r}) + n, err := srcReader.WriteTo(io.Discard) + if err != nil { + b.Fatal(err) + } + if n != bufSize { + b.Fatalf("n = %d; want %d", n, bufSize) + } + } +} + +func BenchmarkReaderReadString(b *testing.B) { + r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n") + buf := NewReader(r) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + r.Seek(0, io.SeekStart) + buf.Reset(r) + + _, err := buf.ReadString('\n') + if err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkWriterCopyOptimal(b *testing.B) { + // Optimal case is where the underlying writer implements io.ReaderFrom + srcBuf := bytes.NewBuffer(make([]byte, 8192)) + src := onlyReader{srcBuf} + dstBuf := new(bytes.Buffer) + dst := NewWriter(dstBuf) + for i := 0; i < b.N; i++ { + srcBuf.Reset() + dstBuf.Reset() + dst.Reset(dstBuf) + io.Copy(dst, src) + } +} + +func BenchmarkWriterCopyUnoptimal(b *testing.B) { + srcBuf := bytes.NewBuffer(make([]byte, 8192)) + src := onlyReader{srcBuf} + dstBuf := new(bytes.Buffer) + dst := NewWriter(onlyWriter{dstBuf}) + for i := 0; i < b.N; i++ { + srcBuf.Reset() + dstBuf.Reset() + dst.Reset(onlyWriter{dstBuf}) + io.Copy(dst, src) + } +} + +func BenchmarkWriterCopyNoReadFrom(b *testing.B) { + srcBuf := bytes.NewBuffer(make([]byte, 8192)) + src := onlyReader{srcBuf} + dstBuf := new(bytes.Buffer) + dstWriter := NewWriter(dstBuf) + dst := onlyWriter{dstWriter} + for i := 0; i < b.N; i++ { + srcBuf.Reset() + dstBuf.Reset() + dstWriter.Reset(dstBuf) + io.Copy(dst, src) + } +} + +func BenchmarkReaderEmpty(b *testing.B) { + b.ReportAllocs() + str := strings.Repeat("x", 16<<10) + for i := 0; i < b.N; i++ { + br := NewReader(strings.NewReader(str)) + n, err := io.Copy(io.Discard, br) + if err != nil { + b.Fatal(err) + } + if n != int64(len(str)) { + b.Fatal("wrong length") + } + } +} + +func BenchmarkWriterEmpty(b *testing.B) { + b.ReportAllocs() + str := strings.Repeat("x", 1<<10) + bs := []byte(str) + for i := 0; i < b.N; i++ { + bw := NewWriter(io.Discard) + bw.Flush() + bw.WriteByte('a') + bw.Flush() + bw.WriteRune('B') + bw.Flush() + bw.Write(bs) + bw.Flush() + bw.WriteString(str) + bw.Flush() + } +} + +func BenchmarkWriterFlush(b *testing.B) { + b.ReportAllocs() + bw := NewWriter(io.Discard) + str := strings.Repeat("x", 50) + for i := 0; i < b.N; i++ { + bw.WriteString(str) + bw.Flush() + } +} diff --git a/go/src/bufio/example_test.go b/go/src/bufio/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7d4f0c1c28dce2d27f7d74b974e5f4746818d716 --- /dev/null +++ b/go/src/bufio/example_test.go @@ -0,0 +1,200 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bufio_test + +import ( + "bufio" + "bytes" + "fmt" + "os" + "strconv" + "strings" +) + +func ExampleWriter() { + w := bufio.NewWriter(os.Stdout) + fmt.Fprint(w, "Hello, ") + fmt.Fprint(w, "world!") + w.Flush() // Don't forget to flush! + // Output: Hello, world! +} + +func ExampleWriter_AvailableBuffer() { + w := bufio.NewWriter(os.Stdout) + for _, i := range []int64{1, 2, 3, 4} { + b := w.AvailableBuffer() + b = strconv.AppendInt(b, i, 10) + b = append(b, ' ') + w.Write(b) + } + w.Flush() + // Output: 1 2 3 4 +} + +// ExampleWriter_ReadFrom demonstrates how to use the ReadFrom method of Writer. +func ExampleWriter_ReadFrom() { + var buf bytes.Buffer + writer := bufio.NewWriter(&buf) + + data := "Hello, world!\nThis is a ReadFrom example." + reader := strings.NewReader(data) + + n, err := writer.ReadFrom(reader) + if err != nil { + fmt.Println("ReadFrom Error:", err) + return + } + + if err = writer.Flush(); err != nil { + fmt.Println("Flush Error:", err) + return + } + + fmt.Println("Bytes written:", n) + fmt.Println("Buffer contents:", buf.String()) + // Output: + // Bytes written: 41 + // Buffer contents: Hello, world! + // This is a ReadFrom example. +} + +// The simplest use of a Scanner, to read standard input as a set of lines. +func ExampleScanner_lines() { + scanner := bufio.NewScanner(os.Stdin) + for scanner.Scan() { + fmt.Println(scanner.Text()) // Println will add back the final '\n' + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(os.Stderr, "reading standard input:", err) + } +} + +// Return the most recent call to Scan as a []byte. +func ExampleScanner_Bytes() { + scanner := bufio.NewScanner(strings.NewReader("gopher")) + for scanner.Scan() { + fmt.Println(len(scanner.Bytes()) == 6) + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string") + } + // Output: + // true +} + +// Use a Scanner to implement a simple word-count utility by scanning the +// input as a sequence of space-delimited tokens. +func ExampleScanner_words() { + // An artificial input source. + const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n" + scanner := bufio.NewScanner(strings.NewReader(input)) + // Set the split function for the scanning operation. + scanner.Split(bufio.ScanWords) + // Count the words. + count := 0 + for scanner.Scan() { + count++ + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(os.Stderr, "reading input:", err) + } + fmt.Printf("%d\n", count) + // Output: 15 +} + +// Use a Scanner with a custom split function (built by wrapping ScanWords) to validate +// 32-bit decimal input. +func ExampleScanner_custom() { + // An artificial input source. + const input = "1234 5678 1234567901234567890" + scanner := bufio.NewScanner(strings.NewReader(input)) + // Create a custom split function by wrapping the existing ScanWords function. + split := func(data []byte, atEOF bool) (advance int, token []byte, err error) { + advance, token, err = bufio.ScanWords(data, atEOF) + if err == nil && token != nil { + _, err = strconv.ParseInt(string(token), 10, 32) + } + return + } + // Set the split function for the scanning operation. + scanner.Split(split) + // Validate the input + for scanner.Scan() { + fmt.Printf("%s\n", scanner.Text()) + } + + if err := scanner.Err(); err != nil { + fmt.Printf("Invalid input: %s", err) + } + // Output: + // 1234 + // 5678 + // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range +} + +// Use a Scanner with a custom split function to parse a comma-separated +// list with an empty final value. +func ExampleScanner_emptyFinalToken() { + // Comma-separated list; last entry is empty. + const input = "1,2,3,4," + scanner := bufio.NewScanner(strings.NewReader(input)) + // Define a split function that separates on commas. + onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) { + for i := 0; i < len(data); i++ { + if data[i] == ',' { + return i + 1, data[:i], nil + } + } + if !atEOF { + return 0, nil, nil + } + // There is one final token to be delivered, which may be the empty string. + // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this + // but does not trigger an error to be returned from Scan itself. + return 0, data, bufio.ErrFinalToken + } + scanner.Split(onComma) + // Scan. + for scanner.Scan() { + fmt.Printf("%q ", scanner.Text()) + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(os.Stderr, "reading input:", err) + } + // Output: "1" "2" "3" "4" "" +} + +// Use a Scanner with a custom split function to parse a comma-separated +// list with an empty final value but stops at the token "STOP". +func ExampleScanner_earlyStop() { + onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) { + i := bytes.IndexByte(data, ',') + if i == -1 { + if !atEOF { + return 0, nil, nil + } + // If we have reached the end, return the last token. + return 0, data, bufio.ErrFinalToken + } + // If the token is "STOP", stop the scanning and ignore the rest. + if string(data[:i]) == "STOP" { + return i + 1, nil, bufio.ErrFinalToken + } + // Otherwise, return the token before the comma. + return i + 1, data[:i], nil + } + const input = "1,2,STOP,4," + scanner := bufio.NewScanner(strings.NewReader(input)) + scanner.Split(onComma) + for scanner.Scan() { + fmt.Printf("Got a token %q\n", scanner.Text()) + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(os.Stderr, "reading input:", err) + } + // Output: + // Got a token "1" + // Got a token "2" +} diff --git a/go/src/bufio/export_test.go b/go/src/bufio/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1667f01a841e07cba04c62e8cf7da7ab3593ca2b --- /dev/null +++ b/go/src/bufio/export_test.go @@ -0,0 +1,29 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bufio + +// Exported for testing only. +import ( + "unicode/utf8" +) + +var IsSpace = isSpace + +const DefaultBufSize = defaultBufSize + +func (s *Scanner) MaxTokenSize(n int) { + if n < utf8.UTFMax || n > 1e9 { + panic("bad max token size") + } + if n < len(s.buf) { + s.buf = make([]byte, n) + } + s.maxTokenSize = n +} + +// ErrOrEOF is like Err, but returns EOF. Used to test a corner case. +func (s *Scanner) ErrOrEOF() error { + return s.err +} diff --git a/go/src/bufio/net_test.go b/go/src/bufio/net_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d3b47e4cb99a39264b3f26ecd5ac1cdd3bc7b188 --- /dev/null +++ b/go/src/bufio/net_test.go @@ -0,0 +1,96 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package bufio_test + +import ( + "bufio" + "io" + "net" + "path/filepath" + "strings" + "sync" + "testing" +) + +// TestCopyUnixpacket tests that we can use bufio when copying +// across a unixpacket socket. This used to fail due to an unnecessary +// empty Write call that was interpreted as an EOF. +func TestCopyUnixpacket(t *testing.T) { + tmpDir := t.TempDir() + socket := filepath.Join(tmpDir, "unixsock") + + // Start a unixpacket server. + addr := &net.UnixAddr{ + Name: socket, + Net: "unixpacket", + } + server, err := net.ListenUnix("unixpacket", addr) + if err != nil { + t.Skipf("skipping test because opening a unixpacket socket failed: %v", err) + } + + // Start a goroutine for the server to accept one connection + // and read all the data sent on the connection, + // reporting the number of bytes read on ch. + ch := make(chan int, 1) + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + + tot := 0 + defer func() { + ch <- tot + }() + + serverConn, err := server.Accept() + if err != nil { + t.Error(err) + return + } + + buf := make([]byte, 1024) + for { + n, err := serverConn.Read(buf) + tot += n + if err == io.EOF { + return + } + if err != nil { + t.Error(err) + return + } + } + }() + + clientConn, err := net.DialUnix("unixpacket", nil, addr) + if err != nil { + // Leaves the server goroutine hanging. Oh well. + t.Fatal(err) + } + + defer wg.Wait() + defer clientConn.Close() + + const data = "data" + r := bufio.NewReader(strings.NewReader(data)) + n, err := io.Copy(clientConn, r) + if err != nil { + t.Fatal(err) + } + + if n != int64(len(data)) { + t.Errorf("io.Copy returned %d, want %d", n, len(data)) + } + + clientConn.Close() + tot := <-ch + + if tot != len(data) { + t.Errorf("server read %d, want %d", tot, len(data)) + } +} diff --git a/go/src/bufio/scan.go b/go/src/bufio/scan.go new file mode 100644 index 0000000000000000000000000000000000000000..1a0a3907c9eb8584ebbafa5bbd9dc34511080691 --- /dev/null +++ b/go/src/bufio/scan.go @@ -0,0 +1,427 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bufio + +import ( + "bytes" + "errors" + "io" + "unicode/utf8" +) + +// Scanner provides a convenient interface for reading data such as +// a file of newline-delimited lines of text. Successive calls to +// the [Scanner.Scan] method will step through the 'tokens' of a file, skipping +// the bytes between the tokens. The specification of a token is +// defined by a split function of type [SplitFunc]; the default split +// function breaks the input into lines with line termination stripped. [Scanner.Split] +// functions are defined in this package for scanning a file into +// lines, bytes, UTF-8-encoded runes, and space-delimited words. The +// client may instead provide a custom split function. +// +// Scanning stops unrecoverably at EOF, the first I/O error, or a token too +// large to fit in the [Scanner.Buffer]. When a scan stops, the reader may have +// advanced arbitrarily far past the last token. Programs that need more +// control over error handling or large tokens, or must run sequential scans +// on a reader, should use [bufio.Reader] instead. +type Scanner struct { + r io.Reader // The reader provided by the client. + split SplitFunc // The function to split the tokens. + maxTokenSize int // Maximum size of a token; modified by tests. + token []byte // Last token returned by split. + buf []byte // Buffer used as argument to split. + start int // First non-processed byte in buf. + end int // End of data in buf. + err error // Sticky error. + empties int // Count of successive empty tokens. + scanCalled bool // Scan has been called; buffer is in use. + done bool // Scan has finished. +} + +// SplitFunc is the signature of the split function used to tokenize the +// input. The arguments are an initial substring of the remaining unprocessed +// data and a flag, atEOF, that reports whether the [Reader] has no more data +// to give. The return values are the number of bytes to advance the input +// and the next token to return to the user, if any, plus an error, if any. +// +// Scanning stops if the function returns an error, in which case some of +// the input may be discarded. If that error is [ErrFinalToken], scanning +// stops with no error. A non-nil token delivered with [ErrFinalToken] +// will be the last token, and a nil token with [ErrFinalToken] +// immediately stops the scanning. +// +// Otherwise, the [Scanner] advances the input. If the token is not nil, +// the [Scanner] returns it to the user. If the token is nil, the +// Scanner reads more data and continues scanning; if there is no more +// data--if atEOF was true--the [Scanner] returns. If the data does not +// yet hold a complete token, for instance if it has no newline while +// scanning lines, a [SplitFunc] can return (0, nil, nil) to signal the +// [Scanner] to read more data into the slice and try again with a +// longer slice starting at the same point in the input. +// +// The function is never called with an empty data slice unless atEOF +// is true. If atEOF is true, however, data may be non-empty and, +// as always, holds unprocessed text. +type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error) + +// Errors returned by Scanner. +var ( + ErrTooLong = errors.New("bufio.Scanner: token too long") + ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count") + ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input") + ErrBadReadCount = errors.New("bufio.Scanner: Read returned impossible count") +) + +const ( + // MaxScanTokenSize is the maximum size used to buffer a token + // unless the user provides an explicit buffer with [Scanner.Buffer]. + // The actual maximum token size may be smaller as the buffer + // may need to include, for instance, a newline. + MaxScanTokenSize = 64 * 1024 + + startBufSize = 4096 // Size of initial allocation for buffer. +) + +// NewScanner returns a new [Scanner] to read from r. +// The split function defaults to [ScanLines]. +func NewScanner(r io.Reader) *Scanner { + return &Scanner{ + r: r, + split: ScanLines, + maxTokenSize: MaxScanTokenSize, + } +} + +// Err returns the first non-EOF error that was encountered by the [Scanner]. +func (s *Scanner) Err() error { + if s.err == io.EOF { + return nil + } + return s.err +} + +// Bytes returns the most recent token generated by a call to [Scanner.Scan]. +// The underlying array may point to data that will be overwritten +// by a subsequent call to Scan. It does no allocation. +func (s *Scanner) Bytes() []byte { + return s.token +} + +// Text returns the most recent token generated by a call to [Scanner.Scan] +// as a newly allocated string holding its bytes. +func (s *Scanner) Text() string { + return string(s.token) +} + +// ErrFinalToken is a special sentinel error value. It is intended to be +// returned by a Split function to indicate that the scanning should stop +// with no error. If the token being delivered with this error is not nil, +// the token is the last token. +// +// The value is useful to stop processing early or when it is necessary to +// deliver a final empty token (which is different from a nil token). +// One could achieve the same behavior with a custom error value but +// providing one here is tidier. +// See the emptyFinalToken example for a use of this value. +var ErrFinalToken = errors.New("final token") + +// Scan advances the [Scanner] to the next token, which will then be +// available through the [Scanner.Bytes] or [Scanner.Text] method. It returns false when +// there are no more tokens, either by reaching the end of the input or an error. +// After Scan returns false, the [Scanner.Err] method will return any error that +// occurred during scanning, except that if it was [io.EOF], [Scanner.Err] +// will return nil. +// Scan panics if the split function returns too many empty +// tokens without advancing the input. This is a common error mode for +// scanners. +func (s *Scanner) Scan() bool { + if s.done { + return false + } + s.scanCalled = true + // Loop until we have a token. + for { + // See if we can get a token with what we already have. + // If we've run out of data but have an error, give the split function + // a chance to recover any remaining, possibly empty token. + if s.end > s.start || s.err != nil { + advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil) + if err != nil { + if err == ErrFinalToken { + s.token = token + s.done = true + // When token is not nil, it means the scanning stops + // with a trailing token, and thus the return value + // should be true to indicate the existence of the token. + return token != nil + } + s.setErr(err) + return false + } + if !s.advance(advance) { + return false + } + s.token = token + if token != nil { + if s.err == nil || advance > 0 { + s.empties = 0 + } else { + // Returning tokens not advancing input at EOF. + s.empties++ + if s.empties > maxConsecutiveEmptyReads { + panic("bufio.Scan: too many empty tokens without progressing") + } + } + return true + } + } + // We cannot generate a token with what we are holding. + // If we've already hit EOF or an I/O error, we are done. + if s.err != nil { + // Shut it down. + s.start = 0 + s.end = 0 + return false + } + // Must read more data. + // First, shift data to beginning of buffer if there's lots of empty space + // or space is needed. + if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) { + copy(s.buf, s.buf[s.start:s.end]) + s.end -= s.start + s.start = 0 + } + // Is the buffer full? If so, resize. + if s.end == len(s.buf) { + // Guarantee no overflow in the multiplication below. + const maxInt = int(^uint(0) >> 1) + if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt/2 { + s.setErr(ErrTooLong) + return false + } + newSize := len(s.buf) * 2 + if newSize == 0 { + newSize = startBufSize + } + newSize = min(newSize, s.maxTokenSize) + newBuf := make([]byte, newSize) + copy(newBuf, s.buf[s.start:s.end]) + s.buf = newBuf + s.end -= s.start + s.start = 0 + } + // Finally we can read some input. Make sure we don't get stuck with + // a misbehaving Reader. Officially we don't need to do this, but let's + // be extra careful: Scanner is for safe, simple jobs. + for loop := 0; ; { + n, err := s.r.Read(s.buf[s.end:len(s.buf)]) + if n < 0 || len(s.buf)-s.end < n { + s.setErr(ErrBadReadCount) + break + } + s.end += n + if err != nil { + s.setErr(err) + break + } + if n > 0 { + s.empties = 0 + break + } + loop++ + if loop > maxConsecutiveEmptyReads { + s.setErr(io.ErrNoProgress) + break + } + } + } +} + +// advance consumes n bytes of the buffer. It reports whether the advance was legal. +func (s *Scanner) advance(n int) bool { + if n < 0 { + s.setErr(ErrNegativeAdvance) + return false + } + if n > s.end-s.start { + s.setErr(ErrAdvanceTooFar) + return false + } + s.start += n + return true +} + +// setErr records the first error encountered. +func (s *Scanner) setErr(err error) { + if s.err == nil || s.err == io.EOF { + s.err = err + } +} + +// Buffer controls memory allocation by the Scanner. +// It sets the initial buffer to use when scanning +// and the maximum size of buffer that may be allocated during scanning. +// The contents of the buffer are ignored. +// +// The maximum token size must be less than the larger of max and cap(buf). +// If max <= cap(buf), [Scanner.Scan] will use this buffer only and do no allocation. +// +// By default, [Scanner.Scan] uses an internal buffer and sets the +// maximum token size to [MaxScanTokenSize]. +// +// Buffer panics if it is called after scanning has started. +func (s *Scanner) Buffer(buf []byte, max int) { + if s.scanCalled { + panic("Buffer called after Scan") + } + s.buf = buf[0:cap(buf)] + s.maxTokenSize = max +} + +// Split sets the split function for the [Scanner]. +// The default split function is [ScanLines]. +// +// Split panics if it is called after scanning has started. +func (s *Scanner) Split(split SplitFunc) { + if s.scanCalled { + panic("Split called after Scan") + } + s.split = split +} + +// Split functions + +// ScanBytes is a split function for a [Scanner] that returns each byte as a token. +func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) { + if atEOF && len(data) == 0 { + return 0, nil, nil + } + return 1, data[0:1], nil +} + +var errorRune = []byte(string(utf8.RuneError)) + +// ScanRunes is a split function for a [Scanner] that returns each +// UTF-8-encoded rune as a token. The sequence of runes returned is +// equivalent to that from a range loop over the input as a string, which +// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". +// Because of the Scan interface, this makes it impossible for the client to +// distinguish correctly encoded replacement runes from encoding errors. +func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) { + if atEOF && len(data) == 0 { + return 0, nil, nil + } + + // Fast path 1: ASCII. + if data[0] < utf8.RuneSelf { + return 1, data[0:1], nil + } + + // Fast path 2: Correct UTF-8 decode without error. + _, width := utf8.DecodeRune(data) + if width > 1 { + // It's a valid encoding. Width cannot be one for a correctly encoded + // non-ASCII rune. + return width, data[0:width], nil + } + + // We know it's an error: we have width==1 and implicitly r==utf8.RuneError. + // Is the error because there wasn't a full rune to be decoded? + // FullRune distinguishes correctly between erroneous and incomplete encodings. + if !atEOF && !utf8.FullRune(data) { + // Incomplete; get more bytes. + return 0, nil, nil + } + + // We have a real UTF-8 encoding error. Return a properly encoded error rune + // but advance only one byte. This matches the behavior of a range loop over + // an incorrectly encoded string. + return 1, errorRune, nil +} + +// dropCR drops a terminal \r from the data. +func dropCR(data []byte) []byte { + if len(data) > 0 && data[len(data)-1] == '\r' { + return data[0 : len(data)-1] + } + return data +} + +// ScanLines is a split function for a [Scanner] that returns each line of +// text, stripped of any trailing end-of-line marker. The returned line may +// be empty. The end-of-line marker is one optional carriage return followed +// by one mandatory newline. In regular expression notation, it is `\r?\n`. +// The last non-empty line of input will be returned even if it has no +// newline. +func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { + if atEOF && len(data) == 0 { + return 0, nil, nil + } + if i := bytes.IndexByte(data, '\n'); i >= 0 { + // We have a full newline-terminated line. + return i + 1, dropCR(data[0:i]), nil + } + // If we're at EOF, we have a final, non-terminated line. Return it. + if atEOF { + return len(data), dropCR(data), nil + } + // Request more data. + return 0, nil, nil +} + +// isSpace reports whether the character is a Unicode white space character. +// We avoid dependency on the unicode package, but check validity of the implementation +// in the tests. +func isSpace(r rune) bool { + if r <= '\u00FF' { + // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs. + switch r { + case ' ', '\t', '\n', '\v', '\f', '\r': + return true + case '\u0085', '\u00A0': + return true + } + return false + } + // High-valued ones. + if '\u2000' <= r && r <= '\u200a' { + return true + } + switch r { + case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000': + return true + } + return false +} + +// ScanWords is a split function for a [Scanner] that returns each +// space-separated word of text, with surrounding spaces deleted. It will +// never return an empty string. The definition of space is set by +// unicode.IsSpace. +func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) { + // Skip leading spaces. + start := 0 + for width := 0; start < len(data); start += width { + var r rune + r, width = utf8.DecodeRune(data[start:]) + if !isSpace(r) { + break + } + } + // Scan until space, marking end of word. + for width, i := 0, start; i < len(data); i += width { + var r rune + r, width = utf8.DecodeRune(data[i:]) + if isSpace(r) { + return i + width, data[start:i], nil + } + } + // If we're at EOF, we have a final, non-empty, non-terminated word. Return it. + if atEOF && len(data) > start { + return len(data), data[start:], nil + } + // Request more data. + return start, nil, nil +} diff --git a/go/src/bufio/scan_test.go b/go/src/bufio/scan_test.go new file mode 100644 index 0000000000000000000000000000000000000000..6b64f7ba9c5d896356a4a3a7e2646de30e6837e0 --- /dev/null +++ b/go/src/bufio/scan_test.go @@ -0,0 +1,596 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bufio_test + +import ( + . "bufio" + "bytes" + "errors" + "io" + "strings" + "testing" + "unicode" + "unicode/utf8" +) + +const smallMaxTokenSize = 256 // Much smaller for more efficient testing. + +// Test white space table matches the Unicode definition. +func TestSpace(t *testing.T) { + for r := rune(0); r <= utf8.MaxRune; r++ { + if IsSpace(r) != unicode.IsSpace(r) { + t.Fatalf("white space property disagrees: %#U should be %t", r, unicode.IsSpace(r)) + } + } +} + +var scanTests = []string{ + "", + "a", + "¼", + "☹", + "\x81", // UTF-8 error + "\uFFFD", // correctly encoded RuneError + "abcdefgh", + "abc def\n\t\tgh ", + "abc¼☹\x81\uFFFD日本語\x82abc", +} + +func TestScanByte(t *testing.T) { + for n, test := range scanTests { + buf := strings.NewReader(test) + s := NewScanner(buf) + s.Split(ScanBytes) + var i int + for i = 0; s.Scan(); i++ { + if b := s.Bytes(); len(b) != 1 || b[0] != test[i] { + t.Errorf("#%d: %d: expected %q got %q", n, i, test, b) + } + } + if i != len(test) { + t.Errorf("#%d: termination expected at %d; got %d", n, len(test), i) + } + err := s.Err() + if err != nil { + t.Errorf("#%d: %v", n, err) + } + } +} + +// Test that the rune splitter returns same sequence of runes (not bytes) as for range string. +func TestScanRune(t *testing.T) { + for n, test := range scanTests { + buf := strings.NewReader(test) + s := NewScanner(buf) + s.Split(ScanRunes) + var i, runeCount int + var expect rune + // Use a string range loop to validate the sequence of runes. + for i, expect = range test { + if !s.Scan() { + break + } + runeCount++ + got, _ := utf8.DecodeRune(s.Bytes()) + if got != expect { + t.Errorf("#%d: %d: expected %q got %q", n, i, expect, got) + } + } + if s.Scan() { + t.Errorf("#%d: scan ran too long, got %q", n, s.Text()) + } + testRuneCount := utf8.RuneCountInString(test) + if runeCount != testRuneCount { + t.Errorf("#%d: termination expected at %d; got %d", n, testRuneCount, runeCount) + } + err := s.Err() + if err != nil { + t.Errorf("#%d: %v", n, err) + } + } +} + +var wordScanTests = []string{ + "", + " ", + "\n", + "a", + " a ", + "abc def", + " abc def ", + " abc\tdef\nghi\rjkl\fmno\vpqr\u0085stu\u00a0\n", +} + +// Test that the word splitter returns the same data as strings.Fields. +func TestScanWords(t *testing.T) { + for n, test := range wordScanTests { + buf := strings.NewReader(test) + s := NewScanner(buf) + s.Split(ScanWords) + words := strings.Fields(test) + var wordCount int + for wordCount = 0; wordCount < len(words); wordCount++ { + if !s.Scan() { + break + } + got := s.Text() + if got != words[wordCount] { + t.Errorf("#%d: %d: expected %q got %q", n, wordCount, words[wordCount], got) + } + } + if s.Scan() { + t.Errorf("#%d: scan ran too long, got %q", n, s.Text()) + } + if wordCount != len(words) { + t.Errorf("#%d: termination expected at %d; got %d", n, len(words), wordCount) + } + err := s.Err() + if err != nil { + t.Errorf("#%d: %v", n, err) + } + } +} + +// slowReader is a reader that returns only a few bytes at a time, to test the incremental +// reads in Scanner.Scan. +type slowReader struct { + max int + buf io.Reader +} + +func (sr *slowReader) Read(p []byte) (n int, err error) { + if len(p) > sr.max { + p = p[0:sr.max] + } + return sr.buf.Read(p) +} + +// genLine writes to buf a predictable but non-trivial line of text of length +// n, including the terminal newline and an occasional carriage return. +// If addNewline is false, the \r and \n are not emitted. +func genLine(buf *bytes.Buffer, lineNum, n int, addNewline bool) { + buf.Reset() + doCR := lineNum%5 == 0 + if doCR { + n-- + } + for i := 0; i < n-1; i++ { // Stop early for \n. + c := 'a' + byte(lineNum+i) + if c == '\n' || c == '\r' { // Don't confuse us. + c = 'N' + } + buf.WriteByte(c) + } + if addNewline { + if doCR { + buf.WriteByte('\r') + } + buf.WriteByte('\n') + } +} + +// Test the line splitter, including some carriage returns but no long lines. +func TestScanLongLines(t *testing.T) { + // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize. + tmp := new(bytes.Buffer) + buf := new(bytes.Buffer) + lineNum := 0 + j := 0 + for i := 0; i < 2*smallMaxTokenSize; i++ { + genLine(tmp, lineNum, j, true) + if j < smallMaxTokenSize { + j++ + } else { + j-- + } + buf.Write(tmp.Bytes()) + lineNum++ + } + s := NewScanner(&slowReader{1, buf}) + s.Split(ScanLines) + s.MaxTokenSize(smallMaxTokenSize) + j = 0 + for lineNum := 0; s.Scan(); lineNum++ { + genLine(tmp, lineNum, j, false) + if j < smallMaxTokenSize { + j++ + } else { + j-- + } + line := tmp.String() // We use the string-valued token here, for variety. + if s.Text() != line { + t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Text(), line) + } + } + err := s.Err() + if err != nil { + t.Fatal(err) + } +} + +// Test that the line splitter errors out on a long line. +func TestScanLineTooLong(t *testing.T) { + const smallMaxTokenSize = 256 // Much smaller for more efficient testing. + // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize. + tmp := new(bytes.Buffer) + buf := new(bytes.Buffer) + lineNum := 0 + j := 0 + for i := 0; i < 2*smallMaxTokenSize; i++ { + genLine(tmp, lineNum, j, true) + j++ + buf.Write(tmp.Bytes()) + lineNum++ + } + s := NewScanner(&slowReader{3, buf}) + s.Split(ScanLines) + s.MaxTokenSize(smallMaxTokenSize) + j = 0 + for lineNum := 0; s.Scan(); lineNum++ { + genLine(tmp, lineNum, j, false) + if j < smallMaxTokenSize { + j++ + } else { + j-- + } + line := tmp.Bytes() + if !bytes.Equal(s.Bytes(), line) { + t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line) + } + } + err := s.Err() + if err != ErrTooLong { + t.Fatalf("expected ErrTooLong; got %s", err) + } +} + +// Test that the line splitter handles a final line without a newline. +func testNoNewline(text string, lines []string, t *testing.T) { + buf := strings.NewReader(text) + s := NewScanner(&slowReader{7, buf}) + s.Split(ScanLines) + for lineNum := 0; s.Scan(); lineNum++ { + line := lines[lineNum] + if s.Text() != line { + t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line) + } + } + err := s.Err() + if err != nil { + t.Fatal(err) + } +} + +// Test that the line splitter handles a final line without a newline. +func TestScanLineNoNewline(t *testing.T) { + const text = "abcdefghijklmn\nopqrstuvwxyz" + lines := []string{ + "abcdefghijklmn", + "opqrstuvwxyz", + } + testNoNewline(text, lines, t) +} + +// Test that the line splitter handles a final line with a carriage return but no newline. +func TestScanLineReturnButNoNewline(t *testing.T) { + const text = "abcdefghijklmn\nopqrstuvwxyz\r" + lines := []string{ + "abcdefghijklmn", + "opqrstuvwxyz", + } + testNoNewline(text, lines, t) +} + +// Test that the line splitter handles a final empty line. +func TestScanLineEmptyFinalLine(t *testing.T) { + const text = "abcdefghijklmn\nopqrstuvwxyz\n\n" + lines := []string{ + "abcdefghijklmn", + "opqrstuvwxyz", + "", + } + testNoNewline(text, lines, t) +} + +// Test that the line splitter handles a final empty line with a carriage return but no newline. +func TestScanLineEmptyFinalLineWithCR(t *testing.T) { + const text = "abcdefghijklmn\nopqrstuvwxyz\n\r" + lines := []string{ + "abcdefghijklmn", + "opqrstuvwxyz", + "", + } + testNoNewline(text, lines, t) +} + +var testError = errors.New("testError") + +// Test the correct error is returned when the split function errors out. +func TestSplitError(t *testing.T) { + // Create a split function that delivers a little data, then a predictable error. + numSplits := 0 + const okCount = 7 + errorSplit := func(data []byte, atEOF bool) (advance int, token []byte, err error) { + if atEOF { + panic("didn't get enough data") + } + if numSplits >= okCount { + return 0, nil, testError + } + numSplits++ + return 1, data[0:1], nil + } + // Read the data. + const text = "abcdefghijklmnopqrstuvwxyz" + buf := strings.NewReader(text) + s := NewScanner(&slowReader{1, buf}) + s.Split(errorSplit) + var i int + for i = 0; s.Scan(); i++ { + if len(s.Bytes()) != 1 || text[i] != s.Bytes()[0] { + t.Errorf("#%d: expected %q got %q", i, text[i], s.Bytes()[0]) + } + } + // Check correct termination location and error. + if i != okCount { + t.Errorf("unexpected termination; expected %d tokens got %d", okCount, i) + } + err := s.Err() + if err != testError { + t.Fatalf("expected %q got %v", testError, err) + } +} + +// Test that an EOF is overridden by a user-generated scan error. +func TestErrAtEOF(t *testing.T) { + s := NewScanner(strings.NewReader("1 2 33")) + // This splitter will fail on last entry, after s.err==EOF. + split := func(data []byte, atEOF bool) (advance int, token []byte, err error) { + advance, token, err = ScanWords(data, atEOF) + if len(token) > 1 { + if s.ErrOrEOF() != io.EOF { + t.Fatal("not testing EOF") + } + err = testError + } + return + } + s.Split(split) + for s.Scan() { + } + if s.Err() != testError { + t.Fatal("wrong error:", s.Err()) + } +} + +// Test for issue 5268. +type alwaysError struct{} + +func (alwaysError) Read(p []byte) (int, error) { + return 0, io.ErrUnexpectedEOF +} + +func TestNonEOFWithEmptyRead(t *testing.T) { + scanner := NewScanner(alwaysError{}) + for scanner.Scan() { + t.Fatal("read should fail") + } + err := scanner.Err() + if err != io.ErrUnexpectedEOF { + t.Errorf("unexpected error: %v", err) + } +} + +// Test that Scan finishes if we have endless empty reads. +type endlessZeros struct{} + +func (endlessZeros) Read(p []byte) (int, error) { + return 0, nil +} + +func TestBadReader(t *testing.T) { + scanner := NewScanner(endlessZeros{}) + for scanner.Scan() { + t.Fatal("read should fail") + } + err := scanner.Err() + if err != io.ErrNoProgress { + t.Errorf("unexpected error: %v", err) + } +} + +func TestScanWordsExcessiveWhiteSpace(t *testing.T) { + const word = "ipsum" + s := strings.Repeat(" ", 4*smallMaxTokenSize) + word + scanner := NewScanner(strings.NewReader(s)) + scanner.MaxTokenSize(smallMaxTokenSize) + scanner.Split(ScanWords) + if !scanner.Scan() { + t.Fatalf("scan failed: %v", scanner.Err()) + } + if token := scanner.Text(); token != word { + t.Fatalf("unexpected token: %v", token) + } +} + +// Test that empty tokens, including at end of line or end of file, are found by the scanner. +// Issue 8672: Could miss final empty token. + +func commaSplit(data []byte, atEOF bool) (advance int, token []byte, err error) { + for i := 0; i < len(data); i++ { + if data[i] == ',' { + return i + 1, data[:i], nil + } + } + return 0, data, ErrFinalToken +} + +func testEmptyTokens(t *testing.T, text string, values []string) { + s := NewScanner(strings.NewReader(text)) + s.Split(commaSplit) + var i int + for i = 0; s.Scan(); i++ { + if i >= len(values) { + t.Fatalf("got %d fields, expected %d", i+1, len(values)) + } + if s.Text() != values[i] { + t.Errorf("%d: expected %q got %q", i, values[i], s.Text()) + } + } + if i != len(values) { + t.Fatalf("got %d fields, expected %d", i, len(values)) + } + if err := s.Err(); err != nil { + t.Fatal(err) + } +} + +func TestEmptyTokens(t *testing.T) { + testEmptyTokens(t, "1,2,3,", []string{"1", "2", "3", ""}) +} + +func TestWithNoEmptyTokens(t *testing.T) { + testEmptyTokens(t, "1,2,3", []string{"1", "2", "3"}) +} + +func loopAtEOFSplit(data []byte, atEOF bool) (advance int, token []byte, err error) { + if len(data) > 0 { + return 1, data[:1], nil + } + return 0, data, nil +} + +func TestDontLoopForever(t *testing.T) { + s := NewScanner(strings.NewReader("abc")) + s.Split(loopAtEOFSplit) + // Expect a panic + defer func() { + err := recover() + if err == nil { + t.Fatal("should have panicked") + } + if msg, ok := err.(string); !ok || !strings.Contains(msg, "empty tokens") { + panic(err) + } + }() + for count := 0; s.Scan(); count++ { + if count > 1000 { + t.Fatal("looping") + } + } + if s.Err() != nil { + t.Fatal("after scan:", s.Err()) + } +} + +func TestBlankLines(t *testing.T) { + s := NewScanner(strings.NewReader(strings.Repeat("\n", 1000))) + for count := 0; s.Scan(); count++ { + if count > 2000 { + t.Fatal("looping") + } + } + if s.Err() != nil { + t.Fatal("after scan:", s.Err()) + } +} + +type countdown int + +func (c *countdown) split(data []byte, atEOF bool) (advance int, token []byte, err error) { + if *c > 0 { + *c-- + return 1, data[:1], nil + } + return 0, nil, nil +} + +// Check that the looping-at-EOF check doesn't trigger for merely empty tokens. +func TestEmptyLinesOK(t *testing.T) { + c := countdown(10000) + s := NewScanner(strings.NewReader(strings.Repeat("\n", 10000))) + s.Split(c.split) + for s.Scan() { + } + if s.Err() != nil { + t.Fatal("after scan:", s.Err()) + } + if c != 0 { + t.Fatalf("stopped with %d left to process", c) + } +} + +// Make sure we can read a huge token if a big enough buffer is provided. +func TestHugeBuffer(t *testing.T) { + text := strings.Repeat("x", 2*MaxScanTokenSize) + s := NewScanner(strings.NewReader(text + "\n")) + s.Buffer(make([]byte, 100), 3*MaxScanTokenSize) + for s.Scan() { + token := s.Text() + if token != text { + t.Errorf("scan got incorrect token of length %d", len(token)) + } + } + if s.Err() != nil { + t.Fatal("after scan:", s.Err()) + } +} + +// negativeEOFReader returns an invalid -1 at the end, as though it +// were wrapping the read system call. +type negativeEOFReader int + +func (r *negativeEOFReader) Read(p []byte) (int, error) { + if *r > 0 { + c := int(*r) + if c > len(p) { + c = len(p) + } + for i := 0; i < c; i++ { + p[i] = 'a' + } + p[c-1] = '\n' + *r -= negativeEOFReader(c) + return c, nil + } + return -1, io.EOF +} + +// Test that the scanner doesn't panic and returns ErrBadReadCount +// on a reader that returns a negative count of bytes read (issue 38053). +func TestNegativeEOFReader(t *testing.T) { + r := negativeEOFReader(10) + scanner := NewScanner(&r) + c := 0 + for scanner.Scan() { + c++ + if c > 1 { + t.Error("read too many lines") + break + } + } + if got, want := scanner.Err(), ErrBadReadCount; got != want { + t.Errorf("scanner.Err: got %v, want %v", got, want) + } +} + +// largeReader returns an invalid count that is larger than the number +// of bytes requested. +type largeReader struct{} + +func (largeReader) Read(p []byte) (int, error) { + return len(p) + 1, nil +} + +// Test that the scanner doesn't panic and returns ErrBadReadCount +// on a reader that returns an impossibly large count of bytes read (issue 38053). +func TestLargeReader(t *testing.T) { + scanner := NewScanner(largeReader{}) + for scanner.Scan() { + } + if got, want := scanner.Err(), ErrBadReadCount; got != want { + t.Errorf("scanner.Err: got %v, want %v", got, want) + } +} diff --git a/go/src/builtin/builtin.go b/go/src/builtin/builtin.go new file mode 100644 index 0000000000000000000000000000000000000000..be53077d9cb495e9e1a950ceccf3ceafe76900ce --- /dev/null +++ b/go/src/builtin/builtin.go @@ -0,0 +1,319 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package builtin provides documentation for Go's predeclared identifiers. +The items documented here are not actually in package builtin +but their descriptions here allow godoc to present documentation +for the language's special identifiers. +*/ +package builtin + +import "cmp" + +// bool is the set of boolean values, true and false. +type bool bool + +// true and false are the two untyped boolean values. +const ( + true = 0 == 0 // Untyped bool. + false = 0 != 0 // Untyped bool. +) + +// uint8 is the set of all unsigned 8-bit integers. +// Range: 0 through 255. +type uint8 uint8 + +// uint16 is the set of all unsigned 16-bit integers. +// Range: 0 through 65535. +type uint16 uint16 + +// uint32 is the set of all unsigned 32-bit integers. +// Range: 0 through 4294967295. +type uint32 uint32 + +// uint64 is the set of all unsigned 64-bit integers. +// Range: 0 through 18446744073709551615. +type uint64 uint64 + +// int8 is the set of all signed 8-bit integers. +// Range: -128 through 127. +type int8 int8 + +// int16 is the set of all signed 16-bit integers. +// Range: -32768 through 32767. +type int16 int16 + +// int32 is the set of all signed 32-bit integers. +// Range: -2147483648 through 2147483647. +type int32 int32 + +// int64 is the set of all signed 64-bit integers. +// Range: -9223372036854775808 through 9223372036854775807. +type int64 int64 + +// float32 is the set of all IEEE 754 32-bit floating-point numbers. +type float32 float32 + +// float64 is the set of all IEEE 754 64-bit floating-point numbers. +type float64 float64 + +// complex64 is the set of all complex numbers with float32 real and +// imaginary parts. +type complex64 complex64 + +// complex128 is the set of all complex numbers with float64 real and +// imaginary parts. +type complex128 complex128 + +// string is the set of all strings of 8-bit bytes, conventionally but not +// necessarily representing UTF-8-encoded text. A string may be empty, but +// not nil. Values of string type are immutable. +type string string + +// int is a signed integer type that is at least 32 bits in size. It is a +// distinct type, however, and not an alias for, say, int32. +type int int + +// uint is an unsigned integer type that is at least 32 bits in size. It is a +// distinct type, however, and not an alias for, say, uint32. +type uint uint + +// uintptr is an integer type that is large enough to hold the bit pattern of +// any pointer. +type uintptr uintptr + +// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is +// used, by convention, to distinguish byte values from 8-bit unsigned +// integer values. +type byte = uint8 + +// rune is an alias for int32 and is equivalent to int32 in all ways. It is +// used, by convention, to distinguish character values from integer values. +type rune = int32 + +// any is an alias for interface{} and is equivalent to interface{} in all ways. +type any = interface{} + +// comparable is an interface that is implemented by all comparable types +// (booleans, numbers, strings, pointers, channels, arrays of comparable types, +// structs whose fields are all comparable types). +// The comparable interface may only be used as a type parameter constraint, +// not as the type of a variable. +type comparable interface{ comparable } + +// iota is a predeclared identifier representing the untyped integer ordinal +// number of the current const specification in a (usually parenthesized) +// const declaration. It is zero-indexed. +const iota = 0 // Untyped int. + +// nil is a predeclared identifier representing the zero value for a +// pointer, channel, func, interface, map, or slice type. +var nil Type // Type must be a pointer, channel, func, interface, map, or slice type + +// Type is here for the purposes of documentation only. It is a stand-in +// for any Go type, but represents the same type for any given function +// invocation. +type Type int + +// Type1 is here for the purposes of documentation only. It is a stand-in +// for any Go type, but represents the same type for any given function +// invocation. +type Type1 int + +// TypeOrExpr is here for the purposes of documentation only. It is a stand-in +// for either a Go type or an expression. +type TypeOrExpr int + +// IntegerType is here for the purposes of documentation only. It is a stand-in +// for any integer type: int, uint, int8 etc. +type IntegerType int + +// FloatType is here for the purposes of documentation only. It is a stand-in +// for either float type: float32 or float64. +type FloatType float32 + +// ComplexType is here for the purposes of documentation only. It is a +// stand-in for either complex type: complex64 or complex128. +type ComplexType complex64 + +// The append built-in function appends elements to the end of a slice. If +// it has sufficient capacity, the destination is resliced to accommodate the +// new elements. If it does not, a new underlying array will be allocated. +// Append returns the updated slice. It is therefore necessary to store the +// result of append, often in the variable holding the slice itself: +// +// slice = append(slice, elem1, elem2) +// slice = append(slice, anotherSlice...) +// +// As a special case, it is legal to append a string to a byte slice, like this: +// +// slice = append([]byte("hello "), "world"...) +func append(slice []Type, elems ...Type) []Type + +// The copy built-in function copies elements from a source slice into a +// destination slice. (As a special case, it also will copy bytes from a +// string to a slice of bytes.) The source and destination may overlap. Copy +// returns the number of elements copied, which will be the minimum of +// len(src) and len(dst). +func copy(dst, src []Type) int + +// The delete built-in function deletes the element with the specified key +// (m[key]) from the map. If m is nil or there is no such element, delete +// is a no-op. +func delete(m map[Type]Type1, key Type) + +// The len built-in function returns the length of v, according to its type: +// +// - Array: the number of elements in v. +// - Pointer to array: the number of elements in *v (even if v is nil). +// - Slice, or map: the number of elements in v; if v is nil, len(v) is zero. +// - String: the number of bytes in v. +// - Channel: the number of elements queued (unread) in the channel buffer; +// if v is nil, len(v) is zero. +// +// For some arguments, such as a string literal or a simple array expression, the +// result can be a constant. See the Go language specification's "Length and +// capacity" section for details. +func len(v Type) int + +// The cap built-in function returns the capacity of v, according to its type: +// +// - Array: the number of elements in v (same as len(v)). +// - Pointer to array: the number of elements in *v (same as len(v)). +// - Slice: the maximum length the slice can reach when resliced; +// if v is nil, cap(v) is zero. +// - Channel: the channel buffer capacity, in units of elements; +// if v is nil, cap(v) is zero. +// +// For some arguments, such as a simple array expression, the result can be a +// constant. See the Go language specification's "Length and capacity" section for +// details. +func cap(v Type) int + +// The make built-in function allocates and initializes an object of type +// slice, map, or chan (only). Like new, the first argument is a type, not a +// value. Unlike new, make's return type is the same as the type of its +// argument, not a pointer to it. The specification of the result depends on +// the type: +// +// - Slice: The size specifies the length. The capacity of the slice is +// equal to its length. A second integer argument may be provided to +// specify a different capacity; it must be no smaller than the +// length. For example, make([]int, 0, 10) allocates an underlying array +// of size 10 and returns a slice of length 0 and capacity 10 that is +// backed by this underlying array. +// - Map: An empty map is allocated with enough space to hold the +// specified number of elements. The size may be omitted, in which case +// a small starting size is allocated. +// - Channel: The channel's buffer is initialized with the specified +// buffer capacity. If zero, or the size is omitted, the channel is +// unbuffered. +func make(t Type, size ...IntegerType) Type + +// The max built-in function returns the largest value of a fixed number of +// arguments of [cmp.Ordered] types. There must be at least one argument. +// If T is a floating-point type and any of the arguments are NaNs, +// max will return NaN. +func max[T cmp.Ordered](x T, y ...T) T + +// The min built-in function returns the smallest value of a fixed number of +// arguments of [cmp.Ordered] types. There must be at least one argument. +// If T is a floating-point type and any of the arguments are NaNs, +// min will return NaN. +func min[T cmp.Ordered](x T, y ...T) T + +// The built-in function new allocates a new, initialized variable and returns +// a pointer to it. It accepts a single argument, which may be either a type +// or an expression. +// If the argument is a type T, then new(T) allocates a variable of type T +// initialized to its zero value. +// Otherwise, the argument is an expression x and new(x) allocates a variable +// of the type of x initialized to the value of x. If that value is an untyped +// constant, it is first implicitly converted to its default type. +func new(TypeOrExpr) *Type + +// The complex built-in function constructs a complex value from two +// floating-point values. The real and imaginary parts must be of the same +// size, either float32 or float64 (or assignable to them), and the return +// value will be the corresponding complex type (complex64 for float32, +// complex128 for float64). +func complex(r, i FloatType) ComplexType + +// The real built-in function returns the real part of the complex number c. +// The return value will be floating point type corresponding to the type of c. +func real(c ComplexType) FloatType + +// The imag built-in function returns the imaginary part of the complex +// number c. The return value will be floating point type corresponding to +// the type of c. +func imag(c ComplexType) FloatType + +// The clear built-in function clears maps and slices. +// For maps, clear deletes all entries, resulting in an empty map. +// For slices, clear sets all elements up to the length of the slice +// to the zero value of the respective element type. If the argument +// type is a type parameter, the type parameter's type set must +// contain only map or slice types, and clear performs the operation +// implied by the type argument. If t is nil, clear is a no-op. +func clear[T ~[]Type | ~map[Type]Type1](t T) + +// The close built-in function closes a channel, which must be either +// bidirectional or send-only. It should be executed only by the sender, +// never the receiver, and has the effect of shutting down the channel after +// the last sent value is received. After the last value has been received +// from a closed channel c, any receive from c will succeed without +// blocking, returning the zero value for the channel element. The form +// +// x, ok := <-c +// +// will also set ok to false for a closed and empty channel. +func close(c chan<- Type) + +// The panic built-in function stops normal execution of the current +// goroutine. When a function F calls panic, normal execution of F stops +// immediately. Any functions whose execution was deferred by F are run in +// the usual way, and then F returns to its caller. To the caller G, the +// invocation of F then behaves like a call to panic, terminating G's +// execution and running any deferred functions. This continues until all +// functions in the executing goroutine have stopped, in reverse order. At +// that point, the program is terminated with a non-zero exit code. This +// termination sequence is called panicking and can be controlled by the +// built-in function recover. +// +// Starting in Go 1.21, calling panic with a nil interface value or an +// untyped nil causes a run-time error (a different panic). +// The GODEBUG setting panicnil=1 disables the run-time error. +func panic(v any) + +// The recover built-in function allows a program to manage behavior of a +// panicking goroutine. Executing a call to recover inside a deferred +// function (but not any function called by it) stops the panicking sequence +// by restoring normal execution and retrieves the error value passed to the +// call of panic. If recover is called outside the deferred function it will +// not stop a panicking sequence. In this case, or when the goroutine is not +// panicking, recover returns nil. +// +// Prior to Go 1.21, recover would also return nil if panic is called with +// a nil argument. See [panic] for details. +func recover() any + +// The print built-in function formats its arguments in an +// implementation-specific way and writes the result to standard error. +// Print is useful for bootstrapping and debugging; it is not guaranteed +// to stay in the language. +func print(args ...Type) + +// The println built-in function formats its arguments in an +// implementation-specific way and writes the result to standard error. +// Spaces are always added between arguments and a newline is appended. +// Println is useful for bootstrapping and debugging; it is not guaranteed +// to stay in the language. +func println(args ...Type) + +// The error built-in interface type is the conventional interface for +// representing an error condition, with the nil value representing no error. +type error interface { + Error() string +} diff --git a/go/src/bytes/boundary_test.go b/go/src/bytes/boundary_test.go new file mode 100644 index 0000000000000000000000000000000000000000..67f377e089634f15f06069c28d4779bb161b1614 --- /dev/null +++ b/go/src/bytes/boundary_test.go @@ -0,0 +1,115 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// +//go:build linux + +package bytes_test + +import ( + . "bytes" + "syscall" + "testing" +) + +// This file tests the situation where byte operations are checking +// data very near to a page boundary. We want to make sure those +// operations do not read across the boundary and cause a page +// fault where they shouldn't. + +// These tests run only on linux. The code being tested is +// not OS-specific, so it does not need to be tested on all +// operating systems. + +// dangerousSlice returns a slice which is immediately +// preceded and followed by a faulting page. +func dangerousSlice(t *testing.T) []byte { + pagesize := syscall.Getpagesize() + b, err := syscall.Mmap(0, 0, 3*pagesize, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANONYMOUS|syscall.MAP_PRIVATE) + if err != nil { + t.Fatalf("mmap failed %s", err) + } + err = syscall.Mprotect(b[:pagesize], syscall.PROT_NONE) + if err != nil { + t.Fatalf("mprotect low failed %s\n", err) + } + err = syscall.Mprotect(b[2*pagesize:], syscall.PROT_NONE) + if err != nil { + t.Fatalf("mprotect high failed %s\n", err) + } + return b[pagesize : 2*pagesize] +} + +func TestEqualNearPageBoundary(t *testing.T) { + t.Parallel() + b := dangerousSlice(t) + for i := range b { + b[i] = 'A' + } + for i := 0; i <= len(b); i++ { + Equal(b[:i], b[len(b)-i:]) + Equal(b[len(b)-i:], b[:i]) + } +} + +func TestIndexByteNearPageBoundary(t *testing.T) { + t.Parallel() + b := dangerousSlice(t) + for i := range b { + idx := IndexByte(b[i:], 1) + if idx != -1 { + t.Fatalf("IndexByte(b[%d:])=%d, want -1\n", i, idx) + } + } +} + +func TestIndexNearPageBoundary(t *testing.T) { + t.Parallel() + q := dangerousSlice(t) + if len(q) > 64 { + // Only worry about when we're near the end of a page. + q = q[len(q)-64:] + } + b := dangerousSlice(t) + if len(b) > 256 { + // Only worry about when we're near the end of a page. + b = b[len(b)-256:] + } + for j := 1; j < len(q); j++ { + q[j-1] = 1 // difference is only found on the last byte + for i := range b { + idx := Index(b[i:], q[:j]) + if idx != -1 { + t.Fatalf("Index(b[%d:], q[:%d])=%d, want -1\n", i, j, idx) + } + } + q[j-1] = 0 + } + + // Test differing alignments and sizes of q which always end on a page boundary. + q[len(q)-1] = 1 // difference is only found on the last byte + for j := 0; j < len(q); j++ { + for i := range b { + idx := Index(b[i:], q[j:]) + if idx != -1 { + t.Fatalf("Index(b[%d:], q[%d:])=%d, want -1\n", i, j, idx) + } + } + } + q[len(q)-1] = 0 +} + +func TestCountNearPageBoundary(t *testing.T) { + t.Parallel() + b := dangerousSlice(t) + for i := range b { + c := Count(b[i:], []byte{1}) + if c != 0 { + t.Fatalf("Count(b[%d:], {1})=%d, want 0\n", i, c) + } + c = Count(b[:i], []byte{0}) + if c != i { + t.Fatalf("Count(b[:%d], {0})=%d, want %d\n", i, c, i) + } + } +} diff --git a/go/src/bytes/buffer.go b/go/src/bytes/buffer.go new file mode 100644 index 0000000000000000000000000000000000000000..6cb4d6a8f66ebf556eb4543f495ec8d537889fd9 --- /dev/null +++ b/go/src/bytes/buffer.go @@ -0,0 +1,500 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes + +// Simple byte buffer for marshaling data. + +import ( + "errors" + "io" + "unicode/utf8" +) + +// smallBufferSize is an initial allocation minimal capacity. +const smallBufferSize = 64 + +// A Buffer is a variable-sized buffer of bytes with [Buffer.Read] and [Buffer.Write] methods. +// The zero value for Buffer is an empty buffer ready to use. +type Buffer struct { + buf []byte // contents are the bytes buf[off : len(buf)] + off int // read at &buf[off], write at &buf[len(buf)] + lastRead readOp // last read operation, so that Unread* can work correctly. + + // Copying and modifying a non-zero Buffer is prone to error, + // but we cannot employ the noCopy trick used by WaitGroup and Mutex, + // which causes vet's copylocks checker to report misuse, as vet + // cannot reliably distinguish the zero and non-zero cases. + // See #26462, #25907, #47276, #48398 for history. +} + +// The readOp constants describe the last action performed on +// the buffer, so that UnreadRune and UnreadByte can check for +// invalid usage. opReadRuneX constants are chosen such that +// converted to int they correspond to the rune size that was read. +type readOp int8 + +// Don't use iota for these, as the values need to correspond with the +// names and comments, which is easier to see when being explicit. +const ( + opRead readOp = -1 // Any other read operation. + opInvalid readOp = 0 // Non-read operation. + opReadRune1 readOp = 1 // Read rune of size 1. + opReadRune2 readOp = 2 // Read rune of size 2. + opReadRune3 readOp = 3 // Read rune of size 3. + opReadRune4 readOp = 4 // Read rune of size 4. +) + +// ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer. +var ErrTooLarge = errors.New("bytes.Buffer: too large") +var errNegativeRead = errors.New("bytes.Buffer: reader returned negative count from Read") + +const maxInt = int(^uint(0) >> 1) + +// Bytes returns a slice of length b.Len() holding the unread portion of the buffer. +// The slice is valid for use only until the next buffer modification (that is, +// only until the next call to a method like [Buffer.Read], [Buffer.Write], [Buffer.Reset], or [Buffer.Truncate]). +// The slice aliases the buffer content at least until the next buffer modification, +// so immediate changes to the slice will affect the result of future reads. +func (b *Buffer) Bytes() []byte { return b.buf[b.off:] } + +// AvailableBuffer returns an empty buffer with b.Available() capacity. +// This buffer is intended to be appended to and +// passed to an immediately succeeding [Buffer.Write] call. +// The buffer is only valid until the next write operation on b. +func (b *Buffer) AvailableBuffer() []byte { return b.buf[len(b.buf):] } + +// String returns the contents of the unread portion of the buffer +// as a string. If the [Buffer] is a nil pointer, it returns "". +// +// To build strings more efficiently, see the [strings.Builder] type. +func (b *Buffer) String() string { + if b == nil { + // Special case, useful in debugging. + return "" + } + return string(b.buf[b.off:]) +} + +// Peek returns the next n bytes without advancing the buffer. +// If Peek returns fewer than n bytes, it also returns [io.EOF]. +// The slice is only valid until the next call to a read or write method. +// The slice aliases the buffer content at least until the next buffer modification, +// so immediate changes to the slice will affect the result of future reads. +func (b *Buffer) Peek(n int) ([]byte, error) { + if b.Len() < n { + return b.buf[b.off:], io.EOF + } + return b.buf[b.off : b.off+n], nil +} + +// empty reports whether the unread portion of the buffer is empty. +func (b *Buffer) empty() bool { return len(b.buf) <= b.off } + +// Len returns the number of bytes of the unread portion of the buffer; +// b.Len() == len(b.Bytes()). +func (b *Buffer) Len() int { return len(b.buf) - b.off } + +// Cap returns the capacity of the buffer's underlying byte slice, that is, the +// total space allocated for the buffer's data. +func (b *Buffer) Cap() int { return cap(b.buf) } + +// Available returns how many bytes are unused in the buffer. +func (b *Buffer) Available() int { return cap(b.buf) - len(b.buf) } + +// Truncate discards all but the first n unread bytes from the buffer +// but continues to use the same allocated storage. +// It panics if n is negative or greater than the length of the buffer. +func (b *Buffer) Truncate(n int) { + if n == 0 { + b.Reset() + return + } + b.lastRead = opInvalid + if n < 0 || n > b.Len() { + panic("bytes.Buffer: truncation out of range") + } + b.buf = b.buf[:b.off+n] +} + +// Reset resets the buffer to be empty, +// but it retains the underlying storage for use by future writes. +// Reset is the same as [Buffer.Truncate](0). +func (b *Buffer) Reset() { + b.buf = b.buf[:0] + b.off = 0 + b.lastRead = opInvalid +} + +// tryGrowByReslice is an inlineable version of grow for the fast-case where the +// internal buffer only needs to be resliced. +// It returns the index where bytes should be written and whether it succeeded. +func (b *Buffer) tryGrowByReslice(n int) (int, bool) { + if l := len(b.buf); n <= cap(b.buf)-l { + b.buf = b.buf[:l+n] + return l, true + } + return 0, false +} + +// grow grows the buffer to guarantee space for n more bytes. +// It returns the index where bytes should be written. +// If the buffer can't grow it will panic with ErrTooLarge. +func (b *Buffer) grow(n int) int { + m := b.Len() + // If buffer is empty, reset to recover space. + if m == 0 && b.off != 0 { + b.Reset() + } + // Try to grow by means of a reslice. + if i, ok := b.tryGrowByReslice(n); ok { + return i + } + if b.buf == nil && n <= smallBufferSize { + b.buf = make([]byte, n, smallBufferSize) + return 0 + } + c := cap(b.buf) + if n <= c/2-m { + // We can slide things down instead of allocating a new + // slice. We only need m+n <= c to slide, but + // we instead let capacity get twice as large so we + // don't spend all our time copying. + copy(b.buf, b.buf[b.off:]) + } else if c > maxInt-c-n { + panic(ErrTooLarge) + } else { + // Add b.off to account for b.buf[:b.off] being sliced off the front. + b.buf = growSlice(b.buf[b.off:], b.off+n) + } + // Restore b.off and len(b.buf). + b.off = 0 + b.buf = b.buf[:m+n] + return m +} + +// Grow grows the buffer's capacity, if necessary, to guarantee space for +// another n bytes. After Grow(n), at least n bytes can be written to the +// buffer without another allocation. +// If n is negative, Grow will panic. +// If the buffer can't grow it will panic with [ErrTooLarge]. +func (b *Buffer) Grow(n int) { + if n < 0 { + panic("bytes.Buffer.Grow: negative count") + } + m := b.grow(n) + b.buf = b.buf[:m] +} + +// Write appends the contents of p to the buffer, growing the buffer as +// needed. The return value n is the length of p; err is always nil. If the +// buffer becomes too large, Write will panic with [ErrTooLarge]. +func (b *Buffer) Write(p []byte) (n int, err error) { + b.lastRead = opInvalid + m, ok := b.tryGrowByReslice(len(p)) + if !ok { + m = b.grow(len(p)) + } + return copy(b.buf[m:], p), nil +} + +// WriteString appends the contents of s to the buffer, growing the buffer as +// needed. The return value n is the length of s; err is always nil. If the +// buffer becomes too large, WriteString will panic with [ErrTooLarge]. +func (b *Buffer) WriteString(s string) (n int, err error) { + b.lastRead = opInvalid + m, ok := b.tryGrowByReslice(len(s)) + if !ok { + m = b.grow(len(s)) + } + return copy(b.buf[m:], s), nil +} + +// MinRead is the minimum slice size passed to a [Buffer.Read] call by +// [Buffer.ReadFrom]. As long as the [Buffer] has at least MinRead bytes beyond +// what is required to hold the contents of r, [Buffer.ReadFrom] will not grow the +// underlying buffer. +const MinRead = 512 + +// ReadFrom reads data from r until EOF and appends it to the buffer, growing +// the buffer as needed. The return value n is the number of bytes read. Any +// error except io.EOF encountered during the read is also returned. If the +// buffer becomes too large, ReadFrom will panic with [ErrTooLarge]. +func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) { + b.lastRead = opInvalid + for { + i := b.grow(MinRead) + b.buf = b.buf[:i] + m, e := r.Read(b.buf[i:cap(b.buf)]) + if m < 0 { + panic(errNegativeRead) + } + + b.buf = b.buf[:i+m] + n += int64(m) + if e == io.EOF { + return n, nil // e is EOF, so return nil explicitly + } + if e != nil { + return n, e + } + } +} + +// growSlice grows b by n, preserving the original content of b. +// If the allocation fails, it panics with ErrTooLarge. +func growSlice(b []byte, n int) []byte { + defer func() { + if recover() != nil { + panic(ErrTooLarge) + } + }() + // TODO(http://golang.org/issue/51462): We should rely on the append-make + // pattern so that the compiler can call runtime.growslice. For example: + // return append(b, make([]byte, n)...) + // This avoids unnecessary zero-ing of the first len(b) bytes of the + // allocated slice, but this pattern causes b to escape onto the heap. + // + // Instead use the append-make pattern with a nil slice to ensure that + // we allocate buffers rounded up to the closest size class. + c := len(b) + n // ensure enough space for n elements + if c < 2*cap(b) { + // The growth rate has historically always been 2x. In the future, + // we could rely purely on append to determine the growth rate. + c = 2 * cap(b) + } + b2 := append([]byte(nil), make([]byte, c)...) + i := copy(b2, b) + return b2[:i] +} + +// WriteTo writes data to w until the buffer is drained or an error occurs. +// The return value n is the number of bytes written; it always fits into an +// int, but it is int64 to match the [io.WriterTo] interface. Any error +// encountered during the write is also returned. +func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) { + b.lastRead = opInvalid + if nBytes := b.Len(); nBytes > 0 { + m, e := w.Write(b.buf[b.off:]) + if m > nBytes { + panic("bytes.Buffer.WriteTo: invalid Write count") + } + b.off += m + n = int64(m) + if e != nil { + return n, e + } + // all bytes should have been written, by definition of + // Write method in io.Writer + if m != nBytes { + return n, io.ErrShortWrite + } + } + // Buffer is now empty; reset. + b.Reset() + return n, nil +} + +// WriteByte appends the byte c to the buffer, growing the buffer as needed. +// The returned error is always nil, but is included to match [bufio.Writer]'s +// WriteByte. If the buffer becomes too large, WriteByte will panic with +// [ErrTooLarge]. +func (b *Buffer) WriteByte(c byte) error { + b.lastRead = opInvalid + m, ok := b.tryGrowByReslice(1) + if !ok { + m = b.grow(1) + } + b.buf[m] = c + return nil +} + +// WriteRune appends the UTF-8 encoding of Unicode code point r to the +// buffer, returning its length and an error, which is always nil but is +// included to match [bufio.Writer]'s WriteRune. The buffer is grown as needed; +// if it becomes too large, WriteRune will panic with [ErrTooLarge]. +func (b *Buffer) WriteRune(r rune) (n int, err error) { + // Compare as uint32 to correctly handle negative runes. + if uint32(r) < utf8.RuneSelf { + b.WriteByte(byte(r)) + return 1, nil + } + b.lastRead = opInvalid + m, ok := b.tryGrowByReslice(utf8.UTFMax) + if !ok { + m = b.grow(utf8.UTFMax) + } + b.buf = utf8.AppendRune(b.buf[:m], r) + return len(b.buf) - m, nil +} + +// Read reads the next len(p) bytes from the buffer or until the buffer +// is drained. The return value n is the number of bytes read. If the +// buffer has no data to return, err is [io.EOF] (unless len(p) is zero); +// otherwise it is nil. +func (b *Buffer) Read(p []byte) (n int, err error) { + b.lastRead = opInvalid + if b.empty() { + // Buffer is empty, reset to recover space. + b.Reset() + if len(p) == 0 { + return 0, nil + } + return 0, io.EOF + } + n = copy(p, b.buf[b.off:]) + b.off += n + if n > 0 { + b.lastRead = opRead + } + return n, nil +} + +// Next returns a slice containing the next n bytes from the buffer, +// advancing the buffer as if the bytes had been returned by [Buffer.Read]. +// If there are fewer than n bytes in the buffer, Next returns the entire buffer. +// The slice is only valid until the next call to a read or write method. +func (b *Buffer) Next(n int) []byte { + b.lastRead = opInvalid + m := b.Len() + if n > m { + n = m + } + data := b.buf[b.off : b.off+n] + b.off += n + if n > 0 { + b.lastRead = opRead + } + return data +} + +// ReadByte reads and returns the next byte from the buffer. +// If no byte is available, it returns error [io.EOF]. +func (b *Buffer) ReadByte() (byte, error) { + if b.empty() { + // Buffer is empty, reset to recover space. + b.Reset() + return 0, io.EOF + } + c := b.buf[b.off] + b.off++ + b.lastRead = opRead + return c, nil +} + +// ReadRune reads and returns the next UTF-8-encoded +// Unicode code point from the buffer. +// If no bytes are available, the error returned is io.EOF. +// If the bytes are an erroneous UTF-8 encoding, it +// consumes one byte and returns U+FFFD, 1. +func (b *Buffer) ReadRune() (r rune, size int, err error) { + if b.empty() { + // Buffer is empty, reset to recover space. + b.Reset() + return 0, 0, io.EOF + } + c := b.buf[b.off] + if c < utf8.RuneSelf { + b.off++ + b.lastRead = opReadRune1 + return rune(c), 1, nil + } + r, n := utf8.DecodeRune(b.buf[b.off:]) + b.off += n + b.lastRead = readOp(n) + return r, n, nil +} + +// UnreadRune unreads the last rune returned by [Buffer.ReadRune]. +// If the most recent read or write operation on the buffer was +// not a successful [Buffer.ReadRune], UnreadRune returns an error. (In this regard +// it is stricter than [Buffer.UnreadByte], which will unread the last byte +// from any read operation.) +func (b *Buffer) UnreadRune() error { + if b.lastRead <= opInvalid { + return errors.New("bytes.Buffer: UnreadRune: previous operation was not a successful ReadRune") + } + if b.off >= int(b.lastRead) { + b.off -= int(b.lastRead) + } + b.lastRead = opInvalid + return nil +} + +var errUnreadByte = errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read") + +// UnreadByte unreads the last byte returned by the most recent successful +// read operation that read at least one byte. If a write has happened since +// the last read, if the last read returned an error, or if the read read zero +// bytes, UnreadByte returns an error. +func (b *Buffer) UnreadByte() error { + if b.lastRead == opInvalid { + return errUnreadByte + } + b.lastRead = opInvalid + if b.off > 0 { + b.off-- + } + return nil +} + +// ReadBytes reads until the first occurrence of delim in the input, +// returning a slice containing the data up to and including the delimiter. +// If ReadBytes encounters an error before finding a delimiter, +// it returns the data read before the error and the error itself (often [io.EOF]). +// ReadBytes returns err != nil if and only if the returned data does not end in +// delim. +func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) { + slice, err := b.readSlice(delim) + // return a copy of slice. The buffer's backing array may + // be overwritten by later calls. + line = append(line, slice...) + return line, err +} + +// readSlice is like ReadBytes but returns a reference to internal buffer data. +func (b *Buffer) readSlice(delim byte) (line []byte, err error) { + i := IndexByte(b.buf[b.off:], delim) + end := b.off + i + 1 + if i < 0 { + end = len(b.buf) + err = io.EOF + } + line = b.buf[b.off:end] + b.off = end + b.lastRead = opRead + return line, err +} + +// ReadString reads until the first occurrence of delim in the input, +// returning a string containing the data up to and including the delimiter. +// If ReadString encounters an error before finding a delimiter, +// it returns the data read before the error and the error itself (often [io.EOF]). +// ReadString returns err != nil if and only if the returned data does not end +// in delim. +func (b *Buffer) ReadString(delim byte) (line string, err error) { + slice, err := b.readSlice(delim) + return string(slice), err +} + +// NewBuffer creates and initializes a new [Buffer] using buf as its +// initial contents. The new [Buffer] takes ownership of buf, and the +// caller should not use buf after this call. NewBuffer is intended to +// prepare a [Buffer] to read existing data. It can also be used to set +// the initial size of the internal buffer for writing. To do that, +// buf should have the desired capacity but a length of zero. +// +// In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is +// sufficient to initialize a [Buffer]. +func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} } + +// NewBufferString creates and initializes a new [Buffer] using string s as its +// initial contents. It is intended to prepare a buffer to read an existing +// string. +// +// In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is +// sufficient to initialize a [Buffer]. +func NewBufferString(s string) *Buffer { + return &Buffer{buf: []byte(s)} +} diff --git a/go/src/bytes/buffer_test.go b/go/src/bytes/buffer_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9c1ba0a838054f38d7d68890312843af7daf594d --- /dev/null +++ b/go/src/bytes/buffer_test.go @@ -0,0 +1,781 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes_test + +import ( + . "bytes" + "fmt" + "internal/testenv" + "io" + "math/rand" + "strconv" + "testing" + "unicode/utf8" +) + +const N = 10000 // make this bigger for a larger (and slower) test +var testString string // test data for write tests +var testBytes []byte // test data; same as testString but as a slice. + +type negativeReader struct{} + +func (r *negativeReader) Read([]byte) (int, error) { return -1, nil } + +func init() { + testBytes = make([]byte, N) + for i := 0; i < N; i++ { + testBytes[i] = 'a' + byte(i%26) + } + testString = string(testBytes) +} + +// Verify that contents of buf match the string s. +func check(t *testing.T, testname string, buf *Buffer, s string) { + bytes := buf.Bytes() + str := buf.String() + if buf.Len() != len(bytes) { + t.Errorf("%s: buf.Len() == %d, len(buf.Bytes()) == %d", testname, buf.Len(), len(bytes)) + } + + if buf.Len() != len(str) { + t.Errorf("%s: buf.Len() == %d, len(buf.String()) == %d", testname, buf.Len(), len(str)) + } + + if buf.Len() != len(s) { + t.Errorf("%s: buf.Len() == %d, len(s) == %d", testname, buf.Len(), len(s)) + } + + if string(bytes) != s { + t.Errorf("%s: string(buf.Bytes()) == %q, s == %q", testname, string(bytes), s) + } +} + +// Fill buf through n writes of string fus. +// The initial contents of buf corresponds to the string s; +// the result is the final contents of buf returned as a string. +func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus string) string { + check(t, testname+" (fill 1)", buf, s) + for ; n > 0; n-- { + m, err := buf.WriteString(fus) + if m != len(fus) { + t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fus)) + } + if err != nil { + t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err) + } + s += fus + check(t, testname+" (fill 4)", buf, s) + } + return s +} + +// Fill buf through n writes of byte slice fub. +// The initial contents of buf corresponds to the string s; +// the result is the final contents of buf returned as a string. +func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub []byte) string { + check(t, testname+" (fill 1)", buf, s) + for ; n > 0; n-- { + m, err := buf.Write(fub) + if m != len(fub) { + t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fub)) + } + if err != nil { + t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err) + } + s += string(fub) + check(t, testname+" (fill 4)", buf, s) + } + return s +} + +func TestNewBuffer(t *testing.T) { + buf := NewBuffer(testBytes) + check(t, "NewBuffer", buf, testString) +} + +var buf Buffer + +// Calling NewBuffer and immediately shallow copying the Buffer struct +// should not result in any allocations. +// This can be used to reset the underlying []byte of an existing Buffer. +func TestNewBufferShallow(t *testing.T) { + testenv.SkipIfOptimizationOff(t) + n := testing.AllocsPerRun(1000, func() { + buf = *NewBuffer(testBytes) + }) + if n > 0 { + t.Errorf("allocations occurred while shallow copying") + } + check(t, "NewBuffer", &buf, testString) +} + +func TestNewBufferString(t *testing.T) { + buf := NewBufferString(testString) + check(t, "NewBufferString", buf, testString) +} + +// Empty buf through repeated reads into fub. +// The initial contents of buf corresponds to the string s. +func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) { + check(t, testname+" (empty 1)", buf, s) + + for { + n, err := buf.Read(fub) + if n == 0 { + break + } + if err != nil { + t.Errorf(testname+" (empty 2): err should always be nil, found err == %s", err) + } + s = s[n:] + check(t, testname+" (empty 3)", buf, s) + } + + check(t, testname+" (empty 4)", buf, "") +} + +func TestBasicOperations(t *testing.T) { + var buf Buffer + + for i := 0; i < 5; i++ { + check(t, "TestBasicOperations (1)", &buf, "") + + buf.Reset() + check(t, "TestBasicOperations (2)", &buf, "") + + buf.Truncate(0) + check(t, "TestBasicOperations (3)", &buf, "") + + n, err := buf.Write(testBytes[0:1]) + if want := 1; err != nil || n != want { + t.Errorf("Write: got (%d, %v), want (%d, %v)", n, err, want, nil) + } + check(t, "TestBasicOperations (4)", &buf, "a") + + buf.WriteByte(testString[1]) + check(t, "TestBasicOperations (5)", &buf, "ab") + + n, err = buf.Write(testBytes[2:26]) + if want := 24; err != nil || n != want { + t.Errorf("Write: got (%d, %v), want (%d, %v)", n, err, want, nil) + } + check(t, "TestBasicOperations (6)", &buf, testString[0:26]) + + buf.Truncate(26) + check(t, "TestBasicOperations (7)", &buf, testString[0:26]) + + buf.Truncate(20) + check(t, "TestBasicOperations (8)", &buf, testString[0:20]) + + empty(t, "TestBasicOperations (9)", &buf, testString[0:20], make([]byte, 5)) + empty(t, "TestBasicOperations (10)", &buf, "", make([]byte, 100)) + + buf.WriteByte(testString[1]) + c, err := buf.ReadByte() + if want := testString[1]; err != nil || c != want { + t.Errorf("ReadByte: got (%q, %v), want (%q, %v)", c, err, want, nil) + } + c, err = buf.ReadByte() + if err != io.EOF { + t.Errorf("ReadByte: got (%q, %v), want (%q, %v)", c, err, byte(0), io.EOF) + } + } +} + +func TestLargeStringWrites(t *testing.T) { + var buf Buffer + limit := 30 + if testing.Short() { + limit = 9 + } + for i := 3; i < limit; i += 3 { + s := fillString(t, "TestLargeWrites (1)", &buf, "", 5, testString) + empty(t, "TestLargeStringWrites (2)", &buf, s, make([]byte, len(testString)/i)) + } + check(t, "TestLargeStringWrites (3)", &buf, "") +} + +func TestLargeByteWrites(t *testing.T) { + var buf Buffer + limit := 30 + if testing.Short() { + limit = 9 + } + for i := 3; i < limit; i += 3 { + s := fillBytes(t, "TestLargeWrites (1)", &buf, "", 5, testBytes) + empty(t, "TestLargeByteWrites (2)", &buf, s, make([]byte, len(testString)/i)) + } + check(t, "TestLargeByteWrites (3)", &buf, "") +} + +func TestLargeStringReads(t *testing.T) { + var buf Buffer + for i := 3; i < 30; i += 3 { + s := fillString(t, "TestLargeReads (1)", &buf, "", 5, testString[:len(testString)/i]) + empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(testString))) + } + check(t, "TestLargeStringReads (3)", &buf, "") +} + +func TestLargeByteReads(t *testing.T) { + var buf Buffer + for i := 3; i < 30; i += 3 { + s := fillBytes(t, "TestLargeReads (1)", &buf, "", 5, testBytes[:len(testBytes)/i]) + empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(testString))) + } + check(t, "TestLargeByteReads (3)", &buf, "") +} + +func TestMixedReadsAndWrites(t *testing.T) { + var buf Buffer + s := "" + for i := 0; i < 50; i++ { + wlen := rand.Intn(len(testString)) + if i%2 == 0 { + s = fillString(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testString[0:wlen]) + } else { + s = fillBytes(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testBytes[0:wlen]) + } + + rlen := rand.Intn(len(testString)) + fub := make([]byte, rlen) + n, _ := buf.Read(fub) + s = s[n:] + } + empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len())) +} + +func TestCapWithPreallocatedSlice(t *testing.T) { + buf := NewBuffer(make([]byte, 10)) + n := buf.Cap() + if n != 10 { + t.Errorf("expected 10, got %d", n) + } +} + +func TestCapWithSliceAndWrittenData(t *testing.T) { + buf := NewBuffer(make([]byte, 0, 10)) + buf.Write([]byte("test")) + n := buf.Cap() + if n != 10 { + t.Errorf("expected 10, got %d", n) + } +} + +func TestNil(t *testing.T) { + var b *Buffer + if b.String() != "" { + t.Errorf("expected ; got %q", b.String()) + } +} + +func TestReadFrom(t *testing.T) { + var buf Buffer + for i := 3; i < 30; i += 3 { + s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, testBytes[:len(testBytes)/i]) + var b Buffer + b.ReadFrom(&buf) + empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(testString))) + } +} + +type panicReader struct{ panic bool } + +func (r panicReader) Read(p []byte) (int, error) { + if r.panic { + panic("oops") + } + return 0, io.EOF +} + +// Make sure that an empty Buffer remains empty when +// it is "grown" before a Read that panics +func TestReadFromPanicReader(t *testing.T) { + + // First verify non-panic behaviour + var buf Buffer + i, err := buf.ReadFrom(panicReader{}) + if err != nil { + t.Fatal(err) + } + if i != 0 { + t.Fatalf("unexpected return from bytes.ReadFrom (1): got: %d, want %d", i, 0) + } + check(t, "TestReadFromPanicReader (1)", &buf, "") + + // Confirm that when Reader panics, the empty buffer remains empty + var buf2 Buffer + defer func() { + recover() + check(t, "TestReadFromPanicReader (2)", &buf2, "") + }() + buf2.ReadFrom(panicReader{panic: true}) +} + +func TestReadFromNegativeReader(t *testing.T) { + var b Buffer + defer func() { + switch err := recover().(type) { + case nil: + t.Fatal("bytes.Buffer.ReadFrom didn't panic") + case error: + // this is the error string of errNegativeRead + wantError := "bytes.Buffer: reader returned negative count from Read" + if err.Error() != wantError { + t.Fatalf("recovered panic: got %v, want %v", err.Error(), wantError) + } + default: + t.Fatalf("unexpected panic value: %#v", err) + } + }() + + b.ReadFrom(new(negativeReader)) +} + +func TestWriteTo(t *testing.T) { + var buf Buffer + for i := 3; i < 30; i += 3 { + s := fillBytes(t, "TestWriteTo (1)", &buf, "", 5, testBytes[:len(testBytes)/i]) + var b Buffer + buf.WriteTo(&b) + empty(t, "TestWriteTo (2)", &b, s, make([]byte, len(testString))) + } +} + +func TestWriteAppend(t *testing.T) { + var got Buffer + var want []byte + for i := 0; i < 1000; i++ { + b := got.AvailableBuffer() + b = strconv.AppendInt(b, int64(i), 10) + want = strconv.AppendInt(want, int64(i), 10) + got.Write(b) + } + if !Equal(got.Bytes(), want) { + t.Fatalf("Bytes() = %q, want %q", &got, want) + } + + // With a sufficiently sized buffer, there should be no allocations. + n := testing.AllocsPerRun(100, func() { + got.Reset() + for i := 0; i < 1000; i++ { + b := got.AvailableBuffer() + b = strconv.AppendInt(b, int64(i), 10) + got.Write(b) + } + }) + if n > 0 { + t.Errorf("allocations occurred while appending") + } +} + +func TestRuneIO(t *testing.T) { + const NRune = 1000 + // Built a test slice while we write the data + b := make([]byte, utf8.UTFMax*NRune) + var buf Buffer + n := 0 + for r := rune(0); r < NRune; r++ { + size := utf8.EncodeRune(b[n:], r) + nbytes, err := buf.WriteRune(r) + if err != nil { + t.Fatalf("WriteRune(%U) error: %s", r, err) + } + if nbytes != size { + t.Fatalf("WriteRune(%U) expected %d, got %d", r, size, nbytes) + } + n += size + } + b = b[0:n] + + // Check the resulting bytes + if !Equal(buf.Bytes(), b) { + t.Fatalf("incorrect result from WriteRune: %q not %q", buf.Bytes(), b) + } + + p := make([]byte, utf8.UTFMax) + // Read it back with ReadRune + for r := rune(0); r < NRune; r++ { + size := utf8.EncodeRune(p, r) + nr, nbytes, err := buf.ReadRune() + if nr != r || nbytes != size || err != nil { + t.Fatalf("ReadRune(%U) got %U,%d not %U,%d (err=%s)", r, nr, nbytes, r, size, err) + } + } + + // Check that UnreadRune works + buf.Reset() + + // check at EOF + if err := buf.UnreadRune(); err == nil { + t.Fatal("UnreadRune at EOF: got no error") + } + if _, _, err := buf.ReadRune(); err == nil { + t.Fatal("ReadRune at EOF: got no error") + } + if err := buf.UnreadRune(); err == nil { + t.Fatal("UnreadRune after ReadRune at EOF: got no error") + } + + // check not at EOF + buf.Write(b) + for r := rune(0); r < NRune; r++ { + r1, size, _ := buf.ReadRune() + if err := buf.UnreadRune(); err != nil { + t.Fatalf("UnreadRune(%U) got error %q", r, err) + } + r2, nbytes, err := buf.ReadRune() + if r1 != r2 || r1 != r || nbytes != size || err != nil { + t.Fatalf("ReadRune(%U) after UnreadRune got %U,%d not %U,%d (err=%s)", r, r2, nbytes, r, size, err) + } + } +} + +func TestWriteInvalidRune(t *testing.T) { + // Invalid runes, including negative ones, should be written as + // utf8.RuneError. + for _, r := range []rune{-1, utf8.MaxRune + 1} { + var buf Buffer + buf.WriteRune(r) + check(t, fmt.Sprintf("TestWriteInvalidRune (%d)", r), &buf, "\uFFFD") + } +} + +func TestNext(t *testing.T) { + b := []byte{0, 1, 2, 3, 4} + tmp := make([]byte, 5) + for i := 0; i <= 5; i++ { + for j := i; j <= 5; j++ { + for k := 0; k <= 6; k++ { + // 0 <= i <= j <= 5; 0 <= k <= 6 + // Check that if we start with a buffer + // of length j at offset i and ask for + // Next(k), we get the right bytes. + buf := NewBuffer(b[0:j]) + n, _ := buf.Read(tmp[0:i]) + if n != i { + t.Fatalf("Read %d returned %d", i, n) + } + bb := buf.Next(k) + want := k + if want > j-i { + want = j - i + } + if len(bb) != want { + t.Fatalf("in %d,%d: len(Next(%d)) == %d", i, j, k, len(bb)) + } + for l, v := range bb { + if v != byte(l+i) { + t.Fatalf("in %d,%d: Next(%d)[%d] = %d, want %d", i, j, k, l, v, l+i) + } + } + } + } + } +} + +var readBytesTests = []struct { + buffer string + delim byte + expected []string + err error +}{ + {"", 0, []string{""}, io.EOF}, + {"a\x00", 0, []string{"a\x00"}, nil}, + {"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil}, + {"hello\x01world", 1, []string{"hello\x01"}, nil}, + {"foo\nbar", 0, []string{"foo\nbar"}, io.EOF}, + {"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil}, + {"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, io.EOF}, +} + +func TestReadBytes(t *testing.T) { + for _, test := range readBytesTests { + buf := NewBufferString(test.buffer) + var err error + for _, expected := range test.expected { + var bytes []byte + bytes, err = buf.ReadBytes(test.delim) + if string(bytes) != expected { + t.Errorf("expected %q, got %q", expected, bytes) + } + if err != nil { + break + } + } + if err != test.err { + t.Errorf("expected error %v, got %v", test.err, err) + } + } +} + +func TestReadString(t *testing.T) { + for _, test := range readBytesTests { + buf := NewBufferString(test.buffer) + var err error + for _, expected := range test.expected { + var s string + s, err = buf.ReadString(test.delim) + if s != expected { + t.Errorf("expected %q, got %q", expected, s) + } + if err != nil { + break + } + } + if err != test.err { + t.Errorf("expected error %v, got %v", test.err, err) + } + } +} + +var peekTests = []struct { + buffer string + skip int + n int + expected string + err error +}{ + {"", 0, 0, "", nil}, + {"aaa", 0, 3, "aaa", nil}, + {"foobar", 0, 2, "fo", nil}, + {"a", 0, 2, "a", io.EOF}, + {"helloworld", 4, 3, "owo", nil}, + {"helloworld", 5, 5, "world", nil}, + {"helloworld", 5, 6, "world", io.EOF}, + {"helloworld", 10, 1, "", io.EOF}, +} + +func TestPeek(t *testing.T) { + for _, test := range peekTests { + buf := NewBufferString(test.buffer) + buf.Next(test.skip) + bytes, err := buf.Peek(test.n) + if string(bytes) != test.expected { + t.Errorf("expected %q, got %q", test.expected, bytes) + } + if err != test.err { + t.Errorf("expected error %v, got %v", test.err, err) + } + if buf.Len() != len(test.buffer)-test.skip { + t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer)-test.skip) + } + } +} + +func BenchmarkReadString(b *testing.B) { + const n = 32 << 10 + + data := make([]byte, n) + data[n-1] = 'x' + b.SetBytes(int64(n)) + for i := 0; i < b.N; i++ { + buf := NewBuffer(data) + _, err := buf.ReadString('x') + if err != nil { + b.Fatal(err) + } + } +} + +func TestGrow(t *testing.T) { + x := []byte{'x'} + y := []byte{'y'} + tmp := make([]byte, 72) + for _, growLen := range []int{0, 100, 1000, 10000, 100000} { + for _, startLen := range []int{0, 100, 1000, 10000, 100000} { + xBytes := Repeat(x, startLen) + + buf := NewBuffer(xBytes) + // If we read, this affects buf.off, which is good to test. + readBytes, _ := buf.Read(tmp) + yBytes := Repeat(y, growLen) + allocs := testing.AllocsPerRun(100, func() { + buf.Grow(growLen) + buf.Write(yBytes) + }) + // Check no allocation occurs in write, as long as we're single-threaded. + if allocs != 0 { + t.Errorf("allocation occurred during write") + } + // Check that buffer has correct data. + if !Equal(buf.Bytes()[0:startLen-readBytes], xBytes[readBytes:]) { + t.Errorf("bad initial data at %d %d", startLen, growLen) + } + if !Equal(buf.Bytes()[startLen-readBytes:startLen-readBytes+growLen], yBytes) { + t.Errorf("bad written data at %d %d", startLen, growLen) + } + } + } +} + +func TestGrowOverflow(t *testing.T) { + defer func() { + if err := recover(); err != ErrTooLarge { + t.Errorf("after too-large Grow, recover() = %v; want %v", err, ErrTooLarge) + } + }() + + buf := NewBuffer(make([]byte, 1)) + const maxInt = int(^uint(0) >> 1) + buf.Grow(maxInt) +} + +// Was a bug: used to give EOF reading empty slice at EOF. +func TestReadEmptyAtEOF(t *testing.T) { + b := new(Buffer) + slice := make([]byte, 0) + n, err := b.Read(slice) + if err != nil { + t.Errorf("read error: %v", err) + } + if n != 0 { + t.Errorf("wrong count; got %d want 0", n) + } +} + +func TestUnreadByte(t *testing.T) { + b := new(Buffer) + + // check at EOF + if err := b.UnreadByte(); err == nil { + t.Fatal("UnreadByte at EOF: got no error") + } + if _, err := b.ReadByte(); err == nil { + t.Fatal("ReadByte at EOF: got no error") + } + if err := b.UnreadByte(); err == nil { + t.Fatal("UnreadByte after ReadByte at EOF: got no error") + } + + // check not at EOF + b.WriteString("abcdefghijklmnopqrstuvwxyz") + + // after unsuccessful read + if n, err := b.Read(nil); n != 0 || err != nil { + t.Fatalf("Read(nil) = %d,%v; want 0,nil", n, err) + } + if err := b.UnreadByte(); err == nil { + t.Fatal("UnreadByte after Read(nil): got no error") + } + + // after successful read + if _, err := b.ReadBytes('m'); err != nil { + t.Fatalf("ReadBytes: %v", err) + } + if err := b.UnreadByte(); err != nil { + t.Fatalf("UnreadByte: %v", err) + } + c, err := b.ReadByte() + if err != nil { + t.Fatalf("ReadByte: %v", err) + } + if c != 'm' { + t.Errorf("ReadByte = %q; want %q", c, 'm') + } +} + +// Tests that we occasionally compact. Issue 5154. +func TestBufferGrowth(t *testing.T) { + var b Buffer + buf := make([]byte, 1024) + b.Write(buf[0:1]) + var cap0 int + for i := 0; i < 5<<10; i++ { + b.Write(buf) + b.Read(buf) + if i == 0 { + cap0 = b.Cap() + } + } + cap1 := b.Cap() + // (*Buffer).grow allows for 2x capacity slop before sliding, + // so set our error threshold at 3x. + if cap1 > cap0*3 { + t.Errorf("buffer cap = %d; too big (grew from %d)", cap1, cap0) + } +} + +func BenchmarkWriteByte(b *testing.B) { + const n = 4 << 10 + b.SetBytes(n) + buf := NewBuffer(make([]byte, n)) + for i := 0; i < b.N; i++ { + buf.Reset() + for i := 0; i < n; i++ { + buf.WriteByte('x') + } + } +} + +func BenchmarkWriteRune(b *testing.B) { + const n = 4 << 10 + const r = '☺' + b.SetBytes(int64(n * utf8.RuneLen(r))) + buf := NewBuffer(make([]byte, n*utf8.UTFMax)) + for i := 0; i < b.N; i++ { + buf.Reset() + for i := 0; i < n; i++ { + buf.WriteRune(r) + } + } +} + +// From Issue 5154. +func BenchmarkBufferNotEmptyWriteRead(b *testing.B) { + buf := make([]byte, 1024) + for i := 0; i < b.N; i++ { + var b Buffer + b.Write(buf[0:1]) + for i := 0; i < 5<<10; i++ { + b.Write(buf) + b.Read(buf) + } + } +} + +// Check that we don't compact too often. From Issue 5154. +func BenchmarkBufferFullSmallReads(b *testing.B) { + buf := make([]byte, 1024) + for i := 0; i < b.N; i++ { + var b Buffer + b.Write(buf) + for b.Len()+20 < b.Cap() { + b.Write(buf[:10]) + } + for i := 0; i < 5<<10; i++ { + b.Read(buf[:1]) + b.Write(buf[:1]) + } + } +} + +func BenchmarkBufferWriteBlock(b *testing.B) { + block := make([]byte, 1024) + for _, n := range []int{1 << 12, 1 << 16, 1 << 20} { + b.Run(fmt.Sprintf("N%d", n), func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + var bb Buffer + for bb.Len() < n { + bb.Write(block) + } + } + }) + } +} + +func BenchmarkBufferAppendNoCopy(b *testing.B) { + var bb Buffer + bb.Grow(16 << 20) + b.SetBytes(int64(bb.Available())) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + bb.Reset() + b := bb.AvailableBuffer() + b = b[:cap(b)] // use max capacity to simulate a large append operation + bb.Write(b) // should be nearly infinitely fast + } +} diff --git a/go/src/bytes/bytes.go b/go/src/bytes/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..87183c01955829a05b0bcde67757af945244ff1f --- /dev/null +++ b/go/src/bytes/bytes.go @@ -0,0 +1,1415 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package bytes implements functions for the manipulation of byte slices. +// It is analogous to the facilities of the [strings] package. +package bytes + +import ( + "internal/bytealg" + "math/bits" + "unicode" + "unicode/utf8" + _ "unsafe" // for linkname +) + +// Equal reports whether a and b +// are the same length and contain the same bytes. +// A nil argument is equivalent to an empty slice. +func Equal(a, b []byte) bool { + // Neither cmd/compile nor gccgo allocates for these string conversions. + return string(a) == string(b) +} + +// Compare returns an integer comparing two byte slices lexicographically. +// The result will be 0 if a == b, -1 if a < b, and +1 if a > b. +// A nil argument is equivalent to an empty slice. +func Compare(a, b []byte) int { + return bytealg.Compare(a, b) +} + +// explode splits s into a slice of UTF-8 sequences, one per Unicode code point (still slices of bytes), +// up to a maximum of n byte slices. Invalid UTF-8 sequences are chopped into individual bytes. +func explode(s []byte, n int) [][]byte { + if n <= 0 || n > len(s) { + n = len(s) + } + a := make([][]byte, n) + var size int + na := 0 + for len(s) > 0 { + if na+1 >= n { + a[na] = s + na++ + break + } + _, size = utf8.DecodeRune(s) + a[na] = s[0:size:size] + s = s[size:] + na++ + } + return a[0:na] +} + +// Count counts the number of non-overlapping instances of sep in s. +// If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s. +func Count(s, sep []byte) int { + // special case + if len(sep) == 0 { + return utf8.RuneCount(s) + 1 + } + if len(sep) == 1 { + return bytealg.Count(s, sep[0]) + } + n := 0 + for { + i := Index(s, sep) + if i == -1 { + return n + } + n++ + s = s[i+len(sep):] + } +} + +// Contains reports whether subslice is within b. +func Contains(b, subslice []byte) bool { + return Index(b, subslice) != -1 +} + +// ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b. +func ContainsAny(b []byte, chars string) bool { + return IndexAny(b, chars) >= 0 +} + +// ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b. +func ContainsRune(b []byte, r rune) bool { + return IndexRune(b, r) >= 0 +} + +// ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r). +func ContainsFunc(b []byte, f func(rune) bool) bool { + return IndexFunc(b, f) >= 0 +} + +// IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b. +func IndexByte(b []byte, c byte) int { + return bytealg.IndexByte(b, c) +} + +func indexBytePortable(s []byte, c byte) int { + for i, b := range s { + if b == c { + return i + } + } + return -1 +} + +// LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s. +func LastIndex(s, sep []byte) int { + n := len(sep) + switch { + case n == 0: + return len(s) + case n == 1: + return bytealg.LastIndexByte(s, sep[0]) + case n == len(s): + if Equal(s, sep) { + return 0 + } + return -1 + case n > len(s): + return -1 + } + return bytealg.LastIndexRabinKarp(s, sep) +} + +// LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s. +func LastIndexByte(s []byte, c byte) int { + return bytealg.LastIndexByte(s, c) +} + +// IndexRune interprets s as a sequence of UTF-8-encoded code points. +// It returns the byte index of the first occurrence in s of the given rune. +// It returns -1 if rune is not present in s. +// If r is [utf8.RuneError], it returns the first instance of any +// invalid UTF-8 byte sequence. +func IndexRune(s []byte, r rune) int { + const haveFastIndex = bytealg.MaxBruteForce > 0 + switch { + case 0 <= r && r < utf8.RuneSelf: + return IndexByte(s, byte(r)) + case r == utf8.RuneError: + for i := 0; i < len(s); { + r1, n := utf8.DecodeRune(s[i:]) + if r1 == utf8.RuneError { + return i + } + i += n + } + return -1 + case !utf8.ValidRune(r): + return -1 + default: + // Search for rune r using the last byte of its UTF-8 encoded form. + // The distribution of the last byte is more uniform compared to the + // first byte which has a 78% chance of being [240, 243, 244]. + var b [utf8.UTFMax]byte + n := utf8.EncodeRune(b[:], r) + last := n - 1 + i := last + fails := 0 + for i < len(s) { + if s[i] != b[last] { + o := IndexByte(s[i+1:], b[last]) + if o < 0 { + return -1 + } + i += o + 1 + } + // Step backwards comparing bytes. + for j := 1; j < n; j++ { + if s[i-j] != b[last-j] { + goto next + } + } + return i - last + next: + fails++ + i++ + if (haveFastIndex && fails > bytealg.Cutover(i)) && i < len(s) || + (!haveFastIndex && fails >= 4+i>>4 && i < len(s)) { + goto fallback + } + } + return -1 + + fallback: + // Switch to bytealg.Index, if available, or a brute force search when + // IndexByte returns too many false positives. + if haveFastIndex { + if j := bytealg.Index(s[i-last:], b[:n]); j >= 0 { + return i + j - last + } + } else { + // If bytealg.Index is not available a brute force search is + // ~1.5-3x faster than Rabin-Karp since n is small. + c0 := b[last] + c1 := b[last-1] // There are at least 2 chars to match + loop: + for ; i < len(s); i++ { + if s[i] == c0 && s[i-1] == c1 { + for k := 2; k < n; k++ { + if s[i-k] != b[last-k] { + continue loop + } + } + return i - last + } + } + } + return -1 + } +} + +// IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. +// It returns the byte index of the first occurrence in s of any of the Unicode +// code points in chars. It returns -1 if chars is empty or if there is no code +// point in common. +func IndexAny(s []byte, chars string) int { + if chars == "" { + // Avoid scanning all of s. + return -1 + } + if len(s) == 1 { + r := rune(s[0]) + if r >= utf8.RuneSelf { + // search utf8.RuneError. + for _, r = range chars { + if r == utf8.RuneError { + return 0 + } + } + return -1 + } + if bytealg.IndexByteString(chars, s[0]) >= 0 { + return 0 + } + return -1 + } + if len(chars) == 1 { + r := rune(chars[0]) + if r >= utf8.RuneSelf { + r = utf8.RuneError + } + return IndexRune(s, r) + } + if len(s) > 8 { + if as, isASCII := makeASCIISet(chars); isASCII { + for i, c := range s { + if as.contains(c) { + return i + } + } + return -1 + } + } + var width int + for i := 0; i < len(s); i += width { + r := rune(s[i]) + if r < utf8.RuneSelf { + if bytealg.IndexByteString(chars, s[i]) >= 0 { + return i + } + width = 1 + continue + } + r, width = utf8.DecodeRune(s[i:]) + if r != utf8.RuneError { + // r is 2 to 4 bytes + if len(chars) == width { + if chars == string(r) { + return i + } + continue + } + // Use bytealg.IndexString for performance if available. + if bytealg.MaxLen >= width { + if bytealg.IndexString(chars, string(r)) >= 0 { + return i + } + continue + } + } + for _, ch := range chars { + if r == ch { + return i + } + } + } + return -1 +} + +// LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code +// points. It returns the byte index of the last occurrence in s of any of +// the Unicode code points in chars. It returns -1 if chars is empty or if +// there is no code point in common. +func LastIndexAny(s []byte, chars string) int { + if chars == "" { + // Avoid scanning all of s. + return -1 + } + if len(s) > 8 { + if as, isASCII := makeASCIISet(chars); isASCII { + for i := len(s) - 1; i >= 0; i-- { + if as.contains(s[i]) { + return i + } + } + return -1 + } + } + if len(s) == 1 { + r := rune(s[0]) + if r >= utf8.RuneSelf { + for _, r = range chars { + if r == utf8.RuneError { + return 0 + } + } + return -1 + } + if bytealg.IndexByteString(chars, s[0]) >= 0 { + return 0 + } + return -1 + } + if len(chars) == 1 { + cr := rune(chars[0]) + if cr >= utf8.RuneSelf { + cr = utf8.RuneError + } + for i := len(s); i > 0; { + r, size := utf8.DecodeLastRune(s[:i]) + i -= size + if r == cr { + return i + } + } + return -1 + } + for i := len(s); i > 0; { + r := rune(s[i-1]) + if r < utf8.RuneSelf { + if bytealg.IndexByteString(chars, s[i-1]) >= 0 { + return i - 1 + } + i-- + continue + } + r, size := utf8.DecodeLastRune(s[:i]) + i -= size + if r != utf8.RuneError { + // r is 2 to 4 bytes + if len(chars) == size { + if chars == string(r) { + return i + } + continue + } + // Use bytealg.IndexString for performance if available. + if bytealg.MaxLen >= size { + if bytealg.IndexString(chars, string(r)) >= 0 { + return i + } + continue + } + } + for _, ch := range chars { + if r == ch { + return i + } + } + } + return -1 +} + +// Generic split: splits after each instance of sep, +// including sepSave bytes of sep in the subslices. +func genSplit(s, sep []byte, sepSave, n int) [][]byte { + if n == 0 { + return nil + } + if len(sep) == 0 { + return explode(s, n) + } + if n < 0 { + n = Count(s, sep) + 1 + } + if n > len(s)+1 { + n = len(s) + 1 + } + + a := make([][]byte, n) + n-- + i := 0 + for i < n { + m := Index(s, sep) + if m < 0 { + break + } + a[i] = s[: m+sepSave : m+sepSave] + s = s[m+len(sep):] + i++ + } + a[i] = s + return a[:i+1] +} + +// SplitN slices s into subslices separated by sep and returns a slice of +// the subslices between those separators. +// If sep is empty, SplitN splits after each UTF-8 sequence. +// The count determines the number of subslices to return: +// - n > 0: at most n subslices; the last subslice will be the unsplit remainder; +// - n == 0: the result is nil (zero subslices); +// - n < 0: all subslices. +// +// To split around the first instance of a separator, see [Cut]. +func SplitN(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) } + +// SplitAfterN slices s into subslices after each instance of sep and +// returns a slice of those subslices. +// If sep is empty, SplitAfterN splits after each UTF-8 sequence. +// The count determines the number of subslices to return: +// - n > 0: at most n subslices; the last subslice will be the unsplit remainder; +// - n == 0: the result is nil (zero subslices); +// - n < 0: all subslices. +func SplitAfterN(s, sep []byte, n int) [][]byte { + return genSplit(s, sep, len(sep), n) +} + +// Split slices s into all subslices separated by sep and returns a slice of +// the subslices between those separators. +// If sep is empty, Split splits after each UTF-8 sequence. +// It is equivalent to SplitN with a count of -1. +// +// To split around the first instance of a separator, see [Cut]. +func Split(s, sep []byte) [][]byte { return genSplit(s, sep, 0, -1) } + +// SplitAfter slices s into all subslices after each instance of sep and +// returns a slice of those subslices. +// If sep is empty, SplitAfter splits after each UTF-8 sequence. +// It is equivalent to SplitAfterN with a count of -1. +func SplitAfter(s, sep []byte) [][]byte { + return genSplit(s, sep, len(sep), -1) +} + +var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} + +// Fields interprets s as a sequence of UTF-8-encoded code points. +// It splits the slice s around each instance of one or more consecutive white space +// characters, as defined by [unicode.IsSpace], returning a slice of subslices of s or an +// empty slice if s contains only white space. Every element of the returned slice is +// non-empty. Unlike [Split], leading and trailing runs of white space characters +// are discarded. +func Fields(s []byte) [][]byte { + // First count the fields. + // This is an exact count if s is ASCII, otherwise it is an approximation. + n := 0 + wasSpace := 1 + // setBits is used to track which bits are set in the bytes of s. + setBits := uint8(0) + for i := 0; i < len(s); i++ { + r := s[i] + setBits |= r + isSpace := int(asciiSpace[r]) + n += wasSpace & ^isSpace + wasSpace = isSpace + } + + if setBits >= utf8.RuneSelf { + // Some runes in the input slice are not ASCII. + return FieldsFunc(s, unicode.IsSpace) + } + + // ASCII fast path + a := make([][]byte, n) + na := 0 + fieldStart := 0 + i := 0 + // Skip spaces in the front of the input. + for i < len(s) && asciiSpace[s[i]] != 0 { + i++ + } + fieldStart = i + for i < len(s) { + if asciiSpace[s[i]] == 0 { + i++ + continue + } + a[na] = s[fieldStart:i:i] + na++ + i++ + // Skip spaces in between fields. + for i < len(s) && asciiSpace[s[i]] != 0 { + i++ + } + fieldStart = i + } + if fieldStart < len(s) { // Last field might end at EOF. + a[na] = s[fieldStart:len(s):len(s)] + } + return a +} + +// FieldsFunc interprets s as a sequence of UTF-8-encoded code points. +// It splits the slice s at each run of code points c satisfying f(c) and +// returns a slice of subslices of s. If all code points in s satisfy f(c), or +// len(s) == 0, an empty slice is returned. Every element of the returned slice is +// non-empty. Unlike [Split], leading and trailing runs of code points +// satisfying f(c) are discarded. +// +// FieldsFunc makes no guarantees about the order in which it calls f(c) +// and assumes that f always returns the same value for a given c. +func FieldsFunc(s []byte, f func(rune) bool) [][]byte { + // A span is used to record a slice of s of the form s[start:end]. + // The start index is inclusive and the end index is exclusive. + type span struct { + start int + end int + } + spans := make([]span, 0, 32) + + // Find the field start and end indices. + // Doing this in a separate pass (rather than slicing the string s + // and collecting the result substrings right away) is significantly + // more efficient, possibly due to cache effects. + start := -1 // valid span start if >= 0 + for i := 0; i < len(s); { + r, size := utf8.DecodeRune(s[i:]) + if f(r) { + if start >= 0 { + spans = append(spans, span{start, i}) + start = -1 + } + } else { + if start < 0 { + start = i + } + } + i += size + } + + // Last field might end at EOF. + if start >= 0 { + spans = append(spans, span{start, len(s)}) + } + + // Create subslices from recorded field indices. + a := make([][]byte, len(spans)) + for i, span := range spans { + a[i] = s[span.start:span.end:span.end] + } + + return a +} + +// Join concatenates the elements of s to create a new byte slice. The separator +// sep is placed between elements in the resulting slice. +func Join(s [][]byte, sep []byte) []byte { + if len(s) == 0 { + return []byte{} + } + if len(s) == 1 { + // Just return a copy. + return append([]byte(nil), s[0]...) + } + + var n int + if len(sep) > 0 { + if len(sep) >= maxInt/(len(s)-1) { + panic("bytes: Join output length overflow") + } + n += len(sep) * (len(s) - 1) + } + for _, v := range s { + if len(v) > maxInt-n { + panic("bytes: Join output length overflow") + } + n += len(v) + } + + b := bytealg.MakeNoZero(n)[:n:n] + bp := copy(b, s[0]) + for _, v := range s[1:] { + bp += copy(b[bp:], sep) + bp += copy(b[bp:], v) + } + return b +} + +// HasPrefix reports whether the byte slice s begins with prefix. +func HasPrefix(s, prefix []byte) bool { + return len(s) >= len(prefix) && Equal(s[:len(prefix)], prefix) +} + +// HasSuffix reports whether the byte slice s ends with suffix. +func HasSuffix(s, suffix []byte) bool { + return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix) +} + +// Map returns a copy of the byte slice s with all its characters modified +// according to the mapping function. If mapping returns a negative value, the character is +// dropped from the byte slice with no replacement. The characters in s and the +// output are interpreted as UTF-8-encoded code points. +func Map(mapping func(r rune) rune, s []byte) []byte { + // In the worst case, the slice can grow when mapped, making + // things unpleasant. But it's so rare we barge in assuming it's + // fine. It could also shrink but that falls out naturally. + b := make([]byte, 0, len(s)) + for i := 0; i < len(s); { + r, wid := utf8.DecodeRune(s[i:]) + r = mapping(r) + if r >= 0 { + b = utf8.AppendRune(b, r) + } + i += wid + } + return b +} + +// Despite being an exported symbol, +// Repeat is linknamed by widely used packages. +// Notable members of the hall of shame include: +// - gitee.com/quant1x/num +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +// Note that this comment is not part of the doc comment. +// +//go:linkname Repeat + +// Repeat returns a new byte slice consisting of count copies of b. +// +// It panics if count is negative or if the result of (len(b) * count) +// overflows. +func Repeat(b []byte, count int) []byte { + if count == 0 { + return []byte{} + } + + // Since we cannot return an error on overflow, + // we should panic if the repeat will generate an overflow. + // See golang.org/issue/16237. + if count < 0 { + panic("bytes: negative Repeat count") + } + hi, lo := bits.Mul(uint(len(b)), uint(count)) + if hi > 0 || lo > uint(maxInt) { + panic("bytes: Repeat output length overflow") + } + n := int(lo) // lo = len(b) * count + + if len(b) == 0 { + return []byte{} + } + + // Past a certain chunk size it is counterproductive to use + // larger chunks as the source of the write, as when the source + // is too large we are basically just thrashing the CPU D-cache. + // So if the result length is larger than an empirically-found + // limit (8KB), we stop growing the source string once the limit + // is reached and keep reusing the same source string - that + // should therefore be always resident in the L1 cache - until we + // have completed the construction of the result. + // This yields significant speedups (up to +100%) in cases where + // the result length is large (roughly, over L2 cache size). + const chunkLimit = 8 * 1024 + chunkMax := n + if chunkMax > chunkLimit { + chunkMax = chunkLimit / len(b) * len(b) + if chunkMax == 0 { + chunkMax = len(b) + } + } + nb := bytealg.MakeNoZero(n)[:n:n] + bp := copy(nb, b) + for bp < n { + chunk := min(bp, chunkMax) + bp += copy(nb[bp:], nb[:chunk]) + } + return nb +} + +// ToUpper returns a copy of the byte slice s with all Unicode letters mapped to +// their upper case. +func ToUpper(s []byte) []byte { + isASCII, hasLower := true, false + for i := 0; i < len(s); i++ { + c := s[i] + if c >= utf8.RuneSelf { + isASCII = false + break + } + hasLower = hasLower || ('a' <= c && c <= 'z') + } + + if isASCII { // optimize for ASCII-only byte slices. + if !hasLower { + // Just return a copy. + return append([]byte(""), s...) + } + b := bytealg.MakeNoZero(len(s))[:len(s):len(s)] + for i := 0; i < len(s); i++ { + c := s[i] + if 'a' <= c && c <= 'z' { + c -= 'a' - 'A' + } + b[i] = c + } + return b + } + return Map(unicode.ToUpper, s) +} + +// ToLower returns a copy of the byte slice s with all Unicode letters mapped to +// their lower case. +func ToLower(s []byte) []byte { + isASCII, hasUpper := true, false + for i := 0; i < len(s); i++ { + c := s[i] + if c >= utf8.RuneSelf { + isASCII = false + break + } + hasUpper = hasUpper || ('A' <= c && c <= 'Z') + } + + if isASCII { // optimize for ASCII-only byte slices. + if !hasUpper { + return append([]byte(""), s...) + } + b := bytealg.MakeNoZero(len(s))[:len(s):len(s)] + for i := 0; i < len(s); i++ { + c := s[i] + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + b[i] = c + } + return b + } + return Map(unicode.ToLower, s) +} + +// ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case. +func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) } + +// ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their +// upper case, giving priority to the special casing rules. +func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte { + return Map(c.ToUpper, s) +} + +// ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their +// lower case, giving priority to the special casing rules. +func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte { + return Map(c.ToLower, s) +} + +// ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their +// title case, giving priority to the special casing rules. +func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte { + return Map(c.ToTitle, s) +} + +// ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytes +// representing invalid UTF-8 replaced with the bytes in replacement, which may be empty. +func ToValidUTF8(s, replacement []byte) []byte { + b := make([]byte, 0, len(s)+len(replacement)) + invalid := false // previous byte was from an invalid UTF-8 sequence + for i := 0; i < len(s); { + c := s[i] + if c < utf8.RuneSelf { + i++ + invalid = false + b = append(b, c) + continue + } + _, wid := utf8.DecodeRune(s[i:]) + if wid == 1 { + i++ + if !invalid { + invalid = true + b = append(b, replacement...) + } + continue + } + invalid = false + b = append(b, s[i:i+wid]...) + i += wid + } + return b +} + +// isSeparator reports whether the rune could mark a word boundary. +// TODO: update when package unicode captures more of the properties. +func isSeparator(r rune) bool { + // ASCII alphanumerics and underscore are not separators + if r <= 0x7F { + switch { + case '0' <= r && r <= '9': + return false + case 'a' <= r && r <= 'z': + return false + case 'A' <= r && r <= 'Z': + return false + case r == '_': + return false + } + return true + } + // Letters and digits are not separators + if unicode.IsLetter(r) || unicode.IsDigit(r) { + return false + } + // Otherwise, all we can do for now is treat spaces as separators. + return unicode.IsSpace(r) +} + +// Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode letters that begin +// words mapped to their title case. +// +// Deprecated: The rule Title uses for word boundaries does not handle Unicode +// punctuation properly. Use golang.org/x/text/cases instead. +func Title(s []byte) []byte { + // Use a closure here to remember state. + // Hackish but effective. Depends on Map scanning in order and calling + // the closure once per rune. + prev := ' ' + return Map( + func(r rune) rune { + if isSeparator(prev) { + prev = r + return unicode.ToTitle(r) + } + prev = r + return r + }, + s) +} + +// TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off +// all leading UTF-8-encoded code points c that satisfy f(c). +func TrimLeftFunc(s []byte, f func(r rune) bool) []byte { + i := indexFunc(s, f, false) + if i == -1 { + return nil + } + return s[i:] +} + +// TrimRightFunc returns a subslice of s by slicing off all trailing +// UTF-8-encoded code points c that satisfy f(c). +func TrimRightFunc(s []byte, f func(r rune) bool) []byte { + i := lastIndexFunc(s, f, false) + if i >= 0 && s[i] >= utf8.RuneSelf { + _, wid := utf8.DecodeRune(s[i:]) + i += wid + } else { + i++ + } + return s[0:i] +} + +// TrimFunc returns a subslice of s by slicing off all leading and trailing +// UTF-8-encoded code points c that satisfy f(c). +func TrimFunc(s []byte, f func(r rune) bool) []byte { + return TrimRightFunc(TrimLeftFunc(s, f), f) +} + +// TrimPrefix returns s without the provided leading prefix string. +// If s doesn't start with prefix, s is returned unchanged. +func TrimPrefix(s, prefix []byte) []byte { + if HasPrefix(s, prefix) { + return s[len(prefix):] + } + return s +} + +// TrimSuffix returns s without the provided trailing suffix string. +// If s doesn't end with suffix, s is returned unchanged. +func TrimSuffix(s, suffix []byte) []byte { + if HasSuffix(s, suffix) { + return s[:len(s)-len(suffix)] + } + return s +} + +// IndexFunc interprets s as a sequence of UTF-8-encoded code points. +// It returns the byte index in s of the first Unicode +// code point satisfying f(c), or -1 if none do. +func IndexFunc(s []byte, f func(r rune) bool) int { + return indexFunc(s, f, true) +} + +// LastIndexFunc interprets s as a sequence of UTF-8-encoded code points. +// It returns the byte index in s of the last Unicode +// code point satisfying f(c), or -1 if none do. +func LastIndexFunc(s []byte, f func(r rune) bool) int { + return lastIndexFunc(s, f, true) +} + +// indexFunc is the same as IndexFunc except that if +// truth==false, the sense of the predicate function is +// inverted. +func indexFunc(s []byte, f func(r rune) bool, truth bool) int { + start := 0 + for start < len(s) { + r, wid := utf8.DecodeRune(s[start:]) + if f(r) == truth { + return start + } + start += wid + } + return -1 +} + +// lastIndexFunc is the same as LastIndexFunc except that if +// truth==false, the sense of the predicate function is +// inverted. +func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int { + for i := len(s); i > 0; { + r, size := rune(s[i-1]), 1 + if r >= utf8.RuneSelf { + r, size = utf8.DecodeLastRune(s[0:i]) + } + i -= size + if f(r) == truth { + return i + } + } + return -1 +} + +// asciiSet is a 32-byte value, where each bit represents the presence of a +// given ASCII character in the set. The 128-bits of the lower 16 bytes, +// starting with the least-significant bit of the lowest word to the +// most-significant bit of the highest word, map to the full range of all +// 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed, +// ensuring that any non-ASCII character will be reported as not in the set. +// This allocates a total of 32 bytes even though the upper half +// is unused to avoid bounds checks in asciiSet.contains. +type asciiSet [8]uint32 + +// makeASCIISet creates a set of ASCII characters and reports whether all +// characters in chars are ASCII. +func makeASCIISet(chars string) (as asciiSet, ok bool) { + for i := 0; i < len(chars); i++ { + c := chars[i] + if c >= utf8.RuneSelf { + return as, false + } + as[c/32] |= 1 << (c % 32) + } + return as, true +} + +// contains reports whether c is inside the set. +func (as *asciiSet) contains(c byte) bool { + return (as[c/32] & (1 << (c % 32))) != 0 +} + +// containsRune is a simplified version of strings.ContainsRune +// to avoid importing the strings package. +// We avoid bytes.ContainsRune to avoid allocating a temporary copy of s. +func containsRune(s string, r rune) bool { + for _, c := range s { + if c == r { + return true + } + } + return false +} + +// Trim returns a subslice of s by slicing off all leading and +// trailing UTF-8-encoded code points contained in cutset. +func Trim(s []byte, cutset string) []byte { + if len(s) == 0 { + // This is what we've historically done. + return nil + } + if cutset == "" { + return s + } + if len(cutset) == 1 && cutset[0] < utf8.RuneSelf { + return trimLeftByte(trimRightByte(s, cutset[0]), cutset[0]) + } + if as, ok := makeASCIISet(cutset); ok { + return trimLeftASCII(trimRightASCII(s, &as), &as) + } + return trimLeftUnicode(trimRightUnicode(s, cutset), cutset) +} + +// TrimLeft returns a subslice of s by slicing off all leading +// UTF-8-encoded code points contained in cutset. +func TrimLeft(s []byte, cutset string) []byte { + if len(s) == 0 { + // This is what we've historically done. + return nil + } + if cutset == "" { + return s + } + if len(cutset) == 1 && cutset[0] < utf8.RuneSelf { + return trimLeftByte(s, cutset[0]) + } + if as, ok := makeASCIISet(cutset); ok { + return trimLeftASCII(s, &as) + } + return trimLeftUnicode(s, cutset) +} + +func trimLeftByte(s []byte, c byte) []byte { + for len(s) > 0 && s[0] == c { + s = s[1:] + } + if len(s) == 0 { + // This is what we've historically done. + return nil + } + return s +} + +func trimLeftASCII(s []byte, as *asciiSet) []byte { + for len(s) > 0 { + if !as.contains(s[0]) { + break + } + s = s[1:] + } + if len(s) == 0 { + // This is what we've historically done. + return nil + } + return s +} + +func trimLeftUnicode(s []byte, cutset string) []byte { + for len(s) > 0 { + r, n := utf8.DecodeRune(s) + if !containsRune(cutset, r) { + break + } + s = s[n:] + } + if len(s) == 0 { + // This is what we've historically done. + return nil + } + return s +} + +// TrimRight returns a subslice of s by slicing off all trailing +// UTF-8-encoded code points that are contained in cutset. +func TrimRight(s []byte, cutset string) []byte { + if len(s) == 0 || cutset == "" { + return s + } + if len(cutset) == 1 && cutset[0] < utf8.RuneSelf { + return trimRightByte(s, cutset[0]) + } + if as, ok := makeASCIISet(cutset); ok { + return trimRightASCII(s, &as) + } + return trimRightUnicode(s, cutset) +} + +func trimRightByte(s []byte, c byte) []byte { + for len(s) > 0 && s[len(s)-1] == c { + s = s[:len(s)-1] + } + return s +} + +func trimRightASCII(s []byte, as *asciiSet) []byte { + for len(s) > 0 { + if !as.contains(s[len(s)-1]) { + break + } + s = s[:len(s)-1] + } + return s +} + +func trimRightUnicode(s []byte, cutset string) []byte { + for len(s) > 0 { + r, n := rune(s[len(s)-1]), 1 + if r >= utf8.RuneSelf { + r, n = utf8.DecodeLastRune(s) + } + if !containsRune(cutset, r) { + break + } + s = s[:len(s)-n] + } + return s +} + +// TrimSpace returns a subslice of s by slicing off all leading and +// trailing white space, as defined by Unicode. +func TrimSpace(s []byte) []byte { + // Fast path for ASCII: look for the first ASCII non-space byte. + for lo, c := range s { + if c >= utf8.RuneSelf { + // If we run into a non-ASCII byte, fall back to the + // slower unicode-aware method on the remaining bytes. + return TrimFunc(s[lo:], unicode.IsSpace) + } + if asciiSpace[c] != 0 { + continue + } + s = s[lo:] + // Now look for the first ASCII non-space byte from the end. + for hi := len(s) - 1; hi >= 0; hi-- { + c := s[hi] + if c >= utf8.RuneSelf { + return TrimFunc(s[:hi+1], unicode.IsSpace) + } + if asciiSpace[c] == 0 { + // At this point, s[:hi+1] starts and ends with ASCII + // non-space bytes, so we're done. Non-ASCII cases have + // already been handled above. + return s[:hi+1] + } + } + } + // Special case to preserve previous TrimLeftFunc behavior, + // returning nil instead of empty slice if all spaces. + return nil +} + +// Runes interprets s as a sequence of UTF-8-encoded code points. +// It returns a slice of runes (Unicode code points) equivalent to s. +func Runes(s []byte) []rune { + t := make([]rune, utf8.RuneCount(s)) + i := 0 + for len(s) > 0 { + r, l := utf8.DecodeRune(s) + t[i] = r + i++ + s = s[l:] + } + return t +} + +// Replace returns a copy of the slice s with the first n +// non-overlapping instances of old replaced by new. +// If old is empty, it matches at the beginning of the slice +// and after each UTF-8 sequence, yielding up to k+1 replacements +// for a k-rune slice. +// If n < 0, there is no limit on the number of replacements. +func Replace(s, old, new []byte, n int) []byte { + m := 0 + if n != 0 { + // Compute number of replacements. + m = Count(s, old) + } + if m == 0 { + // Just return a copy. + return append([]byte(nil), s...) + } + if n < 0 || m < n { + n = m + } + + // Apply replacements to buffer. + t := make([]byte, len(s)+n*(len(new)-len(old))) + w := 0 + start := 0 + if len(old) > 0 { + for range n { + j := start + Index(s[start:], old) + w += copy(t[w:], s[start:j]) + w += copy(t[w:], new) + start = j + len(old) + } + } else { // len(old) == 0 + w += copy(t[w:], new) + for range n - 1 { + _, wid := utf8.DecodeRune(s[start:]) + j := start + wid + w += copy(t[w:], s[start:j]) + w += copy(t[w:], new) + start = j + } + } + w += copy(t[w:], s[start:]) + return t[0:w] +} + +// ReplaceAll returns a copy of the slice s with all +// non-overlapping instances of old replaced by new. +// If old is empty, it matches at the beginning of the slice +// and after each UTF-8 sequence, yielding up to k+1 replacements +// for a k-rune slice. +func ReplaceAll(s, old, new []byte) []byte { + return Replace(s, old, new, -1) +} + +// EqualFold reports whether s and t, interpreted as UTF-8 strings, +// are equal under simple Unicode case-folding, which is a more general +// form of case-insensitivity. +func EqualFold(s, t []byte) bool { + // ASCII fast path + i := 0 + for n := min(len(s), len(t)); i < n; i++ { + sr := s[i] + tr := t[i] + if sr|tr >= utf8.RuneSelf { + goto hasUnicode + } + + // Easy case. + if tr == sr { + continue + } + + // Make sr < tr to simplify what follows. + if tr < sr { + tr, sr = sr, tr + } + // ASCII only, sr/tr must be upper/lower case + if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' { + continue + } + return false + } + // Check if we've exhausted both strings. + return len(s) == len(t) + +hasUnicode: + s = s[i:] + t = t[i:] + for len(s) != 0 && len(t) != 0 { + // Extract first rune from each. + sr, size := utf8.DecodeRune(s) + s = s[size:] + tr, size := utf8.DecodeRune(t) + t = t[size:] + + // If they match, keep going; if not, return false. + + // Easy case. + if tr == sr { + continue + } + + // Make sr < tr to simplify what follows. + if tr < sr { + tr, sr = sr, tr + } + // Fast check for ASCII. + if tr < utf8.RuneSelf { + // ASCII only, sr/tr must be upper/lower case + if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' { + continue + } + return false + } + + // General case. SimpleFold(x) returns the next equivalent rune > x + // or wraps around to smaller values. + r := unicode.SimpleFold(sr) + for r != sr && r < tr { + r = unicode.SimpleFold(r) + } + if r == tr { + continue + } + return false + } + + // One string is empty. Are both? + return len(s) == len(t) +} + +// Index returns the index of the first instance of sep in s, or -1 if sep is not present in s. +func Index(s, sep []byte) int { + n := len(sep) + switch { + case n == 0: + return 0 + case n == 1: + return IndexByte(s, sep[0]) + case n == len(s): + if Equal(sep, s) { + return 0 + } + return -1 + case n > len(s): + return -1 + case n <= bytealg.MaxLen: + // Use brute force when s and sep both are small + if len(s) <= bytealg.MaxBruteForce { + return bytealg.Index(s, sep) + } + c0 := sep[0] + c1 := sep[1] + i := 0 + t := len(s) - n + 1 + fails := 0 + for i < t { + if s[i] != c0 { + // IndexByte is faster than bytealg.Index, so use it as long as + // we're not getting lots of false positives. + o := IndexByte(s[i+1:t], c0) + if o < 0 { + return -1 + } + i += o + 1 + } + if s[i+1] == c1 && Equal(s[i:i+n], sep) { + return i + } + fails++ + i++ + // Switch to bytealg.Index when IndexByte produces too many false positives. + if fails > bytealg.Cutover(i) { + r := bytealg.Index(s[i:], sep) + if r >= 0 { + return r + i + } + return -1 + } + } + return -1 + } + c0 := sep[0] + c1 := sep[1] + i := 0 + fails := 0 + t := len(s) - n + 1 + for i < t { + if s[i] != c0 { + o := IndexByte(s[i+1:t], c0) + if o < 0 { + break + } + i += o + 1 + } + if s[i+1] == c1 && Equal(s[i:i+n], sep) { + return i + } + i++ + fails++ + if fails >= 4+i>>4 && i < t { + // Give up on IndexByte, it isn't skipping ahead + // far enough to be better than Rabin-Karp. + // Experiments (using IndexPeriodic) suggest + // the cutover is about 16 byte skips. + // TODO: if large prefixes of sep are matching + // we should cutover at even larger average skips, + // because Equal becomes that much more expensive. + // This code does not take that effect into account. + j := bytealg.IndexRabinKarp(s[i:], sep) + if j < 0 { + return -1 + } + return i + j + } + } + return -1 +} + +// Cut slices s around the first instance of sep, +// returning the text before and after sep. +// The found result reports whether sep appears in s. +// If sep does not appear in s, cut returns s, nil, false. +// +// Cut returns slices of the original slice s, not copies. +func Cut(s, sep []byte) (before, after []byte, found bool) { + if i := Index(s, sep); i >= 0 { + return s[:i], s[i+len(sep):], true + } + return s, nil, false +} + +// Clone returns a copy of b[:len(b)]. +// The result may have additional unused capacity. +// Clone(nil) returns nil. +func Clone(b []byte) []byte { + if b == nil { + return nil + } + return append([]byte{}, b...) +} + +// CutPrefix returns s without the provided leading prefix byte slice +// and reports whether it found the prefix. +// If s doesn't start with prefix, CutPrefix returns s, false. +// If prefix is the empty byte slice, CutPrefix returns s, true. +// +// CutPrefix returns slices of the original slice s, not copies. +func CutPrefix(s, prefix []byte) (after []byte, found bool) { + if !HasPrefix(s, prefix) { + return s, false + } + return s[len(prefix):], true +} + +// CutSuffix returns s without the provided ending suffix byte slice +// and reports whether it found the suffix. +// If s doesn't end with suffix, CutSuffix returns s, false. +// If suffix is the empty byte slice, CutSuffix returns s, true. +// +// CutSuffix returns slices of the original slice s, not copies. +func CutSuffix(s, suffix []byte) (before []byte, found bool) { + if !HasSuffix(s, suffix) { + return s, false + } + return s[:len(s)-len(suffix)], true +} diff --git a/go/src/bytes/bytes_js_wasm_test.go b/go/src/bytes/bytes_js_wasm_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ad9db343184f99faee7b86b5c6ca14425d2c130b --- /dev/null +++ b/go/src/bytes/bytes_js_wasm_test.go @@ -0,0 +1,21 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js && wasm + +package bytes_test + +import ( + "bytes" + "testing" +) + +func TestIssue65571(t *testing.T) { + b := make([]byte, 1<<31+1) + b[1<<31] = 1 + i := bytes.IndexByte(b, 1) + if i != 1<<31 { + t.Errorf("IndexByte(b, 1) = %d; want %d", i, 1<<31) + } +} diff --git a/go/src/bytes/bytes_test.go b/go/src/bytes/bytes_test.go new file mode 100644 index 0000000000000000000000000000000000000000..891aef2c8b89960899f9d4735420bfd0b24e3aae --- /dev/null +++ b/go/src/bytes/bytes_test.go @@ -0,0 +1,2501 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes_test + +import ( + . "bytes" + "fmt" + "internal/asan" + "internal/testenv" + "iter" + "math" + "math/rand" + "slices" + "strings" + "testing" + "unicode" + "unicode/utf8" + "unsafe" +) + +func sliceOfString(s [][]byte) []string { + result := make([]string, len(s)) + for i, v := range s { + result[i] = string(v) + } + return result +} + +func collect(t *testing.T, seq iter.Seq[[]byte]) [][]byte { + out := slices.Collect(seq) + out1 := slices.Collect(seq) + if !slices.Equal(sliceOfString(out), sliceOfString(out1)) { + t.Fatalf("inconsistent seq:\n%s\n%s", out, out1) + } + return out +} + +type LinesTest struct { + a string + b []string +} + +var linesTests = []LinesTest{ + {a: "abc\nabc\n", b: []string{"abc\n", "abc\n"}}, + {a: "abc\r\nabc", b: []string{"abc\r\n", "abc"}}, + {a: "abc\r\n", b: []string{"abc\r\n"}}, + {a: "\nabc", b: []string{"\n", "abc"}}, + {a: "\nabc\n\n", b: []string{"\n", "abc\n", "\n"}}, +} + +func TestLines(t *testing.T) { + for _, s := range linesTests { + result := sliceOfString(slices.Collect(Lines([]byte(s.a)))) + if !slices.Equal(result, s.b) { + t.Errorf(`slices.Collect(Lines(%q)) = %q; want %q`, s.a, result, s.b) + } + } +} + +// For ease of reading, the test cases use strings that are converted to byte +// slices before invoking the functions. + +var abcd = "abcd" +var faces = "☺☻☹" +var commas = "1,2,3,4" +var dots = "1....2....3....4" + +type BinOpTest struct { + a string + b string + i int +} + +func TestEqual(t *testing.T) { + // Run the tests and check for allocation at the same time. + allocs := testing.AllocsPerRun(10, func() { + for _, tt := range compareTests { + eql := Equal(tt.a, tt.b) + if eql != (tt.i == 0) { + t.Errorf(`Equal(%q, %q) = %v`, tt.a, tt.b, eql) + } + } + }) + if allocs > 0 { + t.Errorf("Equal allocated %v times", allocs) + } +} + +func TestEqualExhaustive(t *testing.T) { + var size = 128 + if testing.Short() { + size = 32 + } + a := make([]byte, size) + b := make([]byte, size) + b_init := make([]byte, size) + // randomish but deterministic data + for i := 0; i < size; i++ { + a[i] = byte(17 * i) + b_init[i] = byte(23*i + 100) + } + + for len := 0; len <= size; len++ { + for x := 0; x <= size-len; x++ { + for y := 0; y <= size-len; y++ { + copy(b, b_init) + copy(b[y:y+len], a[x:x+len]) + if !Equal(a[x:x+len], b[y:y+len]) || !Equal(b[y:y+len], a[x:x+len]) { + t.Errorf("Equal(%d, %d, %d) = false", len, x, y) + } + } + } + } +} + +// make sure Equal returns false for minimally different strings. The data +// is all zeros except for a single one in one location. +func TestNotEqual(t *testing.T) { + var size = 128 + if testing.Short() { + size = 32 + } + a := make([]byte, size) + b := make([]byte, size) + + for len := 0; len <= size; len++ { + for x := 0; x <= size-len; x++ { + for y := 0; y <= size-len; y++ { + for diffpos := x; diffpos < x+len; diffpos++ { + a[diffpos] = 1 + if Equal(a[x:x+len], b[y:y+len]) || Equal(b[y:y+len], a[x:x+len]) { + t.Errorf("NotEqual(%d, %d, %d, %d) = true", len, x, y, diffpos) + } + a[diffpos] = 0 + } + } + } + } +} + +var indexTests = []BinOpTest{ + {"", "", 0}, + {"", "a", -1}, + {"", "foo", -1}, + {"fo", "foo", -1}, + {"foo", "baz", -1}, + {"foo", "foo", 0}, + {"oofofoofooo", "f", 2}, + {"oofofoofooo", "foo", 4}, + {"barfoobarfoo", "foo", 3}, + {"foo", "", 0}, + {"foo", "o", 1}, + {"abcABCabc", "A", 3}, + // cases with one byte strings - test IndexByte and special case in Index() + {"", "a", -1}, + {"x", "a", -1}, + {"x", "x", 0}, + {"abc", "a", 0}, + {"abc", "b", 1}, + {"abc", "c", 2}, + {"abc", "x", -1}, + {"barfoobarfooyyyzzzyyyzzzyyyzzzyyyxxxzzzyyy", "x", 33}, + {"fofofofooofoboo", "oo", 7}, + {"fofofofofofoboo", "ob", 11}, + {"fofofofofofoboo", "boo", 12}, + {"fofofofofofoboo", "oboo", 11}, + {"fofofofofoooboo", "fooo", 8}, + {"fofofofofofoboo", "foboo", 10}, + {"fofofofofofoboo", "fofob", 8}, + {"fofofofofofofoffofoobarfoo", "foffof", 12}, + {"fofofofofoofofoffofoobarfoo", "foffof", 13}, + {"fofofofofofofoffofoobarfoo", "foffofo", 12}, + {"fofofofofoofofoffofoobarfoo", "foffofo", 13}, + {"fofofofofoofofoffofoobarfoo", "foffofoo", 13}, + {"fofofofofofofoffofoobarfoo", "foffofoo", 12}, + {"fofofofofoofofoffofoobarfoo", "foffofoob", 13}, + {"fofofofofofofoffofoobarfoo", "foffofoob", 12}, + {"fofofofofoofofoffofoobarfoo", "foffofooba", 13}, + {"fofofofofofofoffofoobarfoo", "foffofooba", 12}, + {"fofofofofoofofoffofoobarfoo", "foffofoobar", 13}, + {"fofofofofofofoffofoobarfoo", "foffofoobar", 12}, + {"fofofofofoofofoffofoobarfoo", "foffofoobarf", 13}, + {"fofofofofofofoffofoobarfoo", "foffofoobarf", 12}, + {"fofofofofoofofoffofoobarfoo", "foffofoobarfo", 13}, + {"fofofofofofofoffofoobarfoo", "foffofoobarfo", 12}, + {"fofofofofoofofoffofoobarfoo", "foffofoobarfoo", 13}, + {"fofofofofofofoffofoobarfoo", "foffofoobarfoo", 12}, + {"fofofofofoofofoffofoobarfoo", "ofoffofoobarfoo", 12}, + {"fofofofofofofoffofoobarfoo", "ofoffofoobarfoo", 11}, + {"fofofofofoofofoffofoobarfoo", "fofoffofoobarfoo", 11}, + {"fofofofofofofoffofoobarfoo", "fofoffofoobarfoo", 10}, + {"fofofofofoofofoffofoobarfoo", "foobars", -1}, + {"foofyfoobarfoobar", "y", 4}, + {"oooooooooooooooooooooo", "r", -1}, + {"oxoxoxoxoxoxoxoxoxoxoxoy", "oy", 22}, + {"oxoxoxoxoxoxoxoxoxoxoxox", "oy", -1}, + // test fallback to Rabin-Karp. + {"000000000000000000000000000000000000000000000000000000000000000000000001", "0000000000000000000000000000000000000000000000000000000000000000001", 5}, + // test fallback to IndexRune + {"oxoxoxoxoxoxoxoxoxoxox☺", "☺", 22}, + // invalid UTF-8 byte sequence (must be longer than bytealg.MaxBruteForce to + // test that we don't use IndexRune) + {"xx0123456789012345678901234567890123456789012345678901234567890120123456789012345678901234567890123456xxx\xed\x9f\xc0", "\xed\x9f\xc0", 105}, +} + +var lastIndexTests = []BinOpTest{ + {"", "", 0}, + {"", "a", -1}, + {"", "foo", -1}, + {"fo", "foo", -1}, + {"foo", "foo", 0}, + {"foo", "f", 0}, + {"oofofoofooo", "f", 7}, + {"oofofoofooo", "foo", 7}, + {"barfoobarfoo", "foo", 9}, + {"foo", "", 3}, + {"foo", "o", 2}, + {"abcABCabc", "A", 3}, + {"abcABCabc", "a", 6}, +} + +var indexAnyTests = []BinOpTest{ + {"", "", -1}, + {"", "a", -1}, + {"", "abc", -1}, + {"a", "", -1}, + {"a", "a", 0}, + {"\x80", "\xffb", 0}, + {"aaa", "a", 0}, + {"abc", "xyz", -1}, + {"abc", "xcz", 2}, + {"ab☺c", "x☺yz", 2}, + {"a☺b☻c☹d", "cx", len("a☺b☻")}, + {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")}, + {"aRegExp*", ".(|)*+?^$[]", 7}, + {dots + dots + dots, " ", -1}, + {"012abcba210", "\xffb", 4}, + {"012\x80bcb\x80210", "\xffb", 3}, + {"0123456\xcf\x80abc", "\xcfb\x80", 10}, +} + +var lastIndexAnyTests = []BinOpTest{ + {"", "", -1}, + {"", "a", -1}, + {"", "abc", -1}, + {"a", "", -1}, + {"a", "a", 0}, + {"\x80", "\xffb", 0}, + {"aaa", "a", 2}, + {"abc", "xyz", -1}, + {"abc", "ab", 1}, + {"ab☺c", "x☺yz", 2}, + {"a☺b☻c☹d", "cx", len("a☺b☻")}, + {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")}, + {"a.RegExp*", ".(|)*+?^$[]", 8}, + {dots + dots + dots, " ", -1}, + {"012abcba210", "\xffb", 6}, + {"012\x80bcb\x80210", "\xffb", 7}, + {"0123456\xcf\x80abc", "\xcfb\x80", 10}, +} + +// Execute f on each test case. funcName should be the name of f; it's used +// in failure reports. +func runIndexTests(t *testing.T, f func(s, sep []byte) int, funcName string, testCases []BinOpTest) { + for _, test := range testCases { + a := []byte(test.a) + b := []byte(test.b) + actual := f(a, b) + if actual != test.i { + t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, b, actual, test.i) + } + } + var allocTests = []struct { + a []byte + b []byte + i int + }{ + // case for function Index. + {[]byte("000000000000000000000000000000000000000000000000000000000000000000000001"), []byte("0000000000000000000000000000000000000000000000000000000000000000001"), 5}, + // case for function LastIndex. + {[]byte("000000000000000000000000000000000000000000000000000000000000000010000"), []byte("00000000000000000000000000000000000000000000000000000000000001"), 3}, + } + allocs := testing.AllocsPerRun(100, func() { + if i := Index(allocTests[1].a, allocTests[1].b); i != allocTests[1].i { + t.Errorf("Index([]byte(%q), []byte(%q)) = %v; want %v", allocTests[1].a, allocTests[1].b, i, allocTests[1].i) + } + if i := LastIndex(allocTests[0].a, allocTests[0].b); i != allocTests[0].i { + t.Errorf("LastIndex([]byte(%q), []byte(%q)) = %v; want %v", allocTests[0].a, allocTests[0].b, i, allocTests[0].i) + } + }) + if allocs != 0 { + t.Errorf("expected no allocations, got %f", allocs) + } +} + +func runIndexAnyTests(t *testing.T, f func(s []byte, chars string) int, funcName string, testCases []BinOpTest) { + for _, test := range testCases { + a := []byte(test.a) + actual := f(a, test.b) + if actual != test.i { + t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, test.b, actual, test.i) + } + } +} + +func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) } +func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) } +func TestIndexAny(t *testing.T) { runIndexAnyTests(t, IndexAny, "IndexAny", indexAnyTests) } +func TestLastIndexAny(t *testing.T) { + runIndexAnyTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests) +} + +func TestIndexByte(t *testing.T) { + for _, tt := range indexTests { + if len(tt.b) != 1 { + continue + } + a := []byte(tt.a) + b := tt.b[0] + pos := IndexByte(a, b) + if pos != tt.i { + t.Errorf(`IndexByte(%q, '%c') = %v`, tt.a, b, pos) + } + posp := IndexBytePortable(a, b) + if posp != tt.i { + t.Errorf(`indexBytePortable(%q, '%c') = %v`, tt.a, b, posp) + } + } +} + +func TestLastIndexByte(t *testing.T) { + testCases := []BinOpTest{ + {"", "q", -1}, + {"abcdef", "q", -1}, + {"abcdefabcdef", "a", len("abcdef")}, // something in the middle + {"abcdefabcdef", "f", len("abcdefabcde")}, // last byte + {"zabcdefabcdef", "z", 0}, // first byte + {"a☺b☻c☹d", "b", len("a☺")}, // non-ascii + } + for _, test := range testCases { + actual := LastIndexByte([]byte(test.a), test.b[0]) + if actual != test.i { + t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.a, test.b[0], actual, test.i) + } + } +} + +// test a larger buffer with different sizes and alignments +func TestIndexByteBig(t *testing.T) { + var n = 1024 + if testing.Short() { + n = 128 + } + b := make([]byte, n) + for i := 0; i < n; i++ { + // different start alignments + b1 := b[i:] + for j := 0; j < len(b1); j++ { + b1[j] = 'x' + pos := IndexByte(b1, 'x') + if pos != j { + t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) + } + b1[j] = 0 + pos = IndexByte(b1, 'x') + if pos != -1 { + t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) + } + } + // different end alignments + b1 = b[:i] + for j := 0; j < len(b1); j++ { + b1[j] = 'x' + pos := IndexByte(b1, 'x') + if pos != j { + t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) + } + b1[j] = 0 + pos = IndexByte(b1, 'x') + if pos != -1 { + t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) + } + } + // different start and end alignments + b1 = b[i/2 : n-(i+1)/2] + for j := 0; j < len(b1); j++ { + b1[j] = 'x' + pos := IndexByte(b1, 'x') + if pos != j { + t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) + } + b1[j] = 0 + pos = IndexByte(b1, 'x') + if pos != -1 { + t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) + } + } + } +} + +// test a small index across all page offsets +func TestIndexByteSmall(t *testing.T) { + b := make([]byte, 5015) // bigger than a page + // Make sure we find the correct byte even when straddling a page. + for i := 0; i <= len(b)-15; i++ { + for j := 0; j < 15; j++ { + b[i+j] = byte(100 + j) + } + for j := 0; j < 15; j++ { + p := IndexByte(b[i:i+15], byte(100+j)) + if p != j { + t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 100+j, p) + } + } + for j := 0; j < 15; j++ { + b[i+j] = 0 + } + } + // Make sure matches outside the slice never trigger. + for i := 0; i <= len(b)-15; i++ { + for j := 0; j < 15; j++ { + b[i+j] = 1 + } + for j := 0; j < 15; j++ { + p := IndexByte(b[i:i+15], byte(0)) + if p != -1 { + t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 0, p) + } + } + for j := 0; j < 15; j++ { + b[i+j] = 0 + } + } +} + +func TestIndexRune(t *testing.T) { + tests := []struct { + in string + rune rune + want int + }{ + {"", 'a', -1}, + {"", '☺', -1}, + {"foo", '☹', -1}, + {"foo", 'o', 1}, + {"foo☺bar", '☺', 3}, + {"foo☺☻☹bar", '☹', 9}, + {"a A x", 'A', 2}, + {"some_text=some_value", '=', 9}, + {"☺a", 'a', 3}, + {"a☻☺b", '☺', 4}, + {"𠀳𠀗𠀾𠁄𠀧𠁆𠁂𠀫𠀖𠀪𠀲𠀴𠁀𠀨𠀿", '𠀿', 56}, + + // 2 bytes + {"ӆ", 'ӆ', 0}, + {"a", 'ӆ', -1}, + {" ӆ", 'ӆ', 2}, + {" a", 'ӆ', -1}, + {strings.Repeat("ц", 64) + "ӆ", 'ӆ', 128}, // test cutover + {strings.Repeat("ц", 64), 'ӆ', -1}, + + // 3 bytes + {"Ꚁ", 'Ꚁ', 0}, + {"a", 'Ꚁ', -1}, + {" Ꚁ", 'Ꚁ', 2}, + {" a", 'Ꚁ', -1}, + {strings.Repeat("Ꙁ", 64) + "Ꚁ", 'Ꚁ', 192}, // test cutover + {strings.Repeat("Ꙁ", 64) + "Ꚁ", '䚀', -1}, // 'Ꚁ' and '䚀' share the same last two bytes + + // 4 bytes + {"𡌀", '𡌀', 0}, + {"a", '𡌀', -1}, + {" 𡌀", '𡌀', 2}, + {" a", '𡌀', -1}, + {strings.Repeat("𡋀", 64) + "𡌀", '𡌀', 256}, // test cutover + {strings.Repeat("𡋀", 64) + "𡌀", '𣌀', -1}, // '𡌀' and '𣌀' share the same last two bytes + + // RuneError should match any invalid UTF-8 byte sequence. + {"�", '�', 0}, + {"\xff", '�', 0}, + {"☻x�", '�', len("☻x")}, + {"☻x\xe2\x98", '�', len("☻x")}, + {"☻x\xe2\x98�", '�', len("☻x")}, + {"☻x\xe2\x98x", '�', len("☻x")}, + + // Invalid rune values should never match. + {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", -1, -1}, + {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", 0xD800, -1}, // Surrogate pair + {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", utf8.MaxRune + 1, -1}, + + // Test the cutover to bytealg.Index when it is triggered in + // the middle of rune that contains consecutive runs of equal bytes. + {"aaaaaKKKK\U000bc104", '\U000bc104', 17}, // cutover: (n + 16) / 8 + {"aaaaaKKKK鄄", '鄄', 17}, + {"aaKKKKKa\U000bc104", '\U000bc104', 18}, // cutover: 4 + n>>4 + {"aaKKKKKa鄄", '鄄', 18}, + } + for _, tt := range tests { + if got := IndexRune([]byte(tt.in), tt.rune); got != tt.want { + t.Errorf("IndexRune(%q, %d) = %v; want %v", tt.in, tt.rune, got, tt.want) + } + } + + haystack := []byte("test世界") + allocs := testing.AllocsPerRun(1000, func() { + if i := IndexRune(haystack, 's'); i != 2 { + t.Fatalf("'s' at %d; want 2", i) + } + if i := IndexRune(haystack, '世'); i != 4 { + t.Fatalf("'世' at %d; want 4", i) + } + }) + if allocs != 0 { + t.Errorf("expected no allocations, got %f", allocs) + } +} + +// test count of a single byte across page offsets +func TestCountByte(t *testing.T) { + b := make([]byte, 5015) // bigger than a page + windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128} + testCountWindow := func(i, window int) { + for j := 0; j < window; j++ { + b[i+j] = byte(100) + p := Count(b[i:i+window], []byte{100}) + if p != j+1 { + t.Errorf("TestCountByte.Count(%q, 100) = %d", b[i:i+window], p) + } + } + } + + maxWnd := windows[len(windows)-1] + + for i := 0; i <= 2*maxWnd; i++ { + for _, window := range windows { + if window > len(b[i:]) { + window = len(b[i:]) + } + testCountWindow(i, window) + for j := 0; j < window; j++ { + b[i+j] = byte(0) + } + } + } + for i := 4096 - (maxWnd + 1); i < len(b); i++ { + for _, window := range windows { + if window > len(b[i:]) { + window = len(b[i:]) + } + testCountWindow(i, window) + for j := 0; j < window; j++ { + b[i+j] = byte(0) + } + } + } +} + +// Make sure we don't count bytes outside our window +func TestCountByteNoMatch(t *testing.T) { + b := make([]byte, 5015) + windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128} + for i := 0; i <= len(b); i++ { + for _, window := range windows { + if window > len(b[i:]) { + window = len(b[i:]) + } + // Fill the window with non-match + for j := 0; j < window; j++ { + b[i+j] = byte(100) + } + // Try to find something that doesn't exist + p := Count(b[i:i+window], []byte{0}) + if p != 0 { + t.Errorf("TestCountByteNoMatch(%q, 0) = %d", b[i:i+window], p) + } + for j := 0; j < window; j++ { + b[i+j] = byte(0) + } + } + } +} + +var bmbuf []byte + +func valName(x int) string { + if s := x >> 20; s<<20 == x { + return fmt.Sprintf("%dM", s) + } + if s := x >> 10; s<<10 == x { + return fmt.Sprintf("%dK", s) + } + return fmt.Sprint(x) +} + +func benchBytes(b *testing.B, sizes []int, f func(b *testing.B, n int)) { + for _, n := range sizes { + if isRaceBuilder && n > 4<<10 { + continue + } + b.Run(valName(n), func(b *testing.B) { + if len(bmbuf) < n { + bmbuf = make([]byte, n) + } + b.SetBytes(int64(n)) + f(b, n) + }) + } +} + +var indexSizes = []int{10, 32, 4 << 10, 4 << 20, 64 << 20} + +var isRaceBuilder = strings.HasSuffix(testenv.Builder(), "-race") + +func BenchmarkIndexByte(b *testing.B) { + benchBytes(b, indexSizes, bmIndexByte(IndexByte)) +} + +func BenchmarkIndexBytePortable(b *testing.B) { + benchBytes(b, indexSizes, bmIndexByte(IndexBytePortable)) +} + +func bmIndexByte(index func([]byte, byte) int) func(b *testing.B, n int) { + return func(b *testing.B, n int) { + buf := bmbuf[0:n] + buf[n-1] = 'x' + for i := 0; i < b.N; i++ { + j := index(buf, 'x') + if j != n-1 { + b.Fatal("bad index", j) + } + } + buf[n-1] = '\x00' + } +} + +func BenchmarkIndexRune(b *testing.B) { + benchBytes(b, indexSizes, bmIndexRune(IndexRune)) +} + +func BenchmarkIndexRuneASCII(b *testing.B) { + benchBytes(b, indexSizes, bmIndexRuneASCII(IndexRune)) +} + +func BenchmarkIndexRuneUnicode(b *testing.B) { + b.Run("Latin", func(b *testing.B) { + // Latin is mostly 1, 2, 3 byte runes. + benchBytes(b, indexSizes, bmIndexRuneUnicode(unicode.Latin, 'é')) + }) + b.Run("Cyrillic", func(b *testing.B) { + // Cyrillic is mostly 2 and 3 byte runes. + benchBytes(b, indexSizes, bmIndexRuneUnicode(unicode.Cyrillic, 'Ꙁ')) + }) + b.Run("Han", func(b *testing.B) { + // Han consists only of 3 and 4 byte runes. + benchBytes(b, indexSizes, bmIndexRuneUnicode(unicode.Han, '𠀿')) + }) +} + +func bmIndexRuneASCII(index func([]byte, rune) int) func(b *testing.B, n int) { + return func(b *testing.B, n int) { + buf := bmbuf[0:n] + buf[n-1] = 'x' + for i := 0; i < b.N; i++ { + j := index(buf, 'x') + if j != n-1 { + b.Fatal("bad index", j) + } + } + buf[n-1] = '\x00' + } +} + +func bmIndexRune(index func([]byte, rune) int) func(b *testing.B, n int) { + return func(b *testing.B, n int) { + buf := bmbuf[0:n] + utf8.EncodeRune(buf[n-3:], '世') + for i := 0; i < b.N; i++ { + j := index(buf, '世') + if j != n-3 { + b.Fatal("bad index", j) + } + } + buf[n-3] = '\x00' + buf[n-2] = '\x00' + buf[n-1] = '\x00' + } +} + +func bmIndexRuneUnicode(rt *unicode.RangeTable, needle rune) func(b *testing.B, n int) { + var rs []rune + for _, r16 := range rt.R16 { + for r := rune(r16.Lo); r <= rune(r16.Hi); r += rune(r16.Stride) { + if r != needle { + rs = append(rs, r) + } + } + } + for _, r32 := range rt.R32 { + for r := rune(r32.Lo); r <= rune(r32.Hi); r += rune(r32.Stride) { + if r != needle { + rs = append(rs, r) + } + } + } + // Shuffle the runes so that they are not in descending order. + // The sort is deterministic since this is used for benchmarks, + // which need to be repeatable. + rr := rand.New(rand.NewSource(1)) + rr.Shuffle(len(rs), func(i, j int) { + rs[i], rs[j] = rs[j], rs[i] + }) + uchars := string(rs) + + return func(b *testing.B, n int) { + buf := bmbuf[0:n] + o := copy(buf, uchars) + for o < len(buf) { + o += copy(buf[o:], uchars) + } + + // Make space for the needle rune at the end of buf. + m := utf8.RuneLen(needle) + for o := m; o > 0; { + _, sz := utf8.DecodeLastRune(buf) + copy(buf[len(buf)-sz:], "\x00\x00\x00\x00") + buf = buf[:len(buf)-sz] + o -= sz + } + buf = utf8.AppendRune(buf[:n-m], needle) + + n -= m // adjust for rune len + for i := 0; i < b.N; i++ { + j := IndexRune(buf, needle) + if j != n { + b.Fatal("bad index", j) + } + } + for i := range buf { + buf[i] = '\x00' + } + } +} + +func BenchmarkEqual(b *testing.B) { + b.Run("0", func(b *testing.B) { + var buf [4]byte + buf1 := buf[0:0] + buf2 := buf[1:1] + for i := 0; i < b.N; i++ { + eq := Equal(buf1, buf2) + if !eq { + b.Fatal("bad equal") + } + } + }) + + sizes := []int{1, 6, 9, 15, 16, 20, 32, 4 << 10, 4 << 20, 64 << 20} + + b.Run("same", func(b *testing.B) { + benchBytes(b, sizes, bmEqual(func(a, b []byte) bool { return Equal(a, a) })) + }) + + benchBytes(b, sizes, bmEqual(Equal)) +} + +func bmEqual(equal func([]byte, []byte) bool) func(b *testing.B, n int) { + return func(b *testing.B, n int) { + if len(bmbuf) < 2*n { + bmbuf = make([]byte, 2*n) + } + buf1 := bmbuf[0:n] + buf2 := bmbuf[n : 2*n] + buf1[n-1] = 'x' + buf2[n-1] = 'x' + for i := 0; i < b.N; i++ { + eq := equal(buf1, buf2) + if !eq { + b.Fatal("bad equal") + } + } + buf1[n-1] = '\x00' + buf2[n-1] = '\x00' + } +} + +func BenchmarkEqualBothUnaligned(b *testing.B) { + sizes := []int{64, 4 << 10} + if !isRaceBuilder { + sizes = append(sizes, []int{4 << 20, 64 << 20}...) + } + maxSize := 2 * (sizes[len(sizes)-1] + 8) + if len(bmbuf) < maxSize { + bmbuf = make([]byte, maxSize) + } + + for _, n := range sizes { + for _, off := range []int{0, 1, 4, 7} { + buf1 := bmbuf[off : off+n] + buf2Start := (len(bmbuf) / 2) + off + buf2 := bmbuf[buf2Start : buf2Start+n] + buf1[n-1] = 'x' + buf2[n-1] = 'x' + b.Run(fmt.Sprint(n, off), func(b *testing.B) { + b.SetBytes(int64(n)) + for i := 0; i < b.N; i++ { + eq := Equal(buf1, buf2) + if !eq { + b.Fatal("bad equal") + } + } + }) + buf1[n-1] = '\x00' + buf2[n-1] = '\x00' + } + } +} + +func BenchmarkIndex(b *testing.B) { + benchBytes(b, indexSizes, func(b *testing.B, n int) { + buf := bmbuf[0:n] + buf[n-1] = 'x' + for i := 0; i < b.N; i++ { + j := Index(buf, buf[n-7:]) + if j != n-7 { + b.Fatal("bad index", j) + } + } + buf[n-1] = '\x00' + }) +} + +func BenchmarkIndexEasy(b *testing.B) { + benchBytes(b, indexSizes, func(b *testing.B, n int) { + buf := bmbuf[0:n] + buf[n-1] = 'x' + buf[n-7] = 'x' + for i := 0; i < b.N; i++ { + j := Index(buf, buf[n-7:]) + if j != n-7 { + b.Fatal("bad index", j) + } + } + buf[n-1] = '\x00' + buf[n-7] = '\x00' + }) +} + +func BenchmarkCount(b *testing.B) { + benchBytes(b, indexSizes, func(b *testing.B, n int) { + buf := bmbuf[0:n] + buf[n-1] = 'x' + for i := 0; i < b.N; i++ { + j := Count(buf, buf[n-7:]) + if j != 1 { + b.Fatal("bad count", j) + } + } + buf[n-1] = '\x00' + }) +} + +func BenchmarkCountEasy(b *testing.B) { + benchBytes(b, indexSizes, func(b *testing.B, n int) { + buf := bmbuf[0:n] + buf[n-1] = 'x' + buf[n-7] = 'x' + for i := 0; i < b.N; i++ { + j := Count(buf, buf[n-7:]) + if j != 1 { + b.Fatal("bad count", j) + } + } + buf[n-1] = '\x00' + buf[n-7] = '\x00' + }) +} + +func BenchmarkCountSingle(b *testing.B) { + benchBytes(b, indexSizes, func(b *testing.B, n int) { + buf := bmbuf[0:n] + step := 8 + for i := 0; i < len(buf); i += step { + buf[i] = 1 + } + expect := (len(buf) + (step - 1)) / step + for i := 0; i < b.N; i++ { + j := Count(buf, []byte{1}) + if j != expect { + b.Fatal("bad count", j, expect) + } + } + clear(buf) + }) +} + +type SplitTest struct { + s string + sep string + n int + a []string +} + +var splittests = []SplitTest{ + {"", "", -1, []string{}}, + {abcd, "a", 0, nil}, + {abcd, "", 2, []string{"a", "bcd"}}, + {abcd, "a", -1, []string{"", "bcd"}}, + {abcd, "z", -1, []string{"abcd"}}, + {abcd, "", -1, []string{"a", "b", "c", "d"}}, + {commas, ",", -1, []string{"1", "2", "3", "4"}}, + {dots, "...", -1, []string{"1", ".2", ".3", ".4"}}, + {faces, "☹", -1, []string{"☺☻", ""}}, + {faces, "~", -1, []string{faces}}, + {faces, "", -1, []string{"☺", "☻", "☹"}}, + {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}}, + {"1 2", " ", 3, []string{"1", "2"}}, + {"123", "", 2, []string{"1", "23"}}, + {"123", "", 17, []string{"1", "2", "3"}}, + {"bT", "T", math.MaxInt / 4, []string{"b", ""}}, + {"\xff-\xff", "", -1, []string{"\xff", "-", "\xff"}}, + {"\xff-\xff", "-", -1, []string{"\xff", "\xff"}}, +} + +func TestSplit(t *testing.T) { + for _, tt := range splittests { + a := SplitN([]byte(tt.s), []byte(tt.sep), tt.n) + + // Appending to the results should not change future results. + var x []byte + for _, v := range a { + x = append(v, 'z') + } + + result := sliceOfString(a) + if !slices.Equal(result, tt.a) { + t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a) + continue + } + + if tt.n < 0 { + b := sliceOfString(slices.Collect(SplitSeq([]byte(tt.s), []byte(tt.sep)))) + if !slices.Equal(b, tt.a) { + t.Errorf(`collect(SplitSeq(%q, %q)) = %v; want %v`, tt.s, tt.sep, b, tt.a) + } + } + + if tt.n == 0 || len(a) == 0 { + continue + } + + if want := tt.a[len(tt.a)-1] + "z"; string(x) != want { + t.Errorf("last appended result was %s; want %s", x, want) + } + + s := Join(a, []byte(tt.sep)) + if string(s) != tt.s { + t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s) + } + if tt.n < 0 { + b := sliceOfString(Split([]byte(tt.s), []byte(tt.sep))) + if !slices.Equal(result, b) { + t.Errorf("Split disagrees with SplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a) + } + } + if len(a) > 0 { + in, out := a[0], s + if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] { + t.Errorf("Join(%#v, %q) didn't copy", a, tt.sep) + } + } + } +} + +var splitaftertests = []SplitTest{ + {abcd, "a", -1, []string{"a", "bcd"}}, + {abcd, "z", -1, []string{"abcd"}}, + {abcd, "", -1, []string{"a", "b", "c", "d"}}, + {commas, ",", -1, []string{"1,", "2,", "3,", "4"}}, + {dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}}, + {faces, "☹", -1, []string{"☺☻☹", ""}}, + {faces, "~", -1, []string{faces}}, + {faces, "", -1, []string{"☺", "☻", "☹"}}, + {"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}}, + {"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}}, + {"1 2", " ", 3, []string{"1 ", "2"}}, + {"123", "", 2, []string{"1", "23"}}, + {"123", "", 17, []string{"1", "2", "3"}}, +} + +func TestSplitAfter(t *testing.T) { + for _, tt := range splitaftertests { + a := SplitAfterN([]byte(tt.s), []byte(tt.sep), tt.n) + + // Appending to the results should not change future results. + var x []byte + for _, v := range a { + x = append(v, 'z') + } + + result := sliceOfString(a) + if !slices.Equal(result, tt.a) { + t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a) + continue + } + + if tt.n < 0 { + b := sliceOfString(slices.Collect(SplitAfterSeq([]byte(tt.s), []byte(tt.sep)))) + if !slices.Equal(b, tt.a) { + t.Errorf(`collect(SplitAfterSeq(%q, %q)) = %v; want %v`, tt.s, tt.sep, b, tt.a) + } + } + + if want := tt.a[len(tt.a)-1] + "z"; string(x) != want { + t.Errorf("last appended result was %s; want %s", x, want) + } + + s := Join(a, nil) + if string(s) != tt.s { + t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s) + } + if tt.n < 0 { + b := sliceOfString(SplitAfter([]byte(tt.s), []byte(tt.sep))) + if !slices.Equal(result, b) { + t.Errorf("SplitAfter disagrees with SplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a) + } + } + } +} + +type FieldsTest struct { + s string + a []string +} + +var fieldstests = []FieldsTest{ + {"", []string{}}, + {" ", []string{}}, + {" \t ", []string{}}, + {" abc ", []string{"abc"}}, + {"1 2 3 4", []string{"1", "2", "3", "4"}}, + {"1 2 3 4", []string{"1", "2", "3", "4"}}, + {"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}}, + {"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}}, + {"\u2000\u2001\u2002", []string{}}, + {"\n™\t™\n", []string{"™", "™"}}, + {faces, []string{faces}}, +} + +func TestFields(t *testing.T) { + for _, tt := range fieldstests { + b := []byte(tt.s) + a := Fields(b) + + // Appending to the results should not change future results. + var x []byte + for _, v := range a { + x = append(v, 'z') + } + + result := sliceOfString(a) + if !slices.Equal(result, tt.a) { + t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a) + continue + } + + result2 := sliceOfString(collect(t, FieldsSeq([]byte(tt.s)))) + if !slices.Equal(result2, tt.a) { + t.Errorf(`collect(FieldsSeq(%q)) = %v; want %v`, tt.s, result2, tt.a) + } + + if string(b) != tt.s { + t.Errorf("slice changed to %s; want %s", string(b), tt.s) + } + if len(tt.a) > 0 { + if want := tt.a[len(tt.a)-1] + "z"; string(x) != want { + t.Errorf("last appended result was %s; want %s", x, want) + } + } + } +} + +func TestFieldsFunc(t *testing.T) { + for _, tt := range fieldstests { + a := FieldsFunc([]byte(tt.s), unicode.IsSpace) + result := sliceOfString(a) + if !slices.Equal(result, tt.a) { + t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a) + continue + } + } + pred := func(c rune) bool { return c == 'X' } + var fieldsFuncTests = []FieldsTest{ + {"", []string{}}, + {"XX", []string{}}, + {"XXhiXXX", []string{"hi"}}, + {"aXXbXXXcX", []string{"a", "b", "c"}}, + } + for _, tt := range fieldsFuncTests { + b := []byte(tt.s) + a := FieldsFunc(b, pred) + + // Appending to the results should not change future results. + var x []byte + for _, v := range a { + x = append(v, 'z') + } + + result := sliceOfString(a) + if !slices.Equal(result, tt.a) { + t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a) + } + + result2 := sliceOfString(collect(t, FieldsFuncSeq([]byte(tt.s), pred))) + if !slices.Equal(result2, tt.a) { + t.Errorf(`collect(FieldsFuncSeq(%q)) = %v; want %v`, tt.s, result2, tt.a) + } + + if string(b) != tt.s { + t.Errorf("slice changed to %s; want %s", b, tt.s) + } + if len(tt.a) > 0 { + if want := tt.a[len(tt.a)-1] + "z"; string(x) != want { + t.Errorf("last appended result was %s; want %s", x, want) + } + } + } +} + +// Test case for any function which accepts and returns a byte slice. +// For ease of creation, we write the input byte slice as a string. +type StringTest struct { + in string + out []byte +} + +var upperTests = []StringTest{ + {"", []byte("")}, + {"ONLYUPPER", []byte("ONLYUPPER")}, + {"abc", []byte("ABC")}, + {"AbC123", []byte("ABC123")}, + {"azAZ09_", []byte("AZAZ09_")}, + {"longStrinGwitHmixofsmaLLandcAps", []byte("LONGSTRINGWITHMIXOFSMALLANDCAPS")}, + {"long\u0250string\u0250with\u0250nonascii\u2C6Fchars", []byte("LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS")}, + {"\u0250\u0250\u0250\u0250\u0250", []byte("\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F")}, // grows one byte per char + {"a\u0080\U0010FFFF", []byte("A\u0080\U0010FFFF")}, // test utf8.RuneSelf and utf8.MaxRune +} + +var lowerTests = []StringTest{ + {"", []byte("")}, + {"abc", []byte("abc")}, + {"AbC123", []byte("abc123")}, + {"azAZ09_", []byte("azaz09_")}, + {"longStrinGwitHmixofsmaLLandcAps", []byte("longstringwithmixofsmallandcaps")}, + {"LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS", []byte("long\u0250string\u0250with\u0250nonascii\u0250chars")}, + {"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", []byte("\u0251\u0251\u0251\u0251\u0251")}, // shrinks one byte per char + {"A\u0080\U0010FFFF", []byte("a\u0080\U0010FFFF")}, // test utf8.RuneSelf and utf8.MaxRune +} + +const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000" + +var trimSpaceTests = []StringTest{ + {"", nil}, + {" a", []byte("a")}, + {"b ", []byte("b")}, + {"abc", []byte("abc")}, + {space + "abc" + space, []byte("abc")}, + {" ", nil}, + {"\u3000 ", nil}, + {" \u3000", nil}, + {" \t\r\n \t\t\r\r\n\n ", nil}, + {" \t\r\n x\t\t\r\r\n\n ", []byte("x")}, + {" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", []byte("x\t\t\r\r\ny")}, + {"1 \t\r\n2", []byte("1 \t\r\n2")}, + {" x\x80", []byte("x\x80")}, + {" x\xc0", []byte("x\xc0")}, + {"x \xc0\xc0 ", []byte("x \xc0\xc0")}, + {"x \xc0", []byte("x \xc0")}, + {"x \xc0 ", []byte("x \xc0")}, + {"x \xc0\xc0 ", []byte("x \xc0\xc0")}, + {"x ☺\xc0\xc0 ", []byte("x ☺\xc0\xc0")}, + {"x ☺ ", []byte("x ☺")}, +} + +// Execute f on each test case. funcName should be the name of f; it's used +// in failure reports. +func runStringTests(t *testing.T, f func([]byte) []byte, funcName string, testCases []StringTest) { + for _, tc := range testCases { + actual := f([]byte(tc.in)) + if actual == nil && tc.out != nil { + t.Errorf("%s(%q) = nil; want %q", funcName, tc.in, tc.out) + } + if actual != nil && tc.out == nil { + t.Errorf("%s(%q) = %q; want nil", funcName, tc.in, actual) + } + if !Equal(actual, tc.out) { + t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out) + } + } +} + +func tenRunes(r rune) string { + runes := make([]rune, 10) + for i := range runes { + runes[i] = r + } + return string(runes) +} + +// User-defined self-inverse mapping function +func rot13(r rune) rune { + const step = 13 + if r >= 'a' && r <= 'z' { + return ((r - 'a' + step) % 26) + 'a' + } + if r >= 'A' && r <= 'Z' { + return ((r - 'A' + step) % 26) + 'A' + } + return r +} + +func TestMap(t *testing.T) { + // Run a couple of awful growth/shrinkage tests + a := tenRunes('a') + + // 1. Grow. This triggers two reallocations in Map. + maxRune := func(r rune) rune { return unicode.MaxRune } + m := Map(maxRune, []byte(a)) + expect := tenRunes(unicode.MaxRune) + if string(m) != expect { + t.Errorf("growing: expected %q got %q", expect, m) + } + + // 2. Shrink + minRune := func(r rune) rune { return 'a' } + m = Map(minRune, []byte(tenRunes(unicode.MaxRune))) + expect = a + if string(m) != expect { + t.Errorf("shrinking: expected %q got %q", expect, m) + } + + // 3. Rot13 + m = Map(rot13, []byte("a to zed")) + expect = "n gb mrq" + if string(m) != expect { + t.Errorf("rot13: expected %q got %q", expect, m) + } + + // 4. Rot13^2 + m = Map(rot13, Map(rot13, []byte("a to zed"))) + expect = "a to zed" + if string(m) != expect { + t.Errorf("rot13: expected %q got %q", expect, m) + } + + // 5. Drop + dropNotLatin := func(r rune) rune { + if unicode.Is(unicode.Latin, r) { + return r + } + return -1 + } + m = Map(dropNotLatin, []byte("Hello, 세계")) + expect = "Hello" + if string(m) != expect { + t.Errorf("drop: expected %q got %q", expect, m) + } + + // 6. Invalid rune + invalidRune := func(r rune) rune { + return utf8.MaxRune + 1 + } + m = Map(invalidRune, []byte("x")) + expect = "\uFFFD" + if string(m) != expect { + t.Errorf("invalidRune: expected %q got %q", expect, m) + } +} + +func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) } + +func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) } + +func BenchmarkToUpper(b *testing.B) { + for _, tc := range upperTests { + tin := []byte(tc.in) + b.Run(tc.in, func(b *testing.B) { + for i := 0; i < b.N; i++ { + actual := ToUpper(tin) + if !Equal(actual, tc.out) { + b.Errorf("ToUpper(%q) = %q; want %q", tc.in, actual, tc.out) + } + } + }) + } +} + +func BenchmarkToLower(b *testing.B) { + for _, tc := range lowerTests { + tin := []byte(tc.in) + b.Run(tc.in, func(b *testing.B) { + for i := 0; i < b.N; i++ { + actual := ToLower(tin) + if !Equal(actual, tc.out) { + b.Errorf("ToLower(%q) = %q; want %q", tc.in, actual, tc.out) + } + } + }) + } +} + +var toValidUTF8Tests = []struct { + in string + repl string + out string +}{ + {"", "\uFFFD", ""}, + {"abc", "\uFFFD", "abc"}, + {"\uFDDD", "\uFFFD", "\uFDDD"}, + {"a\xffb", "\uFFFD", "a\uFFFDb"}, + {"a\xffb\uFFFD", "X", "aXb\uFFFD"}, + {"a☺\xffb☺\xC0\xAFc☺\xff", "", "a☺b☺c☺"}, + {"a☺\xffb☺\xC0\xAFc☺\xff", "日本語", "a☺日本語b☺日本語c☺日本語"}, + {"\xC0\xAF", "\uFFFD", "\uFFFD"}, + {"\xE0\x80\xAF", "\uFFFD", "\uFFFD"}, + {"\xed\xa0\x80", "abc", "abc"}, + {"\xed\xbf\xbf", "\uFFFD", "\uFFFD"}, + {"\xF0\x80\x80\xaf", "☺", "☺"}, + {"\xF8\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"}, + {"\xFC\x80\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"}, +} + +func TestToValidUTF8(t *testing.T) { + for _, tc := range toValidUTF8Tests { + got := ToValidUTF8([]byte(tc.in), []byte(tc.repl)) + if !Equal(got, []byte(tc.out)) { + t.Errorf("ToValidUTF8(%q, %q) = %q; want %q", tc.in, tc.repl, got, tc.out) + } + } +} + +func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) } + +type RepeatTest struct { + in, out string + count int +} + +var longString = "a" + string(make([]byte, 1<<16)) + "z" + +var RepeatTests = []RepeatTest{ + {"", "", 0}, + {"", "", 1}, + {"", "", 2}, + {"-", "", 0}, + {"-", "-", 1}, + {"-", "----------", 10}, + {"abc ", "abc abc abc ", 3}, + // Tests for results over the chunkLimit + {string(rune(0)), string(make([]byte, 1<<16)), 1 << 16}, + {longString, longString + longString, 2}, +} + +func TestRepeat(t *testing.T) { + for _, tt := range RepeatTests { + tin := []byte(tt.in) + tout := []byte(tt.out) + a := Repeat(tin, tt.count) + if !Equal(a, tout) { + t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout) + continue + } + } +} + +func repeat(b []byte, count int) (err error) { + defer func() { + if r := recover(); r != nil { + switch v := r.(type) { + case error: + err = v + default: + err = fmt.Errorf("%s", v) + } + } + }() + + Repeat(b, count) + + return +} + +// See Issue golang.org/issue/16237 +func TestRepeatCatchesOverflow(t *testing.T) { + type testCase struct { + s string + count int + errStr string + } + + runTestCases := func(prefix string, tests []testCase) { + for i, tt := range tests { + err := repeat([]byte(tt.s), tt.count) + if tt.errStr == "" { + if err != nil { + t.Errorf("#%d panicked %v", i, err) + } + continue + } + + if err == nil || !strings.Contains(err.Error(), tt.errStr) { + t.Errorf("%s#%d got %q want %q", prefix, i, err, tt.errStr) + } + } + } + + const maxInt = int(^uint(0) >> 1) + + runTestCases("", []testCase{ + 0: {"--", -2147483647, "negative"}, + 1: {"", maxInt, ""}, + 2: {"-", 10, ""}, + 3: {"gopher", 0, ""}, + 4: {"-", -1, "negative"}, + 5: {"--", -102, "negative"}, + 6: {string(make([]byte, 255)), int((^uint(0))/255 + 1), "overflow"}, + }) + + const is64Bit = 1<<(^uintptr(0)>>63)/2 != 0 + if !is64Bit { + return + } + + runTestCases("64-bit", []testCase{ + 0: {"-", maxInt, "out of range"}, + }) +} + +type RunesTest struct { + in string + out []rune + lossy bool +} + +var RunesTests = []RunesTest{ + {"", []rune{}, false}, + {" ", []rune{32}, false}, + {"ABC", []rune{65, 66, 67}, false}, + {"abc", []rune{97, 98, 99}, false}, + {"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false}, + {"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true}, + {"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true}, +} + +func TestRunes(t *testing.T) { + for _, tt := range RunesTests { + tin := []byte(tt.in) + a := Runes(tin) + if !slices.Equal(a, tt.out) { + t.Errorf("Runes(%q) = %v; want %v", tin, a, tt.out) + continue + } + if !tt.lossy { + // can only test reassembly if we didn't lose information + s := string(a) + if s != tt.in { + t.Errorf("string(Runes(%q)) = %x; want %x", tin, s, tin) + } + } + } +} + +type TrimTest struct { + f string + in, arg, out string +} + +var trimTests = []TrimTest{ + {"Trim", "abba", "a", "bb"}, + {"Trim", "abba", "ab", ""}, + {"TrimLeft", "abba", "ab", ""}, + {"TrimRight", "abba", "ab", ""}, + {"TrimLeft", "abba", "a", "bba"}, + {"TrimLeft", "abba", "b", "abba"}, + {"TrimRight", "abba", "a", "abb"}, + {"TrimRight", "abba", "b", "abba"}, + {"Trim", "", "<>", "tag"}, + {"Trim", "* listitem", " *", "listitem"}, + {"Trim", `"quote"`, `"`, "quote"}, + {"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"}, + {"Trim", "\x80test\xff", "\xff", "test"}, + {"Trim", " Ġ ", " ", "Ġ"}, + {"Trim", " Ġİ0", "0 ", "Ġİ"}, + //empty string tests + {"Trim", "abba", "", "abba"}, + {"Trim", "", "123", ""}, + {"Trim", "", "", ""}, + {"TrimLeft", "abba", "", "abba"}, + {"TrimLeft", "", "123", ""}, + {"TrimLeft", "", "", ""}, + {"TrimRight", "abba", "", "abba"}, + {"TrimRight", "", "123", ""}, + {"TrimRight", "", "", ""}, + {"TrimRight", "☺\xc0", "☺", "☺\xc0"}, + {"TrimPrefix", "aabb", "a", "abb"}, + {"TrimPrefix", "aabb", "b", "aabb"}, + {"TrimSuffix", "aabb", "a", "aabb"}, + {"TrimSuffix", "aabb", "b", "aab"}, +} + +type TrimNilTest struct { + f string + in []byte + arg string + out []byte +} + +var trimNilTests = []TrimNilTest{ + {"Trim", nil, "", nil}, + {"Trim", []byte{}, "", nil}, + {"Trim", []byte{'a'}, "a", nil}, + {"Trim", []byte{'a', 'a'}, "a", nil}, + {"Trim", []byte{'a'}, "ab", nil}, + {"Trim", []byte{'a', 'b'}, "ab", nil}, + {"Trim", []byte("☺"), "☺", nil}, + {"TrimLeft", nil, "", nil}, + {"TrimLeft", []byte{}, "", nil}, + {"TrimLeft", []byte{'a'}, "a", nil}, + {"TrimLeft", []byte{'a', 'a'}, "a", nil}, + {"TrimLeft", []byte{'a'}, "ab", nil}, + {"TrimLeft", []byte{'a', 'b'}, "ab", nil}, + {"TrimLeft", []byte("☺"), "☺", nil}, + {"TrimRight", nil, "", nil}, + {"TrimRight", []byte{}, "", []byte{}}, + {"TrimRight", []byte{'a'}, "a", []byte{}}, + {"TrimRight", []byte{'a', 'a'}, "a", []byte{}}, + {"TrimRight", []byte{'a'}, "ab", []byte{}}, + {"TrimRight", []byte{'a', 'b'}, "ab", []byte{}}, + {"TrimRight", []byte("☺"), "☺", []byte{}}, + {"TrimPrefix", nil, "", nil}, + {"TrimPrefix", []byte{}, "", []byte{}}, + {"TrimPrefix", []byte{'a'}, "a", []byte{}}, + {"TrimPrefix", []byte("☺"), "☺", []byte{}}, + {"TrimSuffix", nil, "", nil}, + {"TrimSuffix", []byte{}, "", []byte{}}, + {"TrimSuffix", []byte{'a'}, "a", []byte{}}, + {"TrimSuffix", []byte("☺"), "☺", []byte{}}, +} + +func TestTrim(t *testing.T) { + toFn := func(name string) (func([]byte, string) []byte, func([]byte, []byte) []byte) { + switch name { + case "Trim": + return Trim, nil + case "TrimLeft": + return TrimLeft, nil + case "TrimRight": + return TrimRight, nil + case "TrimPrefix": + return nil, TrimPrefix + case "TrimSuffix": + return nil, TrimSuffix + default: + t.Errorf("Undefined trim function %s", name) + return nil, nil + } + } + + for _, tc := range trimTests { + name := tc.f + f, fb := toFn(name) + if f == nil && fb == nil { + continue + } + var actual string + if f != nil { + actual = string(f([]byte(tc.in), tc.arg)) + } else { + actual = string(fb([]byte(tc.in), []byte(tc.arg))) + } + if actual != tc.out { + t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out) + } + } + + for _, tc := range trimNilTests { + name := tc.f + f, fb := toFn(name) + if f == nil && fb == nil { + continue + } + var actual []byte + if f != nil { + actual = f(tc.in, tc.arg) + } else { + actual = fb(tc.in, []byte(tc.arg)) + } + report := func(s []byte) string { + if s == nil { + return "nil" + } else { + return fmt.Sprintf("%q", s) + } + } + if len(actual) != 0 { + t.Errorf("%s(%s, %q) returned non-empty value", name, report(tc.in), tc.arg) + } else { + actualNil := actual == nil + outNil := tc.out == nil + if actualNil != outNil { + t.Errorf("%s(%s, %q) got nil %t; want nil %t", name, report(tc.in), tc.arg, actualNil, outNil) + } + } + } +} + +type predicate struct { + f func(r rune) bool + name string +} + +var isSpace = predicate{unicode.IsSpace, "IsSpace"} +var isDigit = predicate{unicode.IsDigit, "IsDigit"} +var isUpper = predicate{unicode.IsUpper, "IsUpper"} +var isValidRune = predicate{ + func(r rune) bool { + return r != utf8.RuneError + }, + "IsValidRune", +} + +type TrimFuncTest struct { + f predicate + in string + trimOut []byte + leftOut []byte + rightOut []byte +} + +func not(p predicate) predicate { + return predicate{ + func(r rune) bool { + return !p.f(r) + }, + "not " + p.name, + } +} + +var trimFuncTests = []TrimFuncTest{ + {isSpace, space + " hello " + space, + []byte("hello"), + []byte("hello " + space), + []byte(space + " hello")}, + {isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51", + []byte("hello"), + []byte("hello34\u0e50\u0e51"), + []byte("\u0e50\u0e5212hello")}, + {isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", + []byte("hello"), + []byte("helloEF\u2C6F\u2C6FGH\u2C6F\u2C6F"), + []byte("\u2C6F\u2C6F\u2C6F\u2C6FABCDhello")}, + {not(isSpace), "hello" + space + "hello", + []byte(space), + []byte(space + "hello"), + []byte("hello" + space)}, + {not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo", + []byte("\u0e50\u0e521234\u0e50\u0e51"), + []byte("\u0e50\u0e521234\u0e50\u0e51helo"), + []byte("hello\u0e50\u0e521234\u0e50\u0e51")}, + {isValidRune, "ab\xc0a\xc0cd", + []byte("\xc0a\xc0"), + []byte("\xc0a\xc0cd"), + []byte("ab\xc0a\xc0")}, + {not(isValidRune), "\xc0a\xc0", + []byte("a"), + []byte("a\xc0"), + []byte("\xc0a")}, + // The nils returned by TrimLeftFunc are odd behavior, but we need + // to preserve backwards compatibility. + {isSpace, "", + nil, + nil, + []byte("")}, + {isSpace, " ", + nil, + nil, + []byte("")}, +} + +func TestTrimFunc(t *testing.T) { + for _, tc := range trimFuncTests { + trimmers := []struct { + name string + trim func(s []byte, f func(r rune) bool) []byte + out []byte + }{ + {"TrimFunc", TrimFunc, tc.trimOut}, + {"TrimLeftFunc", TrimLeftFunc, tc.leftOut}, + {"TrimRightFunc", TrimRightFunc, tc.rightOut}, + } + for _, trimmer := range trimmers { + actual := trimmer.trim([]byte(tc.in), tc.f.f) + if actual == nil && trimmer.out != nil { + t.Errorf("%s(%q, %q) = nil; want %q", trimmer.name, tc.in, tc.f.name, trimmer.out) + } + if actual != nil && trimmer.out == nil { + t.Errorf("%s(%q, %q) = %q; want nil", trimmer.name, tc.in, tc.f.name, actual) + } + if !Equal(actual, trimmer.out) { + t.Errorf("%s(%q, %q) = %q; want %q", trimmer.name, tc.in, tc.f.name, actual, trimmer.out) + } + } + } +} + +type IndexFuncTest struct { + in string + f predicate + first, last int +} + +var indexFuncTests = []IndexFuncTest{ + {"", isValidRune, -1, -1}, + {"abc", isDigit, -1, -1}, + {"0123", isDigit, 0, 3}, + {"a1b", isDigit, 1, 1}, + {space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes + {"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18}, + {"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34}, + {"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12}, + + // tests of invalid UTF-8 + {"\x801", isDigit, 1, 1}, + {"\x80abc", isDigit, -1, -1}, + {"\xc0a\xc0", isValidRune, 1, 1}, + {"\xc0a\xc0", not(isValidRune), 0, 2}, + {"\xc0☺\xc0", not(isValidRune), 0, 4}, + {"\xc0☺\xc0\xc0", not(isValidRune), 0, 5}, + {"ab\xc0a\xc0cd", not(isValidRune), 2, 4}, + {"a\xe0\x80cd", not(isValidRune), 1, 2}, +} + +func TestIndexFunc(t *testing.T) { + for _, tc := range indexFuncTests { + first := IndexFunc([]byte(tc.in), tc.f.f) + if first != tc.first { + t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first) + } + last := LastIndexFunc([]byte(tc.in), tc.f.f) + if last != tc.last { + t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last) + } + } +} + +type ReplaceTest struct { + in string + old, new string + n int + out string +} + +var ReplaceTests = []ReplaceTest{ + {"hello", "l", "L", 0, "hello"}, + {"hello", "l", "L", -1, "heLLo"}, + {"hello", "x", "X", -1, "hello"}, + {"", "x", "X", -1, ""}, + {"radar", "r", "", -1, "ada"}, + {"", "", "<>", -1, "<>"}, + {"banana", "a", "<>", -1, "b<>n<>n<>"}, + {"banana", "a", "<>", 1, "b<>nana"}, + {"banana", "a", "<>", 1000, "b<>n<>n<>"}, + {"banana", "an", "<>", -1, "b<><>a"}, + {"banana", "ana", "<>", -1, "b<>na"}, + {"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"}, + {"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"}, + {"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"}, + {"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"}, + {"banana", "", "<>", 1, "<>banana"}, + {"banana", "a", "a", -1, "banana"}, + {"banana", "a", "a", 1, "banana"}, + {"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"}, +} + +func TestReplace(t *testing.T) { + for _, tt := range ReplaceTests { + var ( + in = []byte(tt.in) + old = []byte(tt.old) + new = []byte(tt.new) + ) + if !asan.Enabled { + allocs := testing.AllocsPerRun(10, func() { Replace(in, old, new, tt.n) }) + if allocs > 1 { + t.Errorf("Replace(%q, %q, %q, %d) allocates %.2f objects", tt.in, tt.old, tt.new, tt.n, allocs) + } + } + in = append(in, ""...) + in = in[:len(tt.in)] + out := Replace(in, old, new, tt.n) + if s := string(out); s != tt.out { + t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out) + } + if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] { + t.Errorf("Replace(%q, %q, %q, %d) didn't copy", tt.in, tt.old, tt.new, tt.n) + } + if tt.n == -1 { + out := ReplaceAll(in, old, new) + if s := string(out); s != tt.out { + t.Errorf("ReplaceAll(%q, %q, %q) = %q, want %q", tt.in, tt.old, tt.new, s, tt.out) + } + } + } +} + +func FuzzReplace(f *testing.F) { + for _, tt := range ReplaceTests { + f.Add([]byte(tt.in), []byte(tt.old), []byte(tt.new), tt.n) + } + f.Fuzz(func(t *testing.T, in, old, new []byte, n int) { + differentImpl := func(in, old, new []byte, n int) []byte { + var out Buffer + if n < 0 { + n = math.MaxInt + } + for i := 0; i < len(in); { + if n == 0 { + out.Write(in[i:]) + break + } + if HasPrefix(in[i:], old) { + out.Write(new) + i += len(old) + n-- + if len(old) != 0 { + continue + } + if i == len(in) { + break + } + } + if len(old) == 0 { + _, length := utf8.DecodeRune(in[i:]) + out.Write(in[i : i+length]) + i += length + } else { + out.WriteByte(in[i]) + i++ + } + } + if len(old) == 0 && n != 0 { + out.Write(new) + } + return out.Bytes() + } + if simple, replace := differentImpl(in, old, new, n), Replace(in, old, new, n); !slices.Equal(simple, replace) { + t.Errorf("The two implementations do not match %q != %q for Replace(%q, %q, %q, %d)", simple, replace, in, old, new, n) + } + }) +} + +func BenchmarkReplace(b *testing.B) { + for _, tt := range ReplaceTests { + desc := fmt.Sprintf("%q %q %q %d", tt.in, tt.old, tt.new, tt.n) + var ( + in = []byte(tt.in) + old = []byte(tt.old) + new = []byte(tt.new) + ) + b.Run(desc, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + Replace(in, old, new, tt.n) + } + }) + } +} + +type TitleTest struct { + in, out string +} + +var TitleTests = []TitleTest{ + {"", ""}, + {"a", "A"}, + {" aaa aaa aaa ", " Aaa Aaa Aaa "}, + {" Aaa Aaa Aaa ", " Aaa Aaa Aaa "}, + {"123a456", "123a456"}, + {"double-blind", "Double-Blind"}, + {"ÿøû", "Ÿøû"}, + {"with_underscore", "With_underscore"}, + {"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"}, +} + +func TestTitle(t *testing.T) { + for _, tt := range TitleTests { + if s := string(Title([]byte(tt.in))); s != tt.out { + t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out) + } + } +} + +var ToTitleTests = []TitleTest{ + {"", ""}, + {"a", "A"}, + {" aaa aaa aaa ", " AAA AAA AAA "}, + {" Aaa Aaa Aaa ", " AAA AAA AAA "}, + {"123a456", "123A456"}, + {"double-blind", "DOUBLE-BLIND"}, + {"ÿøû", "ŸØÛ"}, +} + +func TestToTitle(t *testing.T) { + for _, tt := range ToTitleTests { + if s := string(ToTitle([]byte(tt.in))); s != tt.out { + t.Errorf("ToTitle(%q) = %q, want %q", tt.in, s, tt.out) + } + } +} + +var EqualFoldTests = []struct { + s, t string + out bool +}{ + {"abc", "abc", true}, + {"ABcd", "ABcd", true}, + {"123abc", "123ABC", true}, + {"αβδ", "ΑΒΔ", true}, + {"abc", "xyz", false}, + {"abc", "XYZ", false}, + {"abcdefghijk", "abcdefghijX", false}, + {"abcdefghijk", "abcdefghij\u212A", true}, + {"abcdefghijK", "abcdefghij\u212A", true}, + {"abcdefghijkz", "abcdefghij\u212Ay", false}, + {"abcdefghijKz", "abcdefghij\u212Ay", false}, +} + +func TestEqualFold(t *testing.T) { + for _, tt := range EqualFoldTests { + if out := EqualFold([]byte(tt.s), []byte(tt.t)); out != tt.out { + t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out) + } + if out := EqualFold([]byte(tt.t), []byte(tt.s)); out != tt.out { + t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out) + } + } +} + +var cutTests = []struct { + s, sep string + before, after string + found bool +}{ + {"abc", "b", "a", "c", true}, + {"abc", "a", "", "bc", true}, + {"abc", "c", "ab", "", true}, + {"abc", "abc", "", "", true}, + {"abc", "", "", "abc", true}, + {"abc", "d", "abc", "", false}, + {"", "d", "", "", false}, + {"", "", "", "", true}, +} + +func TestCut(t *testing.T) { + for _, tt := range cutTests { + if before, after, found := Cut([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || string(after) != tt.after || found != tt.found { + t.Errorf("Cut(%q, %q) = %q, %q, %v, want %q, %q, %v", tt.s, tt.sep, before, after, found, tt.before, tt.after, tt.found) + } + } +} + +var cutPrefixTests = []struct { + s, sep string + after string + found bool +}{ + {"abc", "a", "bc", true}, + {"abc", "abc", "", true}, + {"abc", "", "abc", true}, + {"abc", "d", "abc", false}, + {"", "d", "", false}, + {"", "", "", true}, +} + +func TestCutPrefix(t *testing.T) { + for _, tt := range cutPrefixTests { + if after, found := CutPrefix([]byte(tt.s), []byte(tt.sep)); string(after) != tt.after || found != tt.found { + t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found) + } + } +} + +var cutSuffixTests = []struct { + s, sep string + before string + found bool +}{ + {"abc", "bc", "a", true}, + {"abc", "abc", "", true}, + {"abc", "", "abc", true}, + {"abc", "d", "abc", false}, + {"", "d", "", false}, + {"", "", "", true}, +} + +func TestCutSuffix(t *testing.T) { + for _, tt := range cutSuffixTests { + if before, found := CutSuffix([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || found != tt.found { + t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, before, found, tt.before, tt.found) + } + } +} + +func TestBufferGrowNegative(t *testing.T) { + defer func() { + if err := recover(); err == nil { + t.Fatal("Grow(-1) should have panicked") + } + }() + var b Buffer + b.Grow(-1) +} + +func TestBufferTruncateNegative(t *testing.T) { + defer func() { + if err := recover(); err == nil { + t.Fatal("Truncate(-1) should have panicked") + } + }() + var b Buffer + b.Truncate(-1) +} + +func TestBufferTruncateOutOfRange(t *testing.T) { + defer func() { + if err := recover(); err == nil { + t.Fatal("Truncate(20) should have panicked") + } + }() + var b Buffer + b.Write(make([]byte, 10)) + b.Truncate(20) +} + +var containsTests = []struct { + b, subslice []byte + want bool +}{ + {[]byte("hello"), []byte("hel"), true}, + {[]byte("日本語"), []byte("日本"), true}, + {[]byte("hello"), []byte("Hello, world"), false}, + {[]byte("東京"), []byte("京東"), false}, +} + +func TestContains(t *testing.T) { + for _, tt := range containsTests { + if got := Contains(tt.b, tt.subslice); got != tt.want { + t.Errorf("Contains(%q, %q) = %v, want %v", tt.b, tt.subslice, got, tt.want) + } + } +} + +var ContainsAnyTests = []struct { + b []byte + substr string + expected bool +}{ + {[]byte(""), "", false}, + {[]byte(""), "a", false}, + {[]byte(""), "abc", false}, + {[]byte("a"), "", false}, + {[]byte("a"), "a", true}, + {[]byte("aaa"), "a", true}, + {[]byte("abc"), "xyz", false}, + {[]byte("abc"), "xcz", true}, + {[]byte("a☺b☻c☹d"), "uvw☻xyz", true}, + {[]byte("aRegExp*"), ".(|)*+?^$[]", true}, + {[]byte(dots + dots + dots), " ", false}, +} + +func TestContainsAny(t *testing.T) { + for _, ct := range ContainsAnyTests { + if ContainsAny(ct.b, ct.substr) != ct.expected { + t.Errorf("ContainsAny(%s, %s) = %v, want %v", + ct.b, ct.substr, !ct.expected, ct.expected) + } + } +} + +var ContainsRuneTests = []struct { + b []byte + r rune + expected bool +}{ + {[]byte(""), 'a', false}, + {[]byte("a"), 'a', true}, + {[]byte("aaa"), 'a', true}, + {[]byte("abc"), 'y', false}, + {[]byte("abc"), 'c', true}, + {[]byte("a☺b☻c☹d"), 'x', false}, + {[]byte("a☺b☻c☹d"), '☻', true}, + {[]byte("aRegExp*"), '*', true}, +} + +func TestContainsRune(t *testing.T) { + for _, ct := range ContainsRuneTests { + if ContainsRune(ct.b, ct.r) != ct.expected { + t.Errorf("ContainsRune(%q, %q) = %v, want %v", + ct.b, ct.r, !ct.expected, ct.expected) + } + } +} + +func TestContainsFunc(t *testing.T) { + for _, ct := range ContainsRuneTests { + if ContainsFunc(ct.b, func(r rune) bool { + return ct.r == r + }) != ct.expected { + t.Errorf("ContainsFunc(%q, func(%q)) = %v, want %v", + ct.b, ct.r, !ct.expected, ct.expected) + } + } +} + +var makeFieldsInput = func() []byte { + x := make([]byte, 1<<20) + // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space. + r := rand.New(rand.NewSource(99)) + for i := range x { + switch r.Intn(10) { + case 0: + x[i] = ' ' + case 1: + if i > 0 && x[i-1] == 'x' { + copy(x[i-1:], "χ") + break + } + fallthrough + default: + x[i] = 'x' + } + } + return x +} + +var makeFieldsInputASCII = func() []byte { + x := make([]byte, 1<<20) + // Input is ~10% space, rest ASCII non-space. + r := rand.New(rand.NewSource(99)) + for i := range x { + if r.Intn(10) == 0 { + x[i] = ' ' + } else { + x[i] = 'x' + } + } + return x +} + +var bytesdata = []struct { + name string + data []byte +}{ + {"ASCII", makeFieldsInputASCII()}, + {"Mixed", makeFieldsInput()}, +} + +func BenchmarkFields(b *testing.B) { + for _, sd := range bytesdata { + b.Run(sd.name, func(b *testing.B) { + for j := 1 << 4; j <= 1<<20; j <<= 4 { + b.Run(fmt.Sprintf("%d", j), func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(j)) + data := sd.data[:j] + for i := 0; i < b.N; i++ { + Fields(data) + } + }) + } + }) + } +} + +func BenchmarkFieldsFunc(b *testing.B) { + for _, sd := range bytesdata { + b.Run(sd.name, func(b *testing.B) { + for j := 1 << 4; j <= 1<<20; j <<= 4 { + b.Run(fmt.Sprintf("%d", j), func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(j)) + data := sd.data[:j] + for i := 0; i < b.N; i++ { + FieldsFunc(data, unicode.IsSpace) + } + }) + } + }) + } +} + +func BenchmarkTrimSpace(b *testing.B) { + tests := []struct { + name string + input []byte + }{ + {"NoTrim", []byte("typical")}, + {"ASCII", []byte(" foo bar ")}, + {"SomeNonASCII", []byte(" \u2000\t\r\n x\t\t\r\r\ny\n \u3000 ")}, + {"JustNonASCII", []byte("\u2000\u2000\u2000☺☺☺☺\u3000\u3000\u3000")}, + } + for _, test := range tests { + b.Run(test.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + TrimSpace(test.input) + } + }) + } +} + +func BenchmarkToValidUTF8(b *testing.B) { + tests := []struct { + name string + input []byte + }{ + {"Valid", []byte("typical")}, + {"InvalidASCII", []byte("foo\xffbar")}, + {"InvalidNonASCII", []byte("日本語\xff日本語")}, + } + replacement := []byte("\uFFFD") + b.ResetTimer() + for _, test := range tests { + b.Run(test.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + ToValidUTF8(test.input, replacement) + } + }) + } +} + +func makeBenchInputHard() []byte { + tokens := [...]string{ + "", "

", "", "", + "", "

", "", "", + "hello", "world", + } + x := make([]byte, 0, 1<<20) + r := rand.New(rand.NewSource(99)) + for { + i := r.Intn(len(tokens)) + if len(x)+len(tokens[i]) >= 1<<20 { + break + } + x = append(x, tokens[i]...) + } + return x +} + +var benchInputHard = makeBenchInputHard() + +func benchmarkIndexHard(b *testing.B, sep []byte) { + n := Index(benchInputHard, sep) + if n < 0 { + n = len(benchInputHard) + } + b.SetBytes(int64(n)) + for i := 0; i < b.N; i++ { + Index(benchInputHard, sep) + } +} + +func benchmarkLastIndexHard(b *testing.B, sep []byte) { + for i := 0; i < b.N; i++ { + LastIndex(benchInputHard, sep) + } +} + +func benchmarkCountHard(b *testing.B, sep []byte) { + for i := 0; i < b.N; i++ { + Count(benchInputHard, sep) + } +} + +func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, []byte("<>")) } +func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, []byte("")) } +func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, []byte("hello world")) } +func BenchmarkIndexHard4(b *testing.B) { + benchmarkIndexHard(b, []byte("
helloworld
")) +} + +func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, []byte("<>")) } +func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, []byte("")) } +func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, []byte("hello world")) } + +func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, []byte("<>")) } +func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, []byte("")) } +func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, []byte("hello world")) } + +func BenchmarkSplitEmptySeparator(b *testing.B) { + for i := 0; i < b.N; i++ { + Split(benchInputHard, nil) + } +} + +func BenchmarkSplitSingleByteSeparator(b *testing.B) { + sep := []byte("/") + for i := 0; i < b.N; i++ { + Split(benchInputHard, sep) + } +} + +func BenchmarkSplitMultiByteSeparator(b *testing.B) { + sep := []byte("hello") + for i := 0; i < b.N; i++ { + Split(benchInputHard, sep) + } +} + +func BenchmarkSplitNSingleByteSeparator(b *testing.B) { + sep := []byte("/") + for i := 0; i < b.N; i++ { + SplitN(benchInputHard, sep, 10) + } +} + +func BenchmarkSplitNMultiByteSeparator(b *testing.B) { + sep := []byte("hello") + for i := 0; i < b.N; i++ { + SplitN(benchInputHard, sep, 10) + } +} + +func BenchmarkRepeat(b *testing.B) { + for i := 0; i < b.N; i++ { + Repeat([]byte("-"), 80) + } +} + +func BenchmarkRepeatLarge(b *testing.B) { + s := Repeat([]byte("@"), 8*1024) + for j := 8; j <= 30; j++ { + for _, k := range []int{1, 16, 4097} { + s := s[:k] + n := (1 << j) / k + if n == 0 { + continue + } + b.Run(fmt.Sprintf("%d/%d", 1< b[:1] failed") + } +} + +func TestCompareBytes(t *testing.T) { + lengths := make([]int, 0) // lengths to test in ascending order + for i := 0; i <= 128; i++ { + lengths = append(lengths, i) + } + lengths = append(lengths, 256, 512, 1024, 1333, 4095, 4096, 4097) + + if !testing.Short() { + lengths = append(lengths, 65535, 65536, 65537, 99999) + } + + n := lengths[len(lengths)-1] + a := make([]byte, n+1) + b := make([]byte, n+1) + for _, len := range lengths { + // randomish but deterministic data. No 0 or 255. + for i := 0; i < len; i++ { + a[i] = byte(1 + 31*i%254) + b[i] = byte(1 + 31*i%254) + } + // data past the end is different + for i := len; i <= n; i++ { + a[i] = 8 + b[i] = 9 + } + cmp := Compare(a[:len], b[:len]) + if cmp != 0 { + t.Errorf(`CompareIdentical(%d) = %d`, len, cmp) + } + if len > 0 { + cmp = Compare(a[:len-1], b[:len]) + if cmp != -1 { + t.Errorf(`CompareAshorter(%d) = %d`, len, cmp) + } + cmp = Compare(a[:len], b[:len-1]) + if cmp != 1 { + t.Errorf(`CompareBshorter(%d) = %d`, len, cmp) + } + } + for k := 0; k < len; k++ { + b[k] = a[k] - 1 + cmp = Compare(a[:len], b[:len]) + if cmp != 1 { + t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp) + } + b[k] = a[k] + 1 + cmp = Compare(a[:len], b[:len]) + if cmp != -1 { + t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp) + } + b[k] = a[k] + } + } +} + +func TestEndianBaseCompare(t *testing.T) { + // This test compares byte slices that are almost identical, except one + // difference that for some j, a[j]>b[j] and a[j+1] b2 failed") + } + } +} + +func BenchmarkCompareBytesEmpty(b *testing.B) { + b1 := []byte("") + b2 := b1 + for i := 0; i < b.N; i++ { + if Compare(b1, b2) != 0 { + b.Fatal("b1 != b2") + } + } +} + +func BenchmarkCompareBytesIdentical(b *testing.B) { + b1 := []byte("Hello Gophers!") + b2 := b1 + for i := 0; i < b.N; i++ { + if Compare(b1, b2) != 0 { + b.Fatal("b1 != b2") + } + } +} + +func BenchmarkCompareBytesSameLength(b *testing.B) { + b1 := []byte("Hello Gophers!") + b2 := []byte("Hello, Gophers") + for i := 0; i < b.N; i++ { + if Compare(b1, b2) != -1 { + b.Fatal("b1 < b2 failed") + } + } +} + +func BenchmarkCompareBytesDifferentLength(b *testing.B) { + b1 := []byte("Hello Gophers!") + b2 := []byte("Hello, Gophers!") + for i := 0; i < b.N; i++ { + if Compare(b1, b2) != -1 { + b.Fatal("b1 < b2 failed") + } + } +} + +func benchmarkCompareBytesBigUnaligned(b *testing.B, offset int) { + b.StopTimer() + b1 := make([]byte, 0, 1<<20) + for len(b1) < 1<<20 { + b1 = append(b1, "Hello Gophers!"...) + } + b2 := append([]byte("12345678")[:offset], b1...) + b.StartTimer() + for j := 0; j < b.N; j++ { + if Compare(b1, b2[offset:]) != 0 { + b.Fatal("b1 != b2") + } + } + b.SetBytes(int64(len(b1))) +} + +func BenchmarkCompareBytesBigUnaligned(b *testing.B) { + for i := 1; i < 8; i++ { + b.Run(fmt.Sprintf("offset=%d", i), func(b *testing.B) { + benchmarkCompareBytesBigUnaligned(b, i) + }) + } +} + +func benchmarkCompareBytesBigBothUnaligned(b *testing.B, offset int) { + b.StopTimer() + pattern := []byte("Hello Gophers!") + b1 := make([]byte, 0, 1<<20+len(pattern)) + for len(b1) < 1<<20 { + b1 = append(b1, pattern...) + } + b2 := make([]byte, len(b1)) + copy(b2, b1) + b.StartTimer() + for j := 0; j < b.N; j++ { + if Compare(b1[offset:], b2[offset:]) != 0 { + b.Fatal("b1 != b2") + } + } + b.SetBytes(int64(len(b1[offset:]))) +} + +func BenchmarkCompareBytesBigBothUnaligned(b *testing.B) { + for i := 0; i < 8; i++ { + b.Run(fmt.Sprintf("offset=%d", i), func(b *testing.B) { + benchmarkCompareBytesBigBothUnaligned(b, i) + }) + } +} + +func BenchmarkCompareBytesBig(b *testing.B) { + b.StopTimer() + b1 := make([]byte, 0, 1<<20) + for len(b1) < 1<<20 { + b1 = append(b1, "Hello Gophers!"...) + } + b2 := append([]byte{}, b1...) + b.StartTimer() + for i := 0; i < b.N; i++ { + if Compare(b1, b2) != 0 { + b.Fatal("b1 != b2") + } + } + b.SetBytes(int64(len(b1))) +} + +func BenchmarkCompareBytesBigIdentical(b *testing.B) { + b.StopTimer() + b1 := make([]byte, 0, 1<<20) + for len(b1) < 1<<20 { + b1 = append(b1, "Hello Gophers!"...) + } + b2 := b1 + b.StartTimer() + for i := 0; i < b.N; i++ { + if Compare(b1, b2) != 0 { + b.Fatal("b1 != b2") + } + } + b.SetBytes(int64(len(b1))) +} diff --git a/go/src/bytes/example_test.go b/go/src/bytes/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c489b950e59a913d794cd6f6d5568c21abe667c4 --- /dev/null +++ b/go/src/bytes/example_test.go @@ -0,0 +1,720 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes_test + +import ( + "bytes" + "encoding/base64" + "fmt" + "io" + "os" + "slices" + "strconv" + "unicode" +) + +func ExampleBuffer() { + var b bytes.Buffer // A Buffer needs no initialization. + b.Write([]byte("Hello ")) + fmt.Fprintf(&b, "world!") + b.WriteTo(os.Stdout) + // Output: Hello world! +} + +func ExampleBuffer_reader() { + // A Buffer can turn a string or a []byte into an io.Reader. + buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==") + dec := base64.NewDecoder(base64.StdEncoding, buf) + io.Copy(os.Stdout, dec) + // Output: Gophers rule! +} + +func ExampleBuffer_Bytes() { + buf := bytes.Buffer{} + buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}) + os.Stdout.Write(buf.Bytes()) + // Output: hello world +} + +func ExampleBuffer_AvailableBuffer() { + var buf bytes.Buffer + for i := 0; i < 4; i++ { + b := buf.AvailableBuffer() + b = strconv.AppendInt(b, int64(i), 10) + b = append(b, ' ') + buf.Write(b) + } + os.Stdout.Write(buf.Bytes()) + // Output: 0 1 2 3 +} + +func ExampleBuffer_Cap() { + buf1 := bytes.NewBuffer(make([]byte, 10)) + buf2 := bytes.NewBuffer(make([]byte, 0, 10)) + fmt.Println(buf1.Cap()) + fmt.Println(buf2.Cap()) + // Output: + // 10 + // 10 +} + +func ExampleBuffer_Grow() { + var b bytes.Buffer + b.Grow(64) + bb := b.Bytes() + b.Write([]byte("64 bytes or fewer")) + fmt.Printf("%q", bb[:b.Len()]) + // Output: "64 bytes or fewer" +} + +func ExampleBuffer_Len() { + var b bytes.Buffer + b.Grow(64) + b.Write([]byte("abcde")) + fmt.Printf("%d", b.Len()) + // Output: 5 +} + +func ExampleBuffer_Next() { + var b bytes.Buffer + b.Grow(64) + b.Write([]byte("abcde")) + fmt.Printf("%s\n", b.Next(2)) + fmt.Printf("%s\n", b.Next(2)) + fmt.Printf("%s", b.Next(2)) + // Output: + // ab + // cd + // e +} + +func ExampleBuffer_Read() { + var b bytes.Buffer + b.Grow(64) + b.Write([]byte("abcde")) + rdbuf := make([]byte, 1) + n, err := b.Read(rdbuf) + if err != nil { + panic(err) + } + fmt.Println(n) + fmt.Println(b.String()) + fmt.Println(string(rdbuf)) + // Output: + // 1 + // bcde + // a +} + +func ExampleBuffer_ReadByte() { + var b bytes.Buffer + b.Grow(64) + b.Write([]byte("abcde")) + c, err := b.ReadByte() + if err != nil { + panic(err) + } + fmt.Println(c) + fmt.Println(b.String()) + // Output: + // 97 + // bcde +} + +func ExampleClone() { + b := []byte("abc") + clone := bytes.Clone(b) + fmt.Printf("%s\n", clone) + clone[0] = 'd' + fmt.Printf("%s\n", b) + fmt.Printf("%s\n", clone) + // Output: + // abc + // abc + // dbc +} + +func ExampleCompare() { + // Interpret Compare's result by comparing it to zero. + var a, b []byte + if bytes.Compare(a, b) < 0 { + // a less b + } + if bytes.Compare(a, b) <= 0 { + // a less or equal b + } + if bytes.Compare(a, b) > 0 { + // a greater b + } + if bytes.Compare(a, b) >= 0 { + // a greater or equal b + } + + // Prefer Equal to Compare for equality comparisons. + if bytes.Equal(a, b) { + // a equal b + } + if !bytes.Equal(a, b) { + // a not equal b + } +} + +func ExampleCompare_search() { + // Binary search to find a matching byte slice. + var needle []byte + var haystack [][]byte // Assume sorted + _, found := slices.BinarySearchFunc(haystack, needle, bytes.Compare) + if found { + // Found it! + } +} + +func ExampleContains() { + fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo"))) + fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar"))) + fmt.Println(bytes.Contains([]byte("seafood"), []byte(""))) + fmt.Println(bytes.Contains([]byte(""), []byte(""))) + // Output: + // true + // false + // true + // true +} + +func ExampleContainsAny() { + fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!")) + fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的.")) + fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "")) + fmt.Println(bytes.ContainsAny([]byte(""), "")) + // Output: + // true + // true + // false + // false +} + +func ExampleContainsRune() { + fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f')) + fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö')) + fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大')) + fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!')) + fmt.Println(bytes.ContainsRune([]byte(""), '@')) + // Output: + // true + // false + // true + // true + // false +} + +func ExampleContainsFunc() { + f := func(r rune) bool { + return r >= 'a' && r <= 'z' + } + fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f)) + fmt.Println(bytes.ContainsFunc([]byte("World"), f)) + // Output: + // false + // true +} + +func ExampleCount() { + fmt.Println(bytes.Count([]byte("cheese"), []byte("e"))) + fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune + // Output: + // 3 + // 5 +} + +func ExampleCut() { + show := func(s, sep string) { + before, after, found := bytes.Cut([]byte(s), []byte(sep)) + fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found) + } + show("Gopher", "Go") + show("Gopher", "ph") + show("Gopher", "er") + show("Gopher", "Badger") + // Output: + // Cut("Gopher", "Go") = "", "pher", true + // Cut("Gopher", "ph") = "Go", "er", true + // Cut("Gopher", "er") = "Goph", "", true + // Cut("Gopher", "Badger") = "Gopher", "", false +} + +func ExampleCutPrefix() { + show := func(s, prefix string) { + after, found := bytes.CutPrefix([]byte(s), []byte(prefix)) + fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found) + } + show("Gopher", "Go") + show("Gopher", "ph") + // Output: + // CutPrefix("Gopher", "Go") = "pher", true + // CutPrefix("Gopher", "ph") = "Gopher", false +} + +func ExampleCutSuffix() { + show := func(s, suffix string) { + before, found := bytes.CutSuffix([]byte(s), []byte(suffix)) + fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found) + } + show("Gopher", "Go") + show("Gopher", "er") + // Output: + // CutSuffix("Gopher", "Go") = "Gopher", false + // CutSuffix("Gopher", "er") = "Goph", true +} + +func ExampleEqual() { + fmt.Println(bytes.Equal([]byte("Go"), []byte("Go"))) + fmt.Println(bytes.Equal([]byte("Go"), []byte("C++"))) + // Output: + // true + // false +} + +func ExampleEqualFold() { + fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go"))) + // Output: true +} + +func ExampleFields() { + fmt.Printf("Fields are: %q", bytes.Fields([]byte(" foo bar baz "))) + // Output: Fields are: ["foo" "bar" "baz"] +} + +func ExampleFieldsFunc() { + f := func(c rune) bool { + return !unicode.IsLetter(c) && !unicode.IsNumber(c) + } + fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte(" foo1;bar2,baz3..."), f)) + // Output: Fields are: ["foo1" "bar2" "baz3"] +} + +func ExampleHasPrefix() { + fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go"))) + fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C"))) + fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte(""))) + // Output: + // true + // false + // true +} + +func ExampleHasSuffix() { + fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go"))) + fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O"))) + fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami"))) + fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte(""))) + // Output: + // true + // false + // false + // true +} + +func ExampleIndex() { + fmt.Println(bytes.Index([]byte("chicken"), []byte("ken"))) + fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr"))) + // Output: + // 4 + // -1 +} + +func ExampleIndexByte() { + fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k'))) + fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g'))) + // Output: + // 4 + // -1 +} + +func ExampleIndexFunc() { + f := func(c rune) bool { + return unicode.Is(unicode.Han, c) + } + fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f)) + fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f)) + // Output: + // 7 + // -1 +} + +func ExampleIndexAny() { + fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy")) + fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy")) + // Output: + // 2 + // -1 +} + +func ExampleIndexRune() { + fmt.Println(bytes.IndexRune([]byte("chicken"), 'k')) + fmt.Println(bytes.IndexRune([]byte("chicken"), 'd')) + // Output: + // 4 + // -1 +} + +func ExampleJoin() { + s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")} + fmt.Printf("%s", bytes.Join(s, []byte(", "))) + // Output: foo, bar, baz +} + +func ExampleLastIndex() { + fmt.Println(bytes.Index([]byte("go gopher"), []byte("go"))) + fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go"))) + fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent"))) + // Output: + // 0 + // 3 + // -1 +} + +func ExampleLastIndexAny() { + fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp")) + fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大")) + fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!.")) + // Output: + // 5 + // 3 + // -1 +} + +func ExampleLastIndexByte() { + fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g'))) + fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r'))) + fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z'))) + // Output: + // 3 + // 8 + // -1 +} + +func ExampleLastIndexFunc() { + fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter)) + fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct)) + fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber)) + // Output: + // 8 + // 9 + // -1 +} + +func ExampleMap() { + rot13 := func(r rune) rune { + switch { + case r >= 'A' && r <= 'Z': + return 'A' + (r-'A'+13)%26 + case r >= 'a' && r <= 'z': + return 'a' + (r-'a'+13)%26 + } + return r + } + fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher..."))) + // Output: + // 'Gjnf oevyyvt naq gur fyvgul tbcure... +} + +func ExampleReader_Len() { + fmt.Println(bytes.NewReader([]byte("Hi!")).Len()) + fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len()) + // Output: + // 3 + // 16 +} + +func ExampleRepeat() { + fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2)) + // Output: banana +} + +func ExampleReplace() { + fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2)) + fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1)) + // Output: + // oinky oinky oink + // moo moo moo +} + +func ExampleReplaceAll() { + fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo"))) + // Output: + // moo moo moo +} + +func ExampleRunes() { + rs := bytes.Runes([]byte("go gopher")) + for _, r := range rs { + fmt.Printf("%#U\n", r) + } + // Output: + // U+0067 'g' + // U+006F 'o' + // U+0020 ' ' + // U+0067 'g' + // U+006F 'o' + // U+0070 'p' + // U+0068 'h' + // U+0065 'e' + // U+0072 'r' +} + +func ExampleSplit() { + fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(","))) + fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a "))) + fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte(""))) + fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins"))) + // Output: + // ["a" "b" "c"] + // ["" "man " "plan " "canal panama"] + // [" " "x" "y" "z" " "] + // [""] +} + +func ExampleSplitN() { + fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2)) + z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0) + fmt.Printf("%q (nil = %v)\n", z, z == nil) + // Output: + // ["a" "b,c"] + // [] (nil = true) +} + +func ExampleSplitAfter() { + fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(","))) + // Output: ["a," "b," "c"] +} + +func ExampleSplitAfterN() { + fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2)) + // Output: ["a," "b,c"] +} + +func ExampleTitle() { + fmt.Printf("%s", bytes.Title([]byte("her royal highness"))) + // Output: Her Royal Highness +} + +func ExampleToTitle() { + fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises"))) + fmt.Printf("%s\n", bytes.ToTitle([]byte("брат"))) + // Output: + // LOUD NOISES + // БРАТ +} + +func ExampleToTitleSpecial() { + str := []byte("ahoj vývojári golang") + totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str) + fmt.Println("Original : " + string(str)) + fmt.Println("ToTitle : " + string(totitle)) + // Output: + // Original : ahoj vývojári golang + // ToTitle : AHOJ VÝVOJÁRİ GOLANG +} + +func ExampleToValidUTF8() { + fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD"))) + fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte(""))) + fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc"))) + // Output: + // abc + // abc + // abc +} + +func ExampleTrim() { + fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! ")) + // Output: ["Achtung! Achtung"] +} + +func ExampleTrimFunc() { + fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter))) + fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter))) + fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct))) + fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber))) + // Output: + // -gopher! + // "go-gopher!" + // go-gopher + // go-gopher! +} + +func ExampleTrimLeft() { + fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789"))) + // Output: + // gopher8257 +} + +func ExampleTrimLeftFunc() { + fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter))) + fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct))) + fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber))) + // Output: + // -gopher + // go-gopher! + // go-gopher!567 +} + +func ExampleTrimPrefix() { + var b = []byte("Goodbye,, world!") + b = bytes.TrimPrefix(b, []byte("Goodbye,")) + b = bytes.TrimPrefix(b, []byte("See ya,")) + fmt.Printf("Hello%s", b) + // Output: Hello, world! +} + +func ExampleTrimSpace() { + fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n"))) + // Output: a lone gopher +} + +func ExampleTrimSuffix() { + var b = []byte("Hello, goodbye, etc!") + b = bytes.TrimSuffix(b, []byte("goodbye, etc!")) + b = bytes.TrimSuffix(b, []byte("gopher")) + b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...) + os.Stdout.Write(b) + // Output: Hello, world! +} + +func ExampleTrimRight() { + fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789"))) + // Output: + // 453gopher +} + +func ExampleTrimRightFunc() { + fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter))) + fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct))) + fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber))) + // Output: + // go- + // go-gopher + // 1234go-gopher! +} + +func ExampleToLower() { + fmt.Printf("%s", bytes.ToLower([]byte("Gopher"))) + // Output: gopher +} + +func ExampleToLowerSpecial() { + str := []byte("AHOJ VÝVOJÁRİ GOLANG") + totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str) + fmt.Println("Original : " + string(str)) + fmt.Println("ToLower : " + string(totitle)) + // Output: + // Original : AHOJ VÝVOJÁRİ GOLANG + // ToLower : ahoj vývojári golang +} + +func ExampleToUpper() { + fmt.Printf("%s", bytes.ToUpper([]byte("Gopher"))) + // Output: GOPHER +} + +func ExampleToUpperSpecial() { + str := []byte("ahoj vývojári golang") + totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str) + fmt.Println("Original : " + string(str)) + fmt.Println("ToUpper : " + string(totitle)) + // Output: + // Original : ahoj vývojári golang + // ToUpper : AHOJ VÝVOJÁRİ GOLANG +} + +func ExampleLines() { + text := []byte("Hello\nWorld\nGo Programming\n") + for line := range bytes.Lines(text) { + fmt.Printf("%q\n", line) + } + + // Output: + // "Hello\n" + // "World\n" + // "Go Programming\n" +} + +func ExampleSplitSeq() { + s := []byte("a,b,c,d") + for part := range bytes.SplitSeq(s, []byte(",")) { + fmt.Printf("%q\n", part) + } + + // Output: + // "a" + // "b" + // "c" + // "d" +} + +func ExampleSplitAfterSeq() { + s := []byte("a,b,c,d") + for part := range bytes.SplitAfterSeq(s, []byte(",")) { + fmt.Printf("%q\n", part) + } + + // Output: + // "a," + // "b," + // "c," + // "d" +} + +func ExampleFieldsSeq() { + text := []byte("The quick brown fox") + fmt.Println("Split byte slice into fields:") + for word := range bytes.FieldsSeq(text) { + fmt.Printf("%q\n", word) + } + + textWithSpaces := []byte(" lots of spaces ") + fmt.Println("\nSplit byte slice with multiple spaces:") + for word := range bytes.FieldsSeq(textWithSpaces) { + fmt.Printf("%q\n", word) + } + + // Output: + // Split byte slice into fields: + // "The" + // "quick" + // "brown" + // "fox" + // + // Split byte slice with multiple spaces: + // "lots" + // "of" + // "spaces" +} + +func ExampleFieldsFuncSeq() { + text := []byte("The quick brown fox") + fmt.Println("Split on whitespace(similar to FieldsSeq):") + for word := range bytes.FieldsFuncSeq(text, unicode.IsSpace) { + fmt.Printf("%q\n", word) + } + + mixedText := []byte("abc123def456ghi") + fmt.Println("\nSplit on digits:") + for word := range bytes.FieldsFuncSeq(mixedText, unicode.IsDigit) { + fmt.Printf("%q\n", word) + } + + // Output: + // Split on whitespace(similar to FieldsSeq): + // "The" + // "quick" + // "brown" + // "fox" + // + // Split on digits: + // "abc" + // "def" + // "ghi" +} diff --git a/go/src/bytes/export_test.go b/go/src/bytes/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b65428d9ce84894e05ecd063fa2a53b803a2c9f8 --- /dev/null +++ b/go/src/bytes/export_test.go @@ -0,0 +1,8 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes + +// Export func for testing +var IndexBytePortable = indexBytePortable diff --git a/go/src/bytes/iter.go b/go/src/bytes/iter.go new file mode 100644 index 0000000000000000000000000000000000000000..a4ece881d20fa1ed10490d1e43dbb9179899c013 --- /dev/null +++ b/go/src/bytes/iter.go @@ -0,0 +1,137 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes + +import ( + "iter" + "unicode" + "unicode/utf8" +) + +// Lines returns an iterator over the newline-terminated lines in the byte slice s. +// The lines yielded by the iterator include their terminating newlines. +// If s is empty, the iterator yields no lines at all. +// If s does not end in a newline, the final yielded line will not end in a newline. +// It returns a single-use iterator. +func Lines(s []byte) iter.Seq[[]byte] { + return func(yield func([]byte) bool) { + for len(s) > 0 { + var line []byte + if i := IndexByte(s, '\n'); i >= 0 { + line, s = s[:i+1], s[i+1:] + } else { + line, s = s, nil + } + if !yield(line[:len(line):len(line)]) { + return + } + } + } +} + +// splitSeq is SplitSeq or SplitAfterSeq, configured by how many +// bytes of sep to include in the results (none or all). +func splitSeq(s, sep []byte, sepSave int) iter.Seq[[]byte] { + return func(yield func([]byte) bool) { + if len(sep) == 0 { + for len(s) > 0 { + _, size := utf8.DecodeRune(s) + if !yield(s[:size:size]) { + return + } + s = s[size:] + } + return + } + for { + i := Index(s, sep) + if i < 0 { + break + } + frag := s[:i+sepSave] + if !yield(frag[:len(frag):len(frag)]) { + return + } + s = s[i+len(sep):] + } + yield(s[:len(s):len(s)]) + } +} + +// SplitSeq returns an iterator over all subslices of s separated by sep. +// The iterator yields the same subslices that would be returned by [Split](s, sep), +// but without constructing a new slice containing the subslices. +// It returns a single-use iterator. +func SplitSeq(s, sep []byte) iter.Seq[[]byte] { + return splitSeq(s, sep, 0) +} + +// SplitAfterSeq returns an iterator over subslices of s split after each instance of sep. +// The iterator yields the same subslices that would be returned by [SplitAfter](s, sep), +// but without constructing a new slice containing the subslices. +// It returns a single-use iterator. +func SplitAfterSeq(s, sep []byte) iter.Seq[[]byte] { + return splitSeq(s, sep, len(sep)) +} + +// FieldsSeq returns an iterator over subslices of s split around runs of +// whitespace characters, as defined by [unicode.IsSpace]. +// The iterator yields the same subslices that would be returned by [Fields](s), +// but without constructing a new slice containing the subslices. +func FieldsSeq(s []byte) iter.Seq[[]byte] { + return func(yield func([]byte) bool) { + start := -1 + for i := 0; i < len(s); { + size := 1 + r := rune(s[i]) + isSpace := asciiSpace[s[i]] != 0 + if r >= utf8.RuneSelf { + r, size = utf8.DecodeRune(s[i:]) + isSpace = unicode.IsSpace(r) + } + if isSpace { + if start >= 0 { + if !yield(s[start:i:i]) { + return + } + start = -1 + } + } else if start < 0 { + start = i + } + i += size + } + if start >= 0 { + yield(s[start:len(s):len(s)]) + } + } +} + +// FieldsFuncSeq returns an iterator over subslices of s split around runs of +// Unicode code points satisfying f(c). +// The iterator yields the same subslices that would be returned by [FieldsFunc](s), +// but without constructing a new slice containing the subslices. +func FieldsFuncSeq(s []byte, f func(rune) bool) iter.Seq[[]byte] { + return func(yield func([]byte) bool) { + start := -1 + for i := 0; i < len(s); { + r, size := utf8.DecodeRune(s[i:]) + if f(r) { + if start >= 0 { + if !yield(s[start:i:i]) { + return + } + start = -1 + } + } else if start < 0 { + start = i + } + i += size + } + if start >= 0 { + yield(s[start:len(s):len(s)]) + } + } +} diff --git a/go/src/bytes/iter_test.go b/go/src/bytes/iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e37fdfb96d1b615a481920318e33cd76fd10b089 --- /dev/null +++ b/go/src/bytes/iter_test.go @@ -0,0 +1,56 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes_test + +import ( + . "bytes" + "testing" +) + +func BenchmarkSplitSeqEmptySeparator(b *testing.B) { + for range b.N { + for range SplitSeq(benchInputHard, nil) { + } + } +} + +func BenchmarkSplitSeqSingleByteSeparator(b *testing.B) { + sep := []byte("/") + for range b.N { + for range SplitSeq(benchInputHard, sep) { + } + } +} + +func BenchmarkSplitSeqMultiByteSeparator(b *testing.B) { + sep := []byte("hello") + for range b.N { + for range SplitSeq(benchInputHard, sep) { + } + } +} + +func BenchmarkSplitAfterSeqEmptySeparator(b *testing.B) { + for range b.N { + for range SplitAfterSeq(benchInputHard, nil) { + } + } +} + +func BenchmarkSplitAfterSeqSingleByteSeparator(b *testing.B) { + sep := []byte("/") + for range b.N { + for range SplitAfterSeq(benchInputHard, sep) { + } + } +} + +func BenchmarkSplitAfterSeqMultiByteSeparator(b *testing.B) { + sep := []byte("hello") + for range b.N { + for range SplitAfterSeq(benchInputHard, sep) { + } + } +} diff --git a/go/src/bytes/reader.go b/go/src/bytes/reader.go new file mode 100644 index 0000000000000000000000000000000000000000..d4c3066e0620d058c5648b72bf8322cb6b169594 --- /dev/null +++ b/go/src/bytes/reader.go @@ -0,0 +1,159 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes + +import ( + "errors" + "io" + "unicode/utf8" +) + +// A Reader implements the [io.Reader], [io.ReaderAt], [io.WriterTo], [io.Seeker], +// [io.ByteScanner], and [io.RuneScanner] interfaces by reading from +// a byte slice. +// Unlike a [Buffer], a Reader is read-only and supports seeking. +// The zero value for Reader operates like a Reader of an empty slice. +type Reader struct { + s []byte + i int64 // current reading index + prevRune int // index of previous rune; or < 0 +} + +// Len returns the number of bytes of the unread portion of the +// slice. +func (r *Reader) Len() int { + if r.i >= int64(len(r.s)) { + return 0 + } + return int(int64(len(r.s)) - r.i) +} + +// Size returns the original length of the underlying byte slice. +// Size is the number of bytes available for reading via [Reader.ReadAt]. +// The result is unaffected by any method calls except [Reader.Reset]. +func (r *Reader) Size() int64 { return int64(len(r.s)) } + +// Read implements the [io.Reader] interface. +func (r *Reader) Read(b []byte) (n int, err error) { + if r.i >= int64(len(r.s)) { + return 0, io.EOF + } + r.prevRune = -1 + n = copy(b, r.s[r.i:]) + r.i += int64(n) + return +} + +// ReadAt implements the [io.ReaderAt] interface. +func (r *Reader) ReadAt(b []byte, off int64) (n int, err error) { + // cannot modify state - see io.ReaderAt + if off < 0 { + return 0, errors.New("bytes.Reader.ReadAt: negative offset") + } + if off >= int64(len(r.s)) { + return 0, io.EOF + } + n = copy(b, r.s[off:]) + if n < len(b) { + err = io.EOF + } + return +} + +// ReadByte implements the [io.ByteReader] interface. +func (r *Reader) ReadByte() (byte, error) { + r.prevRune = -1 + if r.i >= int64(len(r.s)) { + return 0, io.EOF + } + b := r.s[r.i] + r.i++ + return b, nil +} + +// UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface. +func (r *Reader) UnreadByte() error { + if r.i <= 0 { + return errors.New("bytes.Reader.UnreadByte: at beginning of slice") + } + r.prevRune = -1 + r.i-- + return nil +} + +// ReadRune implements the [io.RuneReader] interface. +func (r *Reader) ReadRune() (ch rune, size int, err error) { + if r.i >= int64(len(r.s)) { + r.prevRune = -1 + return 0, 0, io.EOF + } + r.prevRune = int(r.i) + if c := r.s[r.i]; c < utf8.RuneSelf { + r.i++ + return rune(c), 1, nil + } + ch, size = utf8.DecodeRune(r.s[r.i:]) + r.i += int64(size) + return +} + +// UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface. +func (r *Reader) UnreadRune() error { + if r.i <= 0 { + return errors.New("bytes.Reader.UnreadRune: at beginning of slice") + } + if r.prevRune < 0 { + return errors.New("bytes.Reader.UnreadRune: previous operation was not ReadRune") + } + r.i = int64(r.prevRune) + r.prevRune = -1 + return nil +} + +// Seek implements the [io.Seeker] interface. +func (r *Reader) Seek(offset int64, whence int) (int64, error) { + r.prevRune = -1 + var abs int64 + switch whence { + case io.SeekStart: + abs = offset + case io.SeekCurrent: + abs = r.i + offset + case io.SeekEnd: + abs = int64(len(r.s)) + offset + default: + return 0, errors.New("bytes.Reader.Seek: invalid whence") + } + if abs < 0 { + return 0, errors.New("bytes.Reader.Seek: negative position") + } + r.i = abs + return abs, nil +} + +// WriteTo implements the [io.WriterTo] interface. +func (r *Reader) WriteTo(w io.Writer) (n int64, err error) { + r.prevRune = -1 + if r.i >= int64(len(r.s)) { + return 0, nil + } + b := r.s[r.i:] + m, err := w.Write(b) + if m > len(b) { + panic("bytes.Reader.WriteTo: invalid Write count") + } + r.i += int64(m) + n = int64(m) + if m != len(b) && err == nil { + err = io.ErrShortWrite + } + return +} + +// Reset resets the [Reader] to be reading from b. +func (r *Reader) Reset(b []byte) { *r = Reader{b, 0, -1} } + +// NewReader returns a new [Reader] reading from b. +func NewReader(b []byte) *Reader { return &Reader{b, 0, -1} } diff --git a/go/src/bytes/reader_test.go b/go/src/bytes/reader_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9119c944ace4783ebb9fb3295beb7be23336e009 --- /dev/null +++ b/go/src/bytes/reader_test.go @@ -0,0 +1,319 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bytes_test + +import ( + . "bytes" + "fmt" + "io" + "sync" + "testing" +) + +func TestReader(t *testing.T) { + r := NewReader([]byte("0123456789")) + tests := []struct { + off int64 + seek int + n int + want string + wantpos int64 + readerr error + seekerr string + }{ + {seek: io.SeekStart, off: 0, n: 20, want: "0123456789"}, + {seek: io.SeekStart, off: 1, n: 1, want: "1"}, + {seek: io.SeekCurrent, off: 1, wantpos: 3, n: 2, want: "34"}, + {seek: io.SeekStart, off: -1, seekerr: "bytes.Reader.Seek: negative position"}, + {seek: io.SeekStart, off: 1 << 33, wantpos: 1 << 33, readerr: io.EOF}, + {seek: io.SeekCurrent, off: 1, wantpos: 1<<33 + 1, readerr: io.EOF}, + {seek: io.SeekStart, n: 5, want: "01234"}, + {seek: io.SeekCurrent, n: 5, want: "56789"}, + {seek: io.SeekEnd, off: -1, n: 1, wantpos: 9, want: "9"}, + } + + for i, tt := range tests { + pos, err := r.Seek(tt.off, tt.seek) + if err == nil && tt.seekerr != "" { + t.Errorf("%d. want seek error %q", i, tt.seekerr) + continue + } + if err != nil && err.Error() != tt.seekerr { + t.Errorf("%d. seek error = %q; want %q", i, err.Error(), tt.seekerr) + continue + } + if tt.wantpos != 0 && tt.wantpos != pos { + t.Errorf("%d. pos = %d, want %d", i, pos, tt.wantpos) + } + buf := make([]byte, tt.n) + n, err := r.Read(buf) + if err != tt.readerr { + t.Errorf("%d. read = %v; want %v", i, err, tt.readerr) + continue + } + got := string(buf[:n]) + if got != tt.want { + t.Errorf("%d. got %q; want %q", i, got, tt.want) + } + } +} + +func TestReadAfterBigSeek(t *testing.T) { + r := NewReader([]byte("0123456789")) + if _, err := r.Seek(1<<31+5, io.SeekStart); err != nil { + t.Fatal(err) + } + if n, err := r.Read(make([]byte, 10)); n != 0 || err != io.EOF { + t.Errorf("Read = %d, %v; want 0, EOF", n, err) + } +} + +func TestReaderAt(t *testing.T) { + r := NewReader([]byte("0123456789")) + tests := []struct { + off int64 + n int + want string + wanterr any + }{ + {0, 10, "0123456789", nil}, + {1, 10, "123456789", io.EOF}, + {1, 9, "123456789", nil}, + {11, 10, "", io.EOF}, + {0, 0, "", nil}, + {-1, 0, "", "bytes.Reader.ReadAt: negative offset"}, + } + for i, tt := range tests { + b := make([]byte, tt.n) + rn, err := r.ReadAt(b, tt.off) + got := string(b[:rn]) + if got != tt.want { + t.Errorf("%d. got %q; want %q", i, got, tt.want) + } + if fmt.Sprintf("%v", err) != fmt.Sprintf("%v", tt.wanterr) { + t.Errorf("%d. got error = %v; want %v", i, err, tt.wanterr) + } + } +} + +func TestReaderAtConcurrent(t *testing.T) { + // Test for the race detector, to verify ReadAt doesn't mutate + // any state. + r := NewReader([]byte("0123456789")) + var wg sync.WaitGroup + for i := 0; i < 5; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + var buf [1]byte + r.ReadAt(buf[:], int64(i)) + }(i) + } + wg.Wait() +} + +func TestEmptyReaderConcurrent(t *testing.T) { + // Test for the race detector, to verify a Read that doesn't yield any bytes + // is okay to use from multiple goroutines. This was our historic behavior. + // See golang.org/issue/7856 + r := NewReader([]byte{}) + var wg sync.WaitGroup + for i := 0; i < 5; i++ { + wg.Add(2) + go func() { + defer wg.Done() + var buf [1]byte + r.Read(buf[:]) + }() + go func() { + defer wg.Done() + r.Read(nil) + }() + } + wg.Wait() +} + +func TestReaderWriteTo(t *testing.T) { + for i := 0; i < 30; i += 3 { + var l int + if i > 0 { + l = len(testString) / i + } + s := testString[:l] + r := NewReader(testBytes[:l]) + var b Buffer + n, err := r.WriteTo(&b) + if expect := int64(len(s)); n != expect { + t.Errorf("got %v; want %v", n, expect) + } + if err != nil { + t.Errorf("for length %d: got error = %v; want nil", l, err) + } + if b.String() != s { + t.Errorf("got string %q; want %q", b.String(), s) + } + if r.Len() != 0 { + t.Errorf("reader contains %v bytes; want 0", r.Len()) + } + } +} + +func TestReaderLen(t *testing.T) { + const data = "hello world" + r := NewReader([]byte(data)) + if got, want := r.Len(), 11; got != want { + t.Errorf("r.Len(): got %d, want %d", got, want) + } + if n, err := r.Read(make([]byte, 10)); err != nil || n != 10 { + t.Errorf("Read failed: read %d %v", n, err) + } + if got, want := r.Len(), 1; got != want { + t.Errorf("r.Len(): got %d, want %d", got, want) + } + if n, err := r.Read(make([]byte, 1)); err != nil || n != 1 { + t.Errorf("Read failed: read %d %v; want 1, nil", n, err) + } + if got, want := r.Len(), 0; got != want { + t.Errorf("r.Len(): got %d, want %d", got, want) + } +} + +var UnreadRuneErrorTests = []struct { + name string + f func(*Reader) +}{ + {"Read", func(r *Reader) { r.Read([]byte{0}) }}, + {"ReadByte", func(r *Reader) { r.ReadByte() }}, + {"UnreadRune", func(r *Reader) { r.UnreadRune() }}, + {"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }}, + {"WriteTo", func(r *Reader) { r.WriteTo(&Buffer{}) }}, +} + +func TestUnreadRuneError(t *testing.T) { + for _, tt := range UnreadRuneErrorTests { + reader := NewReader([]byte("0123456789")) + if _, _, err := reader.ReadRune(); err != nil { + // should not happen + t.Fatal(err) + } + tt.f(reader) + err := reader.UnreadRune() + if err == nil { + t.Errorf("Unreading after %s: expected error", tt.name) + } + } +} + +func TestReaderDoubleUnreadRune(t *testing.T) { + buf := NewBuffer([]byte("groucho")) + if _, _, err := buf.ReadRune(); err != nil { + // should not happen + t.Fatal(err) + } + if err := buf.UnreadByte(); err != nil { + // should not happen + t.Fatal(err) + } + if err := buf.UnreadByte(); err == nil { + t.Fatal("UnreadByte: expected error, got nil") + } +} + +// verify that copying from an empty reader always has the same results, +// regardless of the presence of a WriteTo method. +func TestReaderCopyNothing(t *testing.T) { + type nErr struct { + n int64 + err error + } + type justReader struct { + io.Reader + } + type justWriter struct { + io.Writer + } + discard := justWriter{io.Discard} // hide ReadFrom + + var with, withOut nErr + with.n, with.err = io.Copy(discard, NewReader(nil)) + withOut.n, withOut.err = io.Copy(discard, justReader{NewReader(nil)}) + if with != withOut { + t.Errorf("behavior differs: with = %#v; without: %#v", with, withOut) + } +} + +// tests that Len is affected by reads, but Size is not. +func TestReaderLenSize(t *testing.T) { + r := NewReader([]byte("abc")) + io.CopyN(io.Discard, r, 1) + if r.Len() != 2 { + t.Errorf("Len = %d; want 2", r.Len()) + } + if r.Size() != 3 { + t.Errorf("Size = %d; want 3", r.Size()) + } +} + +func TestReaderReset(t *testing.T) { + r := NewReader([]byte("世界")) + if _, _, err := r.ReadRune(); err != nil { + t.Errorf("ReadRune: unexpected error: %v", err) + } + + const want = "abcdef" + r.Reset([]byte(want)) + if err := r.UnreadRune(); err == nil { + t.Errorf("UnreadRune: expected error, got nil") + } + buf, err := io.ReadAll(r) + if err != nil { + t.Errorf("ReadAll: unexpected error: %v", err) + } + if got := string(buf); got != want { + t.Errorf("ReadAll: got %q, want %q", got, want) + } +} + +func TestReaderZero(t *testing.T) { + if l := (&Reader{}).Len(); l != 0 { + t.Errorf("Len: got %d, want 0", l) + } + + if n, err := (&Reader{}).Read(nil); n != 0 || err != io.EOF { + t.Errorf("Read: got %d, %v; want 0, io.EOF", n, err) + } + + if n, err := (&Reader{}).ReadAt(nil, 11); n != 0 || err != io.EOF { + t.Errorf("ReadAt: got %d, %v; want 0, io.EOF", n, err) + } + + if b, err := (&Reader{}).ReadByte(); b != 0 || err != io.EOF { + t.Errorf("ReadByte: got %d, %v; want 0, io.EOF", b, err) + } + + if ch, size, err := (&Reader{}).ReadRune(); ch != 0 || size != 0 || err != io.EOF { + t.Errorf("ReadRune: got %d, %d, %v; want 0, 0, io.EOF", ch, size, err) + } + + if offset, err := (&Reader{}).Seek(11, io.SeekStart); offset != 11 || err != nil { + t.Errorf("Seek: got %d, %v; want 11, nil", offset, err) + } + + if s := (&Reader{}).Size(); s != 0 { + t.Errorf("Size: got %d, want 0", s) + } + + if (&Reader{}).UnreadByte() == nil { + t.Errorf("UnreadByte: got nil, want error") + } + + if (&Reader{}).UnreadRune() == nil { + t.Errorf("UnreadRune: got nil, want error") + } + + if n, err := (&Reader{}).WriteTo(io.Discard); n != 0 || err != nil { + t.Errorf("WriteTo: got %d, %v; want 0, nil", n, err) + } +} diff --git a/go/src/cmd/README.vendor b/go/src/cmd/README.vendor new file mode 100644 index 0000000000000000000000000000000000000000..ac0df5e9257124ba06492f523eeed3706041fa1c --- /dev/null +++ b/go/src/cmd/README.vendor @@ -0,0 +1,2 @@ +See src/README.vendor for information on loading vendored packages +and updating the vendor directory. diff --git a/go/src/cmd/go.mod b/go/src/cmd/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..14107c2d8ed9f306480bdfaf63ac45cd2349ab7d --- /dev/null +++ b/go/src/cmd/go.mod @@ -0,0 +1,21 @@ +module cmd + +go 1.26 + +require ( + github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8 + golang.org/x/arch v0.23.0 + golang.org/x/build v0.0.0-20251128064159-b9bfd88b30e8 + golang.org/x/mod v0.30.1-0.20251115032019-269c237cf350 + golang.org/x/sync v0.19.0 + golang.org/x/sys v0.39.0 + golang.org/x/telemetry v0.0.0-20251128220624-abf20d0e57ec + golang.org/x/term v0.38.0 + golang.org/x/tools v0.39.1-0.20260323181443-4f499ecaa91d +) + +require ( + github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b // indirect + golang.org/x/text v0.32.0 // indirect + rsc.io/markdown v0.0.0-20240306144322-0bf8f97ee8ef // indirect +) diff --git a/go/src/cmd/go.sum b/go/src/cmd/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..c4920417b21b3ddad34b7f663e997680c578315f --- /dev/null +++ b/go/src/cmd/go.sum @@ -0,0 +1,28 @@ +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8 h1:3DsUAV+VNEQa2CUVLxCY3f87278uWfIDhJnbdvDjvmE= +github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U= +github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b h1:ogbOPx86mIhFy764gGkqnkFC8m5PJA7sPzlk9ppLVQA= +github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= +github.com/yuin/goldmark v1.6.0 h1:boZcn2GTjpsynOsC0iJHnBWa4Bi0qzfJjthwauItG68= +github.com/yuin/goldmark v1.6.0/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg= +golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/build v0.0.0-20251128064159-b9bfd88b30e8 h1:Mp+uRtHbKFW85lGBTOkOOfkPBz7AUKmZGcflkavmGRM= +golang.org/x/build v0.0.0-20251128064159-b9bfd88b30e8/go.mod h1:Jx2RBBeTWGRSCwfSZ+w2Hg1f7LjWycsSkx+EciLAmPE= +golang.org/x/mod v0.30.1-0.20251115032019-269c237cf350 h1:JGDMsCp8NahDR9HSvwrF6V8tzEf87m7Bo4oZ07vRxdU= +golang.org/x/mod v0.30.1-0.20251115032019-269c237cf350/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/telemetry v0.0.0-20251128220624-abf20d0e57ec h1:dRVkWZl6bUOp+oxnOe4BuyhWSIPmt29N4ooHarm7Ic8= +golang.org/x/telemetry v0.0.0-20251128220624-abf20d0e57ec/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ= +golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= +golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/tools v0.39.1-0.20260323181443-4f499ecaa91d h1:d9RYG/Z8xQk+tFy5IyhSwUrt4HhSsqHw/uhwmn1KaJg= +golang.org/x/tools v0.39.1-0.20260323181443-4f499ecaa91d/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +rsc.io/markdown v0.0.0-20240306144322-0bf8f97ee8ef h1:mqLYrXCXYEZOop9/Dbo6RPX11539nwiCNBb1icVPmw8= +rsc.io/markdown v0.0.0-20240306144322-0bf8f97ee8ef/go.mod h1:8xcPgWmwlZONN1D9bjxtHEjrUtSEa3fakVF8iaewYKQ= diff --git a/go/src/cmp/cmp.go b/go/src/cmp/cmp.go new file mode 100644 index 0000000000000000000000000000000000000000..a13834c39858924ba9f1b4b57051124b8f3dc8bb --- /dev/null +++ b/go/src/cmp/cmp.go @@ -0,0 +1,77 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package cmp provides types and functions related to comparing +// ordered values. +package cmp + +// Ordered is a constraint that permits any ordered type: any type +// that supports the operators < <= >= >. +// If future releases of Go add new ordered types, +// this constraint will be modified to include them. +// +// Note that floating-point types may contain NaN ("not-a-number") values. +// An operator such as == or < will always report false when +// comparing a NaN value with any other value, NaN or not. +// See the [Compare] function for a consistent way to compare NaN values. +type Ordered interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 | + ~string +} + +// Less reports whether x is less than y. +// For floating-point types, a NaN is considered less than any non-NaN, +// and -0.0 is not less than (is equal to) 0.0. +func Less[T Ordered](x, y T) bool { + return (isNaN(x) && !isNaN(y)) || x < y +} + +// Compare returns +// +// -1 if x is less than y, +// 0 if x equals y, +// +1 if x is greater than y. +// +// For floating-point types, a NaN is considered less than any non-NaN, +// a NaN is considered equal to a NaN, and -0.0 is equal to 0.0. +func Compare[T Ordered](x, y T) int { + xNaN := isNaN(x) + yNaN := isNaN(y) + if xNaN { + if yNaN { + return 0 + } + return -1 + } + if yNaN { + return +1 + } + if x < y { + return -1 + } + if x > y { + return +1 + } + return 0 +} + +// isNaN reports whether x is a NaN without requiring the math package. +// This will always return false if T is not floating-point. +func isNaN[T Ordered](x T) bool { + return x != x +} + +// Or returns the first of its arguments that is not equal to the zero value. +// If no argument is non-zero, it returns the zero value. +func Or[T comparable](vals ...T) T { + var zero T + for _, val := range vals { + if val != zero { + return val + } + } + return zero +} diff --git a/go/src/cmp/cmp_test.go b/go/src/cmp/cmp_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c9816cba11665739ed079de1d07570af01df0e9f --- /dev/null +++ b/go/src/cmp/cmp_test.go @@ -0,0 +1,202 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp_test + +import ( + "cmp" + "fmt" + "math" + "slices" + "sort" + "strings" + "testing" + "unsafe" +) + +var negzero = math.Copysign(0, -1) +var nonnilptr uintptr = uintptr(unsafe.Pointer(&negzero)) +var nilptr uintptr = uintptr(unsafe.Pointer(nil)) + +var tests = []struct { + x, y any + compare int +}{ + {1, 2, -1}, + {1, 1, 0}, + {2, 1, +1}, + {"a", "aa", -1}, + {"a", "a", 0}, + {"aa", "a", +1}, + {1.0, 1.1, -1}, + {1.1, 1.1, 0}, + {1.1, 1.0, +1}, + {math.Inf(1), math.Inf(1), 0}, + {math.Inf(-1), math.Inf(-1), 0}, + {math.Inf(-1), 1.0, -1}, + {1.0, math.Inf(-1), +1}, + {math.Inf(1), 1.0, +1}, + {1.0, math.Inf(1), -1}, + {math.NaN(), math.NaN(), 0}, + {0.0, math.NaN(), +1}, + {math.NaN(), 0.0, -1}, + {math.NaN(), math.Inf(-1), -1}, + {math.Inf(-1), math.NaN(), +1}, + {0.0, 0.0, 0}, + {negzero, negzero, 0}, + {negzero, 0.0, 0}, + {0.0, negzero, 0}, + {negzero, 1.0, -1}, + {negzero, -1.0, +1}, + {nilptr, nonnilptr, -1}, + {nonnilptr, nilptr, 1}, + {nonnilptr, nonnilptr, 0}, +} + +func TestLess(t *testing.T) { + for _, test := range tests { + var b bool + switch test.x.(type) { + case int: + b = cmp.Less(test.x.(int), test.y.(int)) + case string: + b = cmp.Less(test.x.(string), test.y.(string)) + case float64: + b = cmp.Less(test.x.(float64), test.y.(float64)) + case uintptr: + b = cmp.Less(test.x.(uintptr), test.y.(uintptr)) + } + if b != (test.compare < 0) { + t.Errorf("Less(%v, %v) == %t, want %t", test.x, test.y, b, test.compare < 0) + } + } +} + +func TestCompare(t *testing.T) { + for _, test := range tests { + var c int + switch test.x.(type) { + case int: + c = cmp.Compare(test.x.(int), test.y.(int)) + case string: + c = cmp.Compare(test.x.(string), test.y.(string)) + case float64: + c = cmp.Compare(test.x.(float64), test.y.(float64)) + case uintptr: + c = cmp.Compare(test.x.(uintptr), test.y.(uintptr)) + } + if c != test.compare { + t.Errorf("Compare(%v, %v) == %d, want %d", test.x, test.y, c, test.compare) + } + } +} + +func TestSort(t *testing.T) { + // Test that our comparison function is consistent with + // sort.Float64s. + input := []float64{1.0, 0.0, negzero, math.Inf(1), math.Inf(-1), math.NaN()} + sort.Float64s(input) + for i := 0; i < len(input)-1; i++ { + if cmp.Less(input[i+1], input[i]) { + t.Errorf("Less sort mismatch at %d in %v", i, input) + } + if cmp.Compare(input[i], input[i+1]) > 0 { + t.Errorf("Compare sort mismatch at %d in %v", i, input) + } + } +} + +func TestOr(t *testing.T) { + cases := []struct { + in []int + want int + }{ + {nil, 0}, + {[]int{0}, 0}, + {[]int{1}, 1}, + {[]int{0, 2}, 2}, + {[]int{3, 0}, 3}, + {[]int{4, 5}, 4}, + {[]int{0, 6, 7}, 6}, + } + for _, tc := range cases { + if got := cmp.Or(tc.in...); got != tc.want { + t.Errorf("cmp.Or(%v) = %v; want %v", tc.in, got, tc.want) + } + } +} + +func ExampleOr() { + // Suppose we have some user input + // that may or may not be an empty string + userInput1 := "" + userInput2 := "some text" + + fmt.Println(cmp.Or(userInput1, "default")) + fmt.Println(cmp.Or(userInput2, "default")) + fmt.Println(cmp.Or(userInput1, userInput2, "default")) + // Output: + // default + // some text + // some text +} + +func ExampleOr_sort() { + type Order struct { + Product string + Customer string + Price float64 + } + orders := []Order{ + {"foo", "alice", 1.00}, + {"bar", "bob", 3.00}, + {"baz", "carol", 4.00}, + {"foo", "alice", 2.00}, + {"bar", "carol", 1.00}, + {"foo", "bob", 4.00}, + } + // Sort by customer first, product second, and last by higher price + slices.SortFunc(orders, func(a, b Order) int { + return cmp.Or( + strings.Compare(a.Customer, b.Customer), + strings.Compare(a.Product, b.Product), + cmp.Compare(b.Price, a.Price), + ) + }) + for _, order := range orders { + fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price) + } + + // Output: + // foo alice 2.00 + // foo alice 1.00 + // bar bob 3.00 + // foo bob 4.00 + // bar carol 1.00 + // baz carol 4.00 +} + +func ExampleLess() { + fmt.Println(cmp.Less(1, 2)) + fmt.Println(cmp.Less("a", "aa")) + fmt.Println(cmp.Less(1.0, math.NaN())) + fmt.Println(cmp.Less(math.NaN(), 1.0)) + // Output: + // true + // true + // false + // true +} + +func ExampleCompare() { + fmt.Println(cmp.Compare(1, 2)) + fmt.Println(cmp.Compare("a", "aa")) + fmt.Println(cmp.Compare(1.5, 1.5)) + fmt.Println(cmp.Compare(math.NaN(), 1.0)) + // Output: + // -1 + // -1 + // 0 + // -1 +} diff --git a/go/src/context/afterfunc_test.go b/go/src/context/afterfunc_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c2ef1062d3851fd055f27009bd1eb613d049619a --- /dev/null +++ b/go/src/context/afterfunc_test.go @@ -0,0 +1,141 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context_test + +import ( + "context" + "sync" + "testing" + "time" +) + +// afterFuncContext is a context that's not one of the types +// defined in context.go, that supports registering AfterFuncs. +type afterFuncContext struct { + mu sync.Mutex + afterFuncs map[*byte]func() + done chan struct{} + err error +} + +var _ context.Context = (*afterFuncContext)(nil) + +func (c *afterFuncContext) Deadline() (time.Time, bool) { + return time.Time{}, false +} + +func (c *afterFuncContext) Done() <-chan struct{} { + c.mu.Lock() + defer c.mu.Unlock() + if c.done == nil { + c.done = make(chan struct{}) + } + return c.done +} + +func (c *afterFuncContext) Err() error { + c.mu.Lock() + defer c.mu.Unlock() + return c.err +} + +func (c *afterFuncContext) Value(key any) any { + return nil +} + +func (c *afterFuncContext) AfterFunc(f func()) func() bool { + c.mu.Lock() + defer c.mu.Unlock() + k := new(byte) + if c.afterFuncs == nil { + c.afterFuncs = make(map[*byte]func()) + } + c.afterFuncs[k] = f + return func() bool { + c.mu.Lock() + defer c.mu.Unlock() + _, ok := c.afterFuncs[k] + delete(c.afterFuncs, k) + return ok + } +} + +func (c *afterFuncContext) cancel(err error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.err != nil { + return + } + c.err = err + for _, f := range c.afterFuncs { + go f() + } + c.afterFuncs = nil +} + +func TestCustomContextAfterFuncCancel(t *testing.T) { + ctx0 := &afterFuncContext{} + ctx1, cancel := context.WithCancel(ctx0) + defer cancel() + ctx0.cancel(context.Canceled) + <-ctx1.Done() +} + +func TestCustomContextAfterFuncTimeout(t *testing.T) { + ctx0 := &afterFuncContext{} + ctx1, cancel := context.WithTimeout(ctx0, veryLongDuration) + defer cancel() + ctx0.cancel(context.Canceled) + <-ctx1.Done() +} + +func TestCustomContextAfterFuncAfterFunc(t *testing.T) { + ctx0 := &afterFuncContext{} + donec := make(chan struct{}) + stop := context.AfterFunc(ctx0, func() { + close(donec) + }) + defer stop() + ctx0.cancel(context.Canceled) + <-donec +} + +func TestCustomContextAfterFuncUnregisterCancel(t *testing.T) { + ctx0 := &afterFuncContext{} + _, cancel1 := context.WithCancel(ctx0) + _, cancel2 := context.WithCancel(ctx0) + if got, want := len(ctx0.afterFuncs), 2; got != want { + t.Errorf("after WithCancel(ctx0): ctx0 has %v afterFuncs, want %v", got, want) + } + cancel1() + cancel2() + if got, want := len(ctx0.afterFuncs), 0; got != want { + t.Errorf("after canceling WithCancel(ctx0): ctx0 has %v afterFuncs, want %v", got, want) + } +} + +func TestCustomContextAfterFuncUnregisterTimeout(t *testing.T) { + ctx0 := &afterFuncContext{} + _, cancel := context.WithTimeout(ctx0, veryLongDuration) + if got, want := len(ctx0.afterFuncs), 1; got != want { + t.Errorf("after WithTimeout(ctx0, d): ctx0 has %v afterFuncs, want %v", got, want) + } + cancel() + if got, want := len(ctx0.afterFuncs), 0; got != want { + t.Errorf("after canceling WithTimeout(ctx0, d): ctx0 has %v afterFuncs, want %v", got, want) + } +} + +func TestCustomContextAfterFuncUnregisterAfterFunc(t *testing.T) { + ctx0 := &afterFuncContext{} + stop := context.AfterFunc(ctx0, func() {}) + if got, want := len(ctx0.afterFuncs), 1; got != want { + t.Errorf("after AfterFunc(ctx0, f): ctx0 has %v afterFuncs, want %v", got, want) + } + stop() + if got, want := len(ctx0.afterFuncs), 0; got != want { + t.Errorf("after stopping AfterFunc(ctx0, f): ctx0 has %v afterFuncs, want %v", got, want) + } +} diff --git a/go/src/context/benchmark_test.go b/go/src/context/benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d10950d258970f203bc2aec8def4096fca89fdbf --- /dev/null +++ b/go/src/context/benchmark_test.go @@ -0,0 +1,210 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context_test + +import ( + . "context" + "fmt" + "runtime" + "sync" + "testing" + "time" +) + +func BenchmarkCommonParentCancel(b *testing.B) { + root := WithValue(Background(), "key", "value") + shared, sharedcancel := WithCancel(root) + defer sharedcancel() + + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + x := 0 + for pb.Next() { + ctx, cancel := WithCancel(shared) + if ctx.Value("key").(string) != "value" { + b.Fatal("should not be reached") + } + for i := 0; i < 100; i++ { + x /= x + 1 + } + cancel() + for i := 0; i < 100; i++ { + x /= x + 1 + } + } + }) +} + +func BenchmarkWithTimeout(b *testing.B) { + for concurrency := 40; concurrency <= 4e5; concurrency *= 100 { + name := fmt.Sprintf("concurrency=%d", concurrency) + b.Run(name, func(b *testing.B) { + benchmarkWithTimeout(b, concurrency) + }) + } +} + +func benchmarkWithTimeout(b *testing.B, concurrentContexts int) { + gomaxprocs := runtime.GOMAXPROCS(0) + perPContexts := concurrentContexts / gomaxprocs + root := Background() + + // Generate concurrent contexts. + var wg sync.WaitGroup + ccf := make([][]CancelFunc, gomaxprocs) + for i := range ccf { + wg.Add(1) + go func(i int) { + defer wg.Done() + cf := make([]CancelFunc, perPContexts) + for j := range cf { + _, cf[j] = WithTimeout(root, time.Hour) + } + ccf[i] = cf + }(i) + } + wg.Wait() + + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + wcf := make([]CancelFunc, 10) + for pb.Next() { + for i := range wcf { + _, wcf[i] = WithTimeout(root, time.Hour) + } + for _, f := range wcf { + f() + } + } + }) + b.StopTimer() + + for _, cf := range ccf { + for _, f := range cf { + f() + } + } +} + +func BenchmarkCancelTree(b *testing.B) { + depths := []int{1, 10, 100, 1000} + for _, d := range depths { + b.Run(fmt.Sprintf("depth=%d", d), func(b *testing.B) { + b.Run("Root=Background", func(b *testing.B) { + for i := 0; i < b.N; i++ { + buildContextTree(Background(), d) + } + }) + b.Run("Root=OpenCanceler", func(b *testing.B) { + for i := 0; i < b.N; i++ { + ctx, cancel := WithCancel(Background()) + buildContextTree(ctx, d) + cancel() + } + }) + b.Run("Root=ClosedCanceler", func(b *testing.B) { + for i := 0; i < b.N; i++ { + ctx, cancel := WithCancel(Background()) + cancel() + buildContextTree(ctx, d) + } + }) + }) + } +} + +func buildContextTree(root Context, depth int) { + for d := 0; d < depth; d++ { + root, _ = WithCancel(root) + } +} + +func BenchmarkCheckCanceled(b *testing.B) { + ctx, cancel := WithCancel(Background()) + cancel() + b.Run("Err", func(b *testing.B) { + for i := 0; i < b.N; i++ { + ctx.Err() + } + }) + b.Run("Done", func(b *testing.B) { + for i := 0; i < b.N; i++ { + select { + case <-ctx.Done(): + default: + } + } + }) +} + +func BenchmarkContextCancelDone(b *testing.B) { + ctx, cancel := WithCancel(Background()) + defer cancel() + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + select { + case <-ctx.Done(): + default: + } + } + }) +} + +func BenchmarkDeepValueNewGoRoutine(b *testing.B) { + for _, depth := range []int{10, 20, 30, 50, 100} { + ctx := Background() + for i := 0; i < depth; i++ { + ctx = WithValue(ctx, i, i) + } + + b.Run(fmt.Sprintf("depth=%d", depth), func(b *testing.B) { + for i := 0; i < b.N; i++ { + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + ctx.Value(-1) + }() + wg.Wait() + } + }) + } +} + +func BenchmarkDeepValueSameGoRoutine(b *testing.B) { + for _, depth := range []int{10, 20, 30, 50, 100} { + ctx := Background() + for i := 0; i < depth; i++ { + ctx = WithValue(ctx, i, i) + } + + b.Run(fmt.Sprintf("depth=%d", depth), func(b *testing.B) { + for i := 0; i < b.N; i++ { + ctx.Value(-1) + } + }) + } +} + +func BenchmarkErrOK(b *testing.B) { + ctx, cancel := WithCancel(Background()) + defer cancel() + for b.Loop() { + if err := ctx.Err(); err != nil { + b.Fatalf("ctx.Err() = %v", err) + } + } +} + +func BenchmarkErrCanceled(b *testing.B) { + ctx, cancel := WithCancel(Background()) + cancel() + for b.Loop() { + if err := ctx.Err(); err == nil { + b.Fatalf("ctx.Err() = %v", err) + } + } +} diff --git a/go/src/context/context.go b/go/src/context/context.go new file mode 100644 index 0000000000000000000000000000000000000000..d00ac67e38296573d20520dbd7aceb2fd1a52906 --- /dev/null +++ b/go/src/context/context.go @@ -0,0 +1,806 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package context defines the Context type, which carries deadlines, +// cancellation signals, and other request-scoped values across API boundaries +// and between processes. +// +// Incoming requests to a server should create a [Context], and outgoing +// calls to servers should accept a Context. The chain of function +// calls between them must propagate the Context, optionally replacing +// it with a derived Context created using [WithCancel], [WithDeadline], +// [WithTimeout], or [WithValue]. +// +// A Context may be canceled to indicate that work done on its behalf should stop. +// A Context with a deadline is canceled after the deadline passes. +// When a Context is canceled, all Contexts derived from it are also canceled. +// +// The [WithCancel], [WithDeadline], and [WithTimeout] functions take a +// Context (the parent) and return a derived Context (the child) and a +// [CancelFunc]. Calling the CancelFunc directly cancels the child and its +// children, removes the parent's reference to the child, and stops +// any associated timers. Failing to call the CancelFunc leaks the +// child and its children until the parent is canceled. The go vet tool +// checks that CancelFuncs are used on all control-flow paths. +// +// The [WithCancelCause], [WithDeadlineCause], and [WithTimeoutCause] functions +// return a [CancelCauseFunc], which takes an error and records it as +// the cancellation cause. Calling [Cause] on the canceled context +// or any of its children retrieves the cause. If no cause is specified, +// Cause(ctx) returns the same value as ctx.Err(). +// +// Programs that use Contexts should follow these rules to keep interfaces +// consistent across packages and enable static analysis tools to check context +// propagation: +// +// Do not store Contexts inside a struct type; instead, pass a Context +// explicitly to each function that needs it. This is discussed further in +// https://go.dev/blog/context-and-structs. The Context should be the first +// parameter, typically named ctx: +// +// func DoSomething(ctx context.Context, arg Arg) error { +// // ... use ctx ... +// } +// +// Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] +// if you are unsure about which Context to use. +// +// Use context Values only for request-scoped data that transits processes and +// APIs, not for passing optional parameters to functions. +// +// The same Context may be passed to functions running in different goroutines; +// Contexts are safe for simultaneous use by multiple goroutines. +// +// See https://go.dev/blog/context for example code for a server that uses +// Contexts. +package context + +import ( + "errors" + "internal/reflectlite" + "sync" + "sync/atomic" + "time" +) + +// A Context carries a deadline, a cancellation signal, and other values across +// API boundaries. +// +// Context's methods may be called by multiple goroutines simultaneously. +type Context interface { + // Deadline returns the time when work done on behalf of this context + // should be canceled. Deadline returns ok==false when no deadline is + // set. Successive calls to Deadline return the same results. + Deadline() (deadline time.Time, ok bool) + + // Done returns a channel that's closed when work done on behalf of this + // context should be canceled. Done may return nil if this context can + // never be canceled. Successive calls to Done return the same value. + // The close of the Done channel may happen asynchronously, + // after the cancel function returns. + // + // WithCancel arranges for Done to be closed when cancel is called; + // WithDeadline arranges for Done to be closed when the deadline + // expires; WithTimeout arranges for Done to be closed when the timeout + // elapses. + // + // Done is provided for use in select statements: + // + // // Stream generates values with DoSomething and sends them to out + // // until DoSomething returns an error or ctx.Done is closed. + // func Stream(ctx context.Context, out chan<- Value) error { + // for { + // v, err := DoSomething(ctx) + // if err != nil { + // return err + // } + // select { + // case <-ctx.Done(): + // return ctx.Err() + // case out <- v: + // } + // } + // } + // + // See https://go.dev/blog/pipelines for more examples of how to use + // a Done channel for cancellation. + Done() <-chan struct{} + + // If Done is not yet closed, Err returns nil. + // If Done is closed, Err returns a non-nil error explaining why: + // DeadlineExceeded if the context's deadline passed, + // or Canceled if the context was canceled for some other reason. + // After Err returns a non-nil error, successive calls to Err return the same error. + Err() error + + // Value returns the value associated with this context for key, or nil + // if no value is associated with key. Successive calls to Value with + // the same key returns the same result. + // + // Use context values only for request-scoped data that transits + // processes and API boundaries, not for passing optional parameters to + // functions. + // + // A key identifies a specific value in a Context. Functions that wish + // to store values in Context typically allocate a key in a global + // variable then use that key as the argument to context.WithValue and + // Context.Value. A key can be any type that supports equality; + // packages should define keys as an unexported type to avoid + // collisions. + // + // Packages that define a Context key should provide type-safe accessors + // for the values stored using that key: + // + // // Package user defines a User type that's stored in Contexts. + // package user + // + // import "context" + // + // // User is the type of value stored in the Contexts. + // type User struct {...} + // + // // key is an unexported type for keys defined in this package. + // // This prevents collisions with keys defined in other packages. + // type key int + // + // // userKey is the key for user.User values in Contexts. It is + // // unexported; clients use user.NewContext and user.FromContext + // // instead of using this key directly. + // var userKey key + // + // // NewContext returns a new Context that carries value u. + // func NewContext(ctx context.Context, u *User) context.Context { + // return context.WithValue(ctx, userKey, u) + // } + // + // // FromContext returns the User value stored in ctx, if any. + // func FromContext(ctx context.Context) (*User, bool) { + // u, ok := ctx.Value(userKey).(*User) + // return u, ok + // } + Value(key any) any +} + +// Canceled is the error returned by [Context.Err] when the context is canceled +// for some reason other than its deadline passing. +var Canceled = errors.New("context canceled") + +// DeadlineExceeded is the error returned by [Context.Err] when the context is canceled +// due to its deadline passing. +var DeadlineExceeded error = deadlineExceededError{} + +type deadlineExceededError struct{} + +func (deadlineExceededError) Error() string { return "context deadline exceeded" } +func (deadlineExceededError) Timeout() bool { return true } +func (deadlineExceededError) Temporary() bool { return true } + +// An emptyCtx is never canceled, has no values, and has no deadline. +// It is the common base of backgroundCtx and todoCtx. +type emptyCtx struct{} + +func (emptyCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (emptyCtx) Done() <-chan struct{} { + return nil +} + +func (emptyCtx) Err() error { + return nil +} + +func (emptyCtx) Value(key any) any { + return nil +} + +type backgroundCtx struct{ emptyCtx } + +func (backgroundCtx) String() string { + return "context.Background" +} + +type todoCtx struct{ emptyCtx } + +func (todoCtx) String() string { + return "context.TODO" +} + +// Background returns a non-nil, empty [Context]. It is never canceled, has no +// values, and has no deadline. It is typically used by the main function, +// initialization, and tests, and as the top-level Context for incoming +// requests. +func Background() Context { + return backgroundCtx{} +} + +// TODO returns a non-nil, empty [Context]. Code should use context.TODO when +// it's unclear which Context to use or it is not yet available (because the +// surrounding function has not yet been extended to accept a Context +// parameter). +func TODO() Context { + return todoCtx{} +} + +// A CancelFunc tells an operation to abandon its work. +// A CancelFunc does not wait for the work to stop. +// A CancelFunc may be called by multiple goroutines simultaneously. +// After the first call, subsequent calls to a CancelFunc do nothing. +type CancelFunc func() + +// WithCancel returns a derived context that points to the parent context +// but has a new Done channel. The returned context's Done channel is closed +// when the returned cancel function is called or when the parent context's +// Done channel is closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this [Context] complete. +func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { + c := withCancel(parent) + return c, func() { c.cancel(true, Canceled, nil) } +} + +// A CancelCauseFunc behaves like a [CancelFunc] but additionally sets the cancellation cause. +// This cause can be retrieved by calling [Cause] on the canceled Context or on +// any of its derived Contexts. +// +// If the context has already been canceled, CancelCauseFunc does not set the cause. +// For example, if childContext is derived from parentContext: +// - if parentContext is canceled with cause1 before childContext is canceled with cause2, +// then Cause(parentContext) == Cause(childContext) == cause1 +// - if childContext is canceled with cause2 before parentContext is canceled with cause1, +// then Cause(parentContext) == cause1 and Cause(childContext) == cause2 +type CancelCauseFunc func(cause error) + +// WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc]. +// Calling cancel with a non-nil error (the "cause") records that error in ctx; +// it can then be retrieved using Cause(ctx). +// Calling cancel with nil sets the cause to Canceled. +// +// Example use: +// +// ctx, cancel := context.WithCancelCause(parent) +// cancel(myError) +// ctx.Err() // returns context.Canceled +// context.Cause(ctx) // returns myError +func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc) { + c := withCancel(parent) + return c, func(cause error) { c.cancel(true, Canceled, cause) } +} + +func withCancel(parent Context) *cancelCtx { + if parent == nil { + panic("cannot create context from nil parent") + } + c := &cancelCtx{} + c.propagateCancel(parent, c) + return c +} + +// Cause returns a non-nil error explaining why c was canceled. +// The first cancellation of c or one of its parents sets the cause. +// If that cancellation happened via a call to CancelCauseFunc(err), +// then [Cause] returns err. +// Otherwise Cause(c) returns the same value as c.Err(). +// Cause returns nil if c has not been canceled yet. +func Cause(c Context) error { + err := c.Err() + if err == nil { + return nil + } + if cc, ok := c.Value(&cancelCtxKey).(*cancelCtx); ok { + cc.mu.Lock() + cause := cc.cause + cc.mu.Unlock() + if cause != nil { + return cause + } + // The parent cancelCtx doesn't have a cause, + // so c must have been canceled in some custom context implementation. + } + // We don't have a cause to return from a parent cancelCtx, + // so return the context's error. + return err +} + +// AfterFunc arranges to call f in its own goroutine after ctx is canceled. +// If ctx is already canceled, AfterFunc calls f immediately in its own goroutine. +// +// Multiple calls to AfterFunc on a context operate independently; +// one does not replace another. +// +// Calling the returned stop function stops the association of ctx with f. +// It returns true if the call stopped f from being run. +// If stop returns false, +// either the context is canceled and f has been started in its own goroutine; +// or f was already stopped. +// The stop function does not wait for f to complete before returning. +// If the caller needs to know whether f is completed, +// it must coordinate with f explicitly. +// +// If ctx has a "AfterFunc(func()) func() bool" method, +// AfterFunc will use it to schedule the call. +func AfterFunc(ctx Context, f func()) (stop func() bool) { + a := &afterFuncCtx{ + f: f, + } + a.cancelCtx.propagateCancel(ctx, a) + return func() bool { + stopped := false + a.once.Do(func() { + stopped = true + }) + if stopped { + a.cancel(true, Canceled, nil) + } + return stopped + } +} + +type afterFuncer interface { + AfterFunc(func()) func() bool +} + +type afterFuncCtx struct { + cancelCtx + once sync.Once // either starts running f or stops f from running + f func() +} + +func (a *afterFuncCtx) cancel(removeFromParent bool, err, cause error) { + a.cancelCtx.cancel(false, err, cause) + if removeFromParent { + removeChild(a.Context, a) + } + a.once.Do(func() { + go a.f() + }) +} + +// A stopCtx is used as the parent context of a cancelCtx when +// an AfterFunc has been registered with the parent. +// It holds the stop function used to unregister the AfterFunc. +type stopCtx struct { + Context + stop func() bool +} + +// goroutines counts the number of goroutines ever created; for testing. +var goroutines atomic.Int32 + +// &cancelCtxKey is the key that a cancelCtx returns itself for. +var cancelCtxKey int + +// parentCancelCtx returns the underlying *cancelCtx for parent. +// It does this by looking up parent.Value(&cancelCtxKey) to find +// the innermost enclosing *cancelCtx and then checking whether +// parent.Done() matches that *cancelCtx. (If not, the *cancelCtx +// has been wrapped in a custom implementation providing a +// different done channel, in which case we should not bypass it.) +func parentCancelCtx(parent Context) (*cancelCtx, bool) { + done := parent.Done() + if done == closedchan || done == nil { + return nil, false + } + p, ok := parent.Value(&cancelCtxKey).(*cancelCtx) + if !ok { + return nil, false + } + pdone, _ := p.done.Load().(chan struct{}) + if pdone != done { + return nil, false + } + return p, true +} + +// removeChild removes a context from its parent. +func removeChild(parent Context, child canceler) { + if s, ok := parent.(stopCtx); ok { + s.stop() + return + } + p, ok := parentCancelCtx(parent) + if !ok { + return + } + p.mu.Lock() + if p.children != nil { + delete(p.children, child) + } + p.mu.Unlock() +} + +// A canceler is a context type that can be canceled directly. The +// implementations are *cancelCtx and *timerCtx. +type canceler interface { + cancel(removeFromParent bool, err, cause error) + Done() <-chan struct{} +} + +// closedchan is a reusable closed channel. +var closedchan = make(chan struct{}) + +func init() { + close(closedchan) +} + +// A cancelCtx can be canceled. When canceled, it also cancels any children +// that implement canceler. +type cancelCtx struct { + Context + + mu sync.Mutex // protects following fields + done atomic.Value // of chan struct{}, created lazily, closed by first cancel call + children map[canceler]struct{} // set to nil by the first cancel call + err atomic.Value // set to non-nil by the first cancel call + cause error // set to non-nil by the first cancel call +} + +func (c *cancelCtx) Value(key any) any { + if key == &cancelCtxKey { + return c + } + return value(c.Context, key) +} + +func (c *cancelCtx) Done() <-chan struct{} { + d := c.done.Load() + if d != nil { + return d.(chan struct{}) + } + c.mu.Lock() + defer c.mu.Unlock() + d = c.done.Load() + if d == nil { + d = make(chan struct{}) + c.done.Store(d) + } + return d.(chan struct{}) +} + +func (c *cancelCtx) Err() error { + // An atomic load is ~5x faster than a mutex, which can matter in tight loops. + if err := c.err.Load(); err != nil { + // Ensure the done channel has been closed before returning a non-nil error. + <-c.Done() + return err.(error) + } + return nil +} + +// propagateCancel arranges for child to be canceled when parent is. +// It sets the parent context of cancelCtx. +func (c *cancelCtx) propagateCancel(parent Context, child canceler) { + c.Context = parent + + done := parent.Done() + if done == nil { + return // parent is never canceled + } + + select { + case <-done: + // parent is already canceled + child.cancel(false, parent.Err(), Cause(parent)) + return + default: + } + + if p, ok := parentCancelCtx(parent); ok { + // parent is a *cancelCtx, or derives from one. + p.mu.Lock() + if err := p.err.Load(); err != nil { + // parent has already been canceled + child.cancel(false, err.(error), p.cause) + } else { + if p.children == nil { + p.children = make(map[canceler]struct{}) + } + p.children[child] = struct{}{} + } + p.mu.Unlock() + return + } + + if a, ok := parent.(afterFuncer); ok { + // parent implements an AfterFunc method. + c.mu.Lock() + stop := a.AfterFunc(func() { + child.cancel(false, parent.Err(), Cause(parent)) + }) + c.Context = stopCtx{ + Context: parent, + stop: stop, + } + c.mu.Unlock() + return + } + + goroutines.Add(1) + go func() { + select { + case <-parent.Done(): + child.cancel(false, parent.Err(), Cause(parent)) + case <-child.Done(): + } + }() +} + +type stringer interface { + String() string +} + +func contextName(c Context) string { + if s, ok := c.(stringer); ok { + return s.String() + } + return reflectlite.TypeOf(c).String() +} + +func (c *cancelCtx) String() string { + return contextName(c.Context) + ".WithCancel" +} + +// cancel closes c.done, cancels each of c's children, and, if +// removeFromParent is true, removes c from its parent's children. +// cancel sets c.cause to cause if this is the first time c is canceled. +func (c *cancelCtx) cancel(removeFromParent bool, err, cause error) { + if err == nil { + panic("context: internal error: missing cancel error") + } + if cause == nil { + cause = err + } + c.mu.Lock() + if c.err.Load() != nil { + c.mu.Unlock() + return // already canceled + } + c.err.Store(err) + c.cause = cause + d, _ := c.done.Load().(chan struct{}) + if d == nil { + c.done.Store(closedchan) + } else { + close(d) + } + for child := range c.children { + // NOTE: acquiring the child's lock while holding parent's lock. + child.cancel(false, err, cause) + } + c.children = nil + c.mu.Unlock() + + if removeFromParent { + removeChild(c.Context, c) + } +} + +// WithoutCancel returns a derived context that points to the parent context +// and is not canceled when parent is canceled. +// The returned context returns no Deadline or Err, and its Done channel is nil. +// Calling [Cause] on the returned context returns nil. +func WithoutCancel(parent Context) Context { + if parent == nil { + panic("cannot create context from nil parent") + } + return withoutCancelCtx{parent} +} + +type withoutCancelCtx struct { + c Context +} + +func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (withoutCancelCtx) Done() <-chan struct{} { + return nil +} + +func (withoutCancelCtx) Err() error { + return nil +} + +func (c withoutCancelCtx) Value(key any) any { + return value(c, key) +} + +func (c withoutCancelCtx) String() string { + return contextName(c.c) + ".WithoutCancel" +} + +// WithDeadline returns a derived context that points to the parent context +// but has the deadline adjusted to be no later than d. If the parent's +// deadline is already earlier than d, WithDeadline(parent, d) is semantically +// equivalent to parent. The returned [Context.Done] channel is closed when +// the deadline expires, when the returned cancel function is called, +// or when the parent context's Done channel is closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this [Context] complete. +func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { + return WithDeadlineCause(parent, d, nil) +} + +// WithDeadlineCause behaves like [WithDeadline] but also sets the cause of the +// returned Context when the deadline is exceeded. The returned [CancelFunc] does +// not set the cause. +func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) { + if parent == nil { + panic("cannot create context from nil parent") + } + if cur, ok := parent.Deadline(); ok && cur.Before(d) { + // The current deadline is already sooner than the new one. + return WithCancel(parent) + } + c := &timerCtx{ + deadline: d, + } + c.cancelCtx.propagateCancel(parent, c) + dur := time.Until(d) + if dur <= 0 { + c.cancel(true, DeadlineExceeded, cause) // deadline has already passed + return c, func() { c.cancel(false, Canceled, nil) } + } + c.mu.Lock() + defer c.mu.Unlock() + if c.err.Load() == nil { + c.timer = time.AfterFunc(dur, func() { + c.cancel(true, DeadlineExceeded, cause) + }) + } + return c, func() { c.cancel(true, Canceled, nil) } +} + +// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to +// implement Done and Err. It implements cancel by stopping its timer then +// delegating to cancelCtx.cancel. +type timerCtx struct { + cancelCtx + timer *time.Timer // Under cancelCtx.mu. + + deadline time.Time +} + +func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { + return c.deadline, true +} + +func (c *timerCtx) String() string { + return contextName(c.cancelCtx.Context) + ".WithDeadline(" + + c.deadline.String() + " [" + + time.Until(c.deadline).String() + "])" +} + +func (c *timerCtx) cancel(removeFromParent bool, err, cause error) { + c.cancelCtx.cancel(false, err, cause) + if removeFromParent { + // Remove this timerCtx from its parent cancelCtx's children. + removeChild(c.cancelCtx.Context, c) + } + c.mu.Lock() + if c.timer != nil { + c.timer.Stop() + c.timer = nil + } + c.mu.Unlock() +} + +// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this [Context] complete: +// +// func slowOperationWithTimeout(ctx context.Context) (Result, error) { +// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) +// defer cancel() // releases resources if slowOperation completes before timeout elapses +// return slowOperation(ctx) +// } +func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { + return WithDeadline(parent, time.Now().Add(timeout)) +} + +// WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the +// returned Context when the timeout expires. The returned [CancelFunc] does +// not set the cause. +func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc) { + return WithDeadlineCause(parent, time.Now().Add(timeout), cause) +} + +// WithValue returns a derived context that points to the parent Context. +// In the derived context, the value associated with key is val. +// +// Use context Values only for request-scoped data that transits processes and +// APIs, not for passing optional parameters to functions. +// +// The provided key must be comparable and should not be of type +// string or any other built-in type to avoid collisions between +// packages using context. Users of WithValue should define their own +// types for keys. To avoid allocating when assigning to an +// interface{}, context keys often have concrete type +// struct{}. Alternatively, exported context key variables' static +// type should be a pointer or interface. +func WithValue(parent Context, key, val any) Context { + if parent == nil { + panic("cannot create context from nil parent") + } + if key == nil { + panic("nil key") + } + if !reflectlite.TypeOf(key).Comparable() { + panic("key is not comparable") + } + return &valueCtx{parent, key, val} +} + +// A valueCtx carries a key-value pair. It implements Value for that key and +// delegates all other calls to the embedded Context. +type valueCtx struct { + Context + key, val any +} + +// stringify tries a bit to stringify v, without using fmt, since we don't +// want context depending on the unicode tables. This is only used by +// *valueCtx.String(). +func stringify(v any) string { + switch s := v.(type) { + case stringer: + return s.String() + case string: + return s + case nil: + return "" + } + return reflectlite.TypeOf(v).String() +} + +func (c *valueCtx) String() string { + return contextName(c.Context) + ".WithValue(" + + stringify(c.key) + ", " + + stringify(c.val) + ")" +} + +func (c *valueCtx) Value(key any) any { + if c.key == key { + return c.val + } + return value(c.Context, key) +} + +func value(c Context, key any) any { + for { + switch ctx := c.(type) { + case *valueCtx: + if key == ctx.key { + return ctx.val + } + c = ctx.Context + case *cancelCtx: + if key == &cancelCtxKey { + return c + } + c = ctx.Context + case withoutCancelCtx: + if key == &cancelCtxKey { + // This implements Cause(ctx) == nil + // when ctx is created using WithoutCancel. + return nil + } + c = ctx.c + case *timerCtx: + if key == &cancelCtxKey { + return &ctx.cancelCtx + } + c = ctx.Context + case backgroundCtx, todoCtx: + return nil + default: + return c.Value(key) + } + } +} diff --git a/go/src/context/context_test.go b/go/src/context/context_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ad47f853dd4b3620df67b12dcc554524546d9a74 --- /dev/null +++ b/go/src/context/context_test.go @@ -0,0 +1,297 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context + +// Tests in package context cannot depend directly on package testing due to an import cycle. +// If your test requires access to unexported members of the context package, +// add your test below as `func XTestFoo(t testingT)` and add a `TestFoo` to x_test.go +// that calls it. Otherwise, write a regular test in a test.go file in package context_test. + +import ( + "time" +) + +type testingT interface { + Deadline() (time.Time, bool) + Error(args ...any) + Errorf(format string, args ...any) + Fail() + FailNow() + Failed() bool + Fatal(args ...any) + Fatalf(format string, args ...any) + Helper() + Log(args ...any) + Logf(format string, args ...any) + Name() string + Parallel() + Skip(args ...any) + SkipNow() + Skipf(format string, args ...any) + Skipped() bool +} + +const veryLongDuration = 1000 * time.Hour // an arbitrary upper bound on the test's running time + +func contains(m map[canceler]struct{}, key canceler) bool { + _, ret := m[key] + return ret +} + +func XTestParentFinishesChild(t testingT) { + // Context tree: + // parent -> cancelChild + // parent -> valueChild -> timerChild + // parent -> afterChild + parent, cancel := WithCancel(Background()) + cancelChild, stop := WithCancel(parent) + defer stop() + valueChild := WithValue(parent, "key", "value") + timerChild, stop := WithTimeout(valueChild, veryLongDuration) + defer stop() + afterStop := AfterFunc(parent, func() {}) + defer afterStop() + + select { + case x := <-parent.Done(): + t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) + case x := <-cancelChild.Done(): + t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) + case x := <-timerChild.Done(): + t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) + case x := <-valueChild.Done(): + t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) + default: + } + + // The parent's children should contain the three cancelable children. + pc := parent.(*cancelCtx) + cc := cancelChild.(*cancelCtx) + tc := timerChild.(*timerCtx) + pc.mu.Lock() + var ac *afterFuncCtx + for c := range pc.children { + if a, ok := c.(*afterFuncCtx); ok { + ac = a + break + } + } + if len(pc.children) != 3 || !contains(pc.children, cc) || !contains(pc.children, tc) || ac == nil { + t.Errorf("bad linkage: pc.children = %v, want %v, %v, and an afterFunc", + pc.children, cc, tc) + } + pc.mu.Unlock() + + if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { + t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) + } + if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { + t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) + } + if p, ok := parentCancelCtx(ac.Context); !ok || p != pc { + t.Errorf("bad linkage: parentCancelCtx(afterChild.Context) = %v, %v want %v, true", p, ok, pc) + } + + cancel() + + pc.mu.Lock() + if len(pc.children) != 0 { + t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) + } + pc.mu.Unlock() + + // parent and children should all be finished. + check := func(ctx Context, name string) { + select { + case <-ctx.Done(): + default: + t.Errorf("<-%s.Done() blocked, but shouldn't have", name) + } + if e := ctx.Err(); e != Canceled { + t.Errorf("%s.Err() == %v want %v", name, e, Canceled) + } + } + check(parent, "parent") + check(cancelChild, "cancelChild") + check(valueChild, "valueChild") + check(timerChild, "timerChild") + + // WithCancel should return a canceled context on a canceled parent. + precanceledChild := WithValue(parent, "key", "value") + select { + case <-precanceledChild.Done(): + default: + t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") + } + if e := precanceledChild.Err(); e != Canceled { + t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) + } +} + +func XTestChildFinishesFirst(t testingT) { + cancelable, stop := WithCancel(Background()) + defer stop() + for _, parent := range []Context{Background(), cancelable} { + child, cancel := WithCancel(parent) + + select { + case x := <-parent.Done(): + t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) + case x := <-child.Done(): + t.Errorf("<-child.Done() == %v want nothing (it should block)", x) + default: + } + + cc := child.(*cancelCtx) + pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() + if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { + t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) + } + + if pcok { + pc.mu.Lock() + if len(pc.children) != 1 || !contains(pc.children, cc) { + t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) + } + pc.mu.Unlock() + } + + cancel() + + if pcok { + pc.mu.Lock() + if len(pc.children) != 0 { + t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) + } + pc.mu.Unlock() + } + + // child should be finished. + select { + case <-child.Done(): + default: + t.Errorf("<-child.Done() blocked, but shouldn't have") + } + if e := child.Err(); e != Canceled { + t.Errorf("child.Err() == %v want %v", e, Canceled) + } + + // parent should not be finished. + select { + case x := <-parent.Done(): + t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) + default: + } + if e := parent.Err(); e != nil { + t.Errorf("parent.Err() == %v want nil", e) + } + } +} + +func XTestCancelRemoves(t testingT) { + checkChildren := func(when string, ctx Context, want int) { + if got := len(ctx.(*cancelCtx).children); got != want { + t.Errorf("%s: context has %d children, want %d", when, got, want) + } + } + + ctx, _ := WithCancel(Background()) + checkChildren("after creation", ctx, 0) + _, cancel := WithCancel(ctx) + checkChildren("with WithCancel child ", ctx, 1) + cancel() + checkChildren("after canceling WithCancel child", ctx, 0) + + ctx, _ = WithCancel(Background()) + checkChildren("after creation", ctx, 0) + _, cancel = WithTimeout(ctx, 60*time.Minute) + checkChildren("with WithTimeout child ", ctx, 1) + cancel() + checkChildren("after canceling WithTimeout child", ctx, 0) + + ctx, _ = WithCancel(Background()) + checkChildren("after creation", ctx, 0) + stop := AfterFunc(ctx, func() {}) + checkChildren("with AfterFunc child ", ctx, 1) + stop() + checkChildren("after stopping AfterFunc child ", ctx, 0) +} + +type myCtx struct { + Context +} + +type myDoneCtx struct { + Context +} + +func (d *myDoneCtx) Done() <-chan struct{} { + c := make(chan struct{}) + return c +} +func XTestCustomContextGoroutines(t testingT) { + g := goroutines.Load() + checkNoGoroutine := func() { + t.Helper() + now := goroutines.Load() + if now != g { + t.Fatalf("%d goroutines created", now-g) + } + } + checkCreatedGoroutine := func() { + t.Helper() + now := goroutines.Load() + if now != g+1 { + t.Fatalf("%d goroutines created, want 1", now-g) + } + g = now + } + + _, cancel0 := WithCancel(&myDoneCtx{Background()}) + cancel0() + checkCreatedGoroutine() + + _, cancel0 = WithTimeout(&myDoneCtx{Background()}, veryLongDuration) + cancel0() + checkCreatedGoroutine() + + checkNoGoroutine() + defer checkNoGoroutine() + + ctx1, cancel1 := WithCancel(Background()) + defer cancel1() + checkNoGoroutine() + + ctx2 := &myCtx{ctx1} + ctx3, cancel3 := WithCancel(ctx2) + defer cancel3() + checkNoGoroutine() + + _, cancel3b := WithCancel(&myDoneCtx{ctx2}) + defer cancel3b() + checkCreatedGoroutine() // ctx1 is not providing Done, must not be used + + ctx4, cancel4 := WithTimeout(ctx3, veryLongDuration) + defer cancel4() + checkNoGoroutine() + + ctx5, cancel5 := WithCancel(ctx4) + defer cancel5() + checkNoGoroutine() + + cancel5() + checkNoGoroutine() + + _, cancel6 := WithTimeout(ctx5, veryLongDuration) + defer cancel6() + checkNoGoroutine() + + // Check applied to canceled context. + cancel6() + cancel1() + _, cancel7 := WithCancel(ctx5) + defer cancel7() + checkNoGoroutine() +} diff --git a/go/src/context/example_test.go b/go/src/context/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..be8cd8376e173678e1f38c7d09806cce9ac8ecba --- /dev/null +++ b/go/src/context/example_test.go @@ -0,0 +1,263 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context_test + +import ( + "context" + "errors" + "fmt" + "net" + "sync" + "time" +) + +var neverReady = make(chan struct{}) // never closed + +// This example demonstrates the use of a cancelable context to prevent a +// goroutine leak. By the end of the example function, the goroutine started +// by gen will return without leaking. +func ExampleWithCancel() { + // gen generates integers in a separate goroutine and + // sends them to the returned channel. + // The callers of gen need to cancel the context once + // they are done consuming generated integers not to leak + // the internal goroutine started by gen. + gen := func(ctx context.Context) <-chan int { + dst := make(chan int) + n := 1 + go func() { + for { + select { + case <-ctx.Done(): + return // returning not to leak the goroutine + case dst <- n: + n++ + } + } + }() + return dst + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // cancel when we are finished consuming integers + + for n := range gen(ctx) { + fmt.Println(n) + if n == 5 { + break + } + } + // Output: + // 1 + // 2 + // 3 + // 4 + // 5 +} + +// This example passes a context with an arbitrary deadline to tell a blocking +// function that it should abandon its work as soon as it gets to it. +func ExampleWithDeadline() { + d := time.Now().Add(shortDuration) + ctx, cancel := context.WithDeadline(context.Background(), d) + + // Even though ctx will be expired, it is good practice to call its + // cancellation function in any case. Failure to do so may keep the + // context and its parent alive longer than necessary. + defer cancel() + + select { + case <-neverReady: + fmt.Println("ready") + case <-ctx.Done(): + fmt.Println(ctx.Err()) + } + + // Output: + // context deadline exceeded +} + +// This example passes a context with a timeout to tell a blocking function that +// it should abandon its work after the timeout elapses. +func ExampleWithTimeout() { + // Pass a context with a timeout to tell a blocking function that it + // should abandon its work after the timeout elapses. + ctx, cancel := context.WithTimeout(context.Background(), shortDuration) + defer cancel() + + select { + case <-neverReady: + fmt.Println("ready") + case <-ctx.Done(): + fmt.Println(ctx.Err()) // prints "context deadline exceeded" + } + + // Output: + // context deadline exceeded +} + +// This example demonstrates how a value can be passed to the context +// and also how to retrieve it if it exists. +func ExampleWithValue() { + type favContextKey string + + f := func(ctx context.Context, k favContextKey) { + if v := ctx.Value(k); v != nil { + fmt.Println("found value:", v) + return + } + fmt.Println("key not found:", k) + } + + k := favContextKey("language") + ctx := context.WithValue(context.Background(), k, "Go") + + f(ctx, k) + f(ctx, favContextKey("color")) + + // Output: + // found value: Go + // key not found: color +} + +// This example uses AfterFunc to define a function which waits on a sync.Cond, +// stopping the wait when a context is canceled. +func ExampleAfterFunc_cond() { + waitOnCond := func(ctx context.Context, cond *sync.Cond, conditionMet func() bool) error { + stopf := context.AfterFunc(ctx, func() { + // We need to acquire cond.L here to be sure that the Broadcast + // below won't occur before the call to Wait, which would result + // in a missed signal (and deadlock). + cond.L.Lock() + defer cond.L.Unlock() + + // If multiple goroutines are waiting on cond simultaneously, + // we need to make sure we wake up exactly this one. + // That means that we need to Broadcast to all of the goroutines, + // which will wake them all up. + // + // If there are N concurrent calls to waitOnCond, each of the goroutines + // will spuriously wake up O(N) other goroutines that aren't ready yet, + // so this will cause the overall CPU cost to be O(N²). + cond.Broadcast() + }) + defer stopf() + + // Since the wakeups are using Broadcast instead of Signal, this call to + // Wait may unblock due to some other goroutine's context being canceled, + // so to be sure that ctx is actually canceled we need to check it in a loop. + for !conditionMet() { + cond.Wait() + if ctx.Err() != nil { + return ctx.Err() + } + } + + return nil + } + + cond := sync.NewCond(new(sync.Mutex)) + + var wg sync.WaitGroup + for i := 0; i < 4; i++ { + wg.Add(1) + go func() { + defer wg.Done() + + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) + defer cancel() + + cond.L.Lock() + defer cond.L.Unlock() + + err := waitOnCond(ctx, cond, func() bool { return false }) + fmt.Println(err) + }() + } + wg.Wait() + + // Output: + // context deadline exceeded + // context deadline exceeded + // context deadline exceeded + // context deadline exceeded +} + +// This example uses AfterFunc to define a function which reads from a net.Conn, +// stopping the read when a context is canceled. +func ExampleAfterFunc_connection() { + readFromConn := func(ctx context.Context, conn net.Conn, b []byte) (n int, err error) { + stopc := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + conn.SetReadDeadline(time.Now()) + close(stopc) + }) + n, err = conn.Read(b) + if !stop() { + // The AfterFunc was started. + // Wait for it to complete, and reset the Conn's deadline. + <-stopc + conn.SetReadDeadline(time.Time{}) + return n, ctx.Err() + } + return n, err + } + + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + fmt.Println(err) + return + } + defer listener.Close() + + conn, err := net.Dial(listener.Addr().Network(), listener.Addr().String()) + if err != nil { + fmt.Println(err) + return + } + defer conn.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) + defer cancel() + + b := make([]byte, 1024) + _, err = readFromConn(ctx, conn, b) + fmt.Println(err) + + // Output: + // context deadline exceeded +} + +// This example uses AfterFunc to define a function which combines +// the cancellation signals of two Contexts. +func ExampleAfterFunc_merge() { + // mergeCancel returns a context that contains the values of ctx, + // and which is canceled when either ctx or cancelCtx is canceled. + mergeCancel := func(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithCancelCause(ctx) + stop := context.AfterFunc(cancelCtx, func() { + cancel(context.Cause(cancelCtx)) + }) + return ctx, func() { + stop() + cancel(context.Canceled) + } + } + + ctx1, cancel1 := context.WithCancelCause(context.Background()) + defer cancel1(errors.New("ctx1 canceled")) + + ctx2, cancel2 := context.WithCancelCause(context.Background()) + + mergedCtx, mergedCancel := mergeCancel(ctx1, ctx2) + defer mergedCancel() + + cancel2(errors.New("ctx2 canceled")) + <-mergedCtx.Done() + fmt.Println(context.Cause(mergedCtx)) + + // Output: + // ctx2 canceled +} diff --git a/go/src/context/net_test.go b/go/src/context/net_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a007689d363713a4c548623ef934c6bb83918ade --- /dev/null +++ b/go/src/context/net_test.go @@ -0,0 +1,21 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context_test + +import ( + "context" + "net" + "testing" +) + +func TestDeadlineExceededIsNetError(t *testing.T) { + err, ok := context.DeadlineExceeded.(net.Error) + if !ok { + t.Fatal("DeadlineExceeded does not implement net.Error") + } + if !err.Timeout() || !err.Temporary() { + t.Fatalf("Timeout() = %v, Temporary() = %v, want true, true", err.Timeout(), err.Temporary()) + } +} diff --git a/go/src/context/x_test.go b/go/src/context/x_test.go new file mode 100644 index 0000000000000000000000000000000000000000..aeb5470399f4eec82a32533c24079f8c653dd2c9 --- /dev/null +++ b/go/src/context/x_test.go @@ -0,0 +1,1198 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context_test + +import ( + . "context" + "errors" + "fmt" + "internal/asan" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +// Each XTestFoo in context_test.go must be called from a TestFoo here to run. +func TestParentFinishesChild(t *testing.T) { + XTestParentFinishesChild(t) // uses unexported context types +} +func TestChildFinishesFirst(t *testing.T) { + XTestChildFinishesFirst(t) // uses unexported context types +} +func TestCancelRemoves(t *testing.T) { + XTestCancelRemoves(t) // uses unexported context types +} +func TestCustomContextGoroutines(t *testing.T) { + XTestCustomContextGoroutines(t) // reads the context.goroutines counter +} + +// The following are regular tests in package context_test. + +// otherContext is a Context that's not one of the types defined in context.go. +// This lets us test code paths that differ based on the underlying type of the +// Context. +type otherContext struct { + Context +} + +const ( + shortDuration = 1 * time.Millisecond // a reasonable duration to block in a test + veryLongDuration = 1000 * time.Hour // an arbitrary upper bound on the test's running time +) + +// quiescent returns an arbitrary duration by which the program should have +// completed any remaining work and reached a steady (idle) state. +func quiescent(t *testing.T) time.Duration { + deadline, ok := t.Deadline() + if !ok { + return 5 * time.Second + } + + const arbitraryCleanupMargin = 1 * time.Second + return time.Until(deadline) - arbitraryCleanupMargin +} +func TestBackground(t *testing.T) { + c := Background() + if c == nil { + t.Fatalf("Background returned nil") + } + select { + case x := <-c.Done(): + t.Errorf("<-c.Done() == %v want nothing (it should block)", x) + default: + } + if got, want := fmt.Sprint(c), "context.Background"; got != want { + t.Errorf("Background().String() = %q want %q", got, want) + } +} + +func TestTODO(t *testing.T) { + c := TODO() + if c == nil { + t.Fatalf("TODO returned nil") + } + select { + case x := <-c.Done(): + t.Errorf("<-c.Done() == %v want nothing (it should block)", x) + default: + } + if got, want := fmt.Sprint(c), "context.TODO"; got != want { + t.Errorf("TODO().String() = %q want %q", got, want) + } +} + +func TestWithCancel(t *testing.T) { + c1, cancel := WithCancel(Background()) + + if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { + t.Errorf("c1.String() = %q want %q", got, want) + } + + o := otherContext{c1} + c2, _ := WithCancel(o) + contexts := []Context{c1, o, c2} + + for i, c := range contexts { + if d := c.Done(); d == nil { + t.Errorf("c[%d].Done() == %v want non-nil", i, d) + } + if e := c.Err(); e != nil { + t.Errorf("c[%d].Err() == %v want nil", i, e) + } + + select { + case x := <-c.Done(): + t.Errorf("<-c.Done() == %v want nothing (it should block)", x) + default: + } + } + + cancel() // Should propagate synchronously. + for i, c := range contexts { + select { + case <-c.Done(): + default: + t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) + } + if e := c.Err(); e != Canceled { + t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) + } + } +} + +func testDeadline(c Context, name string, t *testing.T) { + t.Helper() + d := quiescent(t) + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-timer.C: + t.Fatalf("%s: context not timed out after %v", name, d) + case <-c.Done(): + } + if e := c.Err(); e != DeadlineExceeded { + t.Errorf("%s: c.Err() == %v; want %v", name, e, DeadlineExceeded) + } +} + +func TestDeadline(t *testing.T) { + t.Parallel() + + c, _ := WithDeadline(Background(), time.Now().Add(shortDuration)) + if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { + t.Errorf("c.String() = %q want prefix %q", got, prefix) + } + testDeadline(c, "WithDeadline", t) + + c, _ = WithDeadline(Background(), time.Now().Add(shortDuration)) + o := otherContext{c} + testDeadline(o, "WithDeadline+otherContext", t) + + c, _ = WithDeadline(Background(), time.Now().Add(shortDuration)) + o = otherContext{c} + c, _ = WithDeadline(o, time.Now().Add(veryLongDuration)) + testDeadline(c, "WithDeadline+otherContext+WithDeadline", t) + + c, _ = WithDeadline(Background(), time.Now().Add(-shortDuration)) + testDeadline(c, "WithDeadline+inthepast", t) + + c, _ = WithDeadline(Background(), time.Now()) + testDeadline(c, "WithDeadline+now", t) +} + +func TestTimeout(t *testing.T) { + t.Parallel() + + c, _ := WithTimeout(Background(), shortDuration) + if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { + t.Errorf("c.String() = %q want prefix %q", got, prefix) + } + testDeadline(c, "WithTimeout", t) + + c, _ = WithTimeout(Background(), shortDuration) + o := otherContext{c} + testDeadline(o, "WithTimeout+otherContext", t) + + c, _ = WithTimeout(Background(), shortDuration) + o = otherContext{c} + c, _ = WithTimeout(o, veryLongDuration) + testDeadline(c, "WithTimeout+otherContext+WithTimeout", t) +} + +func TestCanceledTimeout(t *testing.T) { + c, _ := WithTimeout(Background(), time.Second) + o := otherContext{c} + c, cancel := WithTimeout(o, veryLongDuration) + cancel() // Should propagate synchronously. + select { + case <-c.Done(): + default: + t.Errorf("<-c.Done() blocked, but shouldn't have") + } + if e := c.Err(); e != Canceled { + t.Errorf("c.Err() == %v want %v", e, Canceled) + } +} + +type key1 int +type key2 int + +func (k key2) String() string { return fmt.Sprintf("%[1]T(%[1]d)", k) } + +var k1 = key1(1) +var k2 = key2(1) // same int as k1, different type +var k3 = key2(3) // same type as k2, different int + +func TestValues(t *testing.T) { + check := func(c Context, nm, v1, v2, v3 string) { + if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { + t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) + } + if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { + t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) + } + if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { + t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) + } + } + + c0 := Background() + check(c0, "c0", "", "", "") + + c1 := WithValue(Background(), k1, "c1k1") + check(c1, "c1", "c1k1", "", "") + + if got, want := fmt.Sprint(c1), `context.Background.WithValue(context_test.key1, c1k1)`; got != want { + t.Errorf("c.String() = %q want %q", got, want) + } + + c2 := WithValue(c1, k2, "c2k2") + check(c2, "c2", "c1k1", "c2k2", "") + + if got, want := fmt.Sprint(c2), `context.Background.WithValue(context_test.key1, c1k1).WithValue(context_test.key2(1), c2k2)`; got != want { + t.Errorf("c.String() = %q want %q", got, want) + } + + c3 := WithValue(c2, k3, "c3k3") + check(c3, "c2", "c1k1", "c2k2", "c3k3") + + c4 := WithValue(c3, k1, nil) + check(c4, "c4", "", "c2k2", "c3k3") + + if got, want := fmt.Sprint(c4), `context.Background.WithValue(context_test.key1, c1k1).WithValue(context_test.key2(1), c2k2).WithValue(context_test.key2(3), c3k3).WithValue(context_test.key1, )`; got != want { + t.Errorf("c.String() = %q want %q", got, want) + } + + o0 := otherContext{Background()} + check(o0, "o0", "", "", "") + + o1 := otherContext{WithValue(Background(), k1, "c1k1")} + check(o1, "o1", "c1k1", "", "") + + o2 := WithValue(o1, k2, "o2k2") + check(o2, "o2", "c1k1", "o2k2", "") + + o3 := otherContext{c4} + check(o3, "o3", "", "c2k2", "c3k3") + + o4 := WithValue(o3, k3, nil) + check(o4, "o4", "", "c2k2", "") +} + +func TestAllocs(t *testing.T) { + if asan.Enabled { + t.Skip("test allocates more with -asan") + } + bg := Background() + for _, test := range []struct { + desc string + f func() + limit float64 + gccgoLimit float64 + }{ + { + desc: "Background()", + f: func() { Background() }, + limit: 0, + gccgoLimit: 0, + }, + { + desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), + f: func() { + c := WithValue(bg, k1, nil) + c.Value(k1) + }, + limit: 3, + gccgoLimit: 3, + }, + { + desc: "WithTimeout(bg, 1*time.Nanosecond)", + f: func() { + c, _ := WithTimeout(bg, 1*time.Nanosecond) + <-c.Done() + }, + limit: 12, + gccgoLimit: 15, + }, + { + desc: "WithCancel(bg)", + f: func() { + c, cancel := WithCancel(bg) + cancel() + <-c.Done() + }, + limit: 5, + gccgoLimit: 8, + }, + { + desc: "WithTimeout(bg, 5*time.Millisecond)", + f: func() { + c, cancel := WithTimeout(bg, 5*time.Millisecond) + cancel() + <-c.Done() + }, + limit: 8, + gccgoLimit: 25, + }, + } { + limit := test.limit + if runtime.Compiler == "gccgo" { + // gccgo does not yet do escape analysis. + // TODO(iant): Remove this when gccgo does do escape analysis. + limit = test.gccgoLimit + } + numRuns := 100 + if testing.Short() { + numRuns = 10 + } + if n := testing.AllocsPerRun(numRuns, test.f); n > limit { + t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) + } + } +} + +func TestSimultaneousCancels(t *testing.T) { + root, cancel := WithCancel(Background()) + m := map[Context]CancelFunc{root: cancel} + q := []Context{root} + // Create a tree of contexts. + for len(q) != 0 && len(m) < 100 { + parent := q[0] + q = q[1:] + for i := 0; i < 4; i++ { + ctx, cancel := WithCancel(parent) + m[ctx] = cancel + q = append(q, ctx) + } + } + // Start all the cancels in a random order. + var wg sync.WaitGroup + wg.Add(len(m)) + for _, cancel := range m { + go func(cancel CancelFunc) { + cancel() + wg.Done() + }(cancel) + } + + d := quiescent(t) + stuck := make(chan struct{}) + timer := time.AfterFunc(d, func() { close(stuck) }) + defer timer.Stop() + + // Wait on all the contexts in a random order. + for ctx := range m { + select { + case <-ctx.Done(): + case <-stuck: + buf := make([]byte, 10<<10) + n := runtime.Stack(buf, true) + t.Fatalf("timed out after %v waiting for <-ctx.Done(); stacks:\n%s", d, buf[:n]) + } + } + // Wait for all the cancel functions to return. + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + case <-stuck: + buf := make([]byte, 10<<10) + n := runtime.Stack(buf, true) + t.Fatalf("timed out after %v waiting for cancel functions; stacks:\n%s", d, buf[:n]) + } +} + +func TestInterlockedCancels(t *testing.T) { + parent, cancelParent := WithCancel(Background()) + child, cancelChild := WithCancel(parent) + go func() { + <-parent.Done() + cancelChild() + }() + cancelParent() + d := quiescent(t) + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-child.Done(): + case <-timer.C: + buf := make([]byte, 10<<10) + n := runtime.Stack(buf, true) + t.Fatalf("timed out after %v waiting for child.Done(); stacks:\n%s", d, buf[:n]) + } +} + +func TestLayersCancel(t *testing.T) { + testLayers(t, time.Now().UnixNano(), false) +} + +func TestLayersTimeout(t *testing.T) { + testLayers(t, time.Now().UnixNano(), true) +} + +func testLayers(t *testing.T, seed int64, testTimeout bool) { + t.Parallel() + + r := rand.New(rand.NewSource(seed)) + prefix := fmt.Sprintf("seed=%d", seed) + errorf := func(format string, a ...any) { + t.Errorf(prefix+format, a...) + } + const ( + minLayers = 30 + ) + type value int + var ( + vals []*value + cancels []CancelFunc + numTimers int + ctx = Background() + ) + for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { + switch r.Intn(3) { + case 0: + v := new(value) + ctx = WithValue(ctx, v, v) + vals = append(vals, v) + case 1: + var cancel CancelFunc + ctx, cancel = WithCancel(ctx) + cancels = append(cancels, cancel) + case 2: + var cancel CancelFunc + d := veryLongDuration + if testTimeout { + d = shortDuration + } + ctx, cancel = WithTimeout(ctx, d) + cancels = append(cancels, cancel) + numTimers++ + } + } + checkValues := func(when string) { + for _, key := range vals { + if val := ctx.Value(key).(*value); key != val { + errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) + } + } + } + if !testTimeout { + select { + case <-ctx.Done(): + errorf("ctx should not be canceled yet") + default: + } + } + if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { + t.Errorf("ctx.String() = %q want prefix %q", s, prefix) + } + t.Log(ctx) + checkValues("before cancel") + if testTimeout { + d := quiescent(t) + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + case <-timer.C: + errorf("ctx should have timed out after %v", d) + } + checkValues("after timeout") + } else { + cancel := cancels[r.Intn(len(cancels))] + cancel() + select { + case <-ctx.Done(): + default: + errorf("ctx should be canceled") + } + checkValues("after cancel") + } +} + +func TestWithCancelCanceledParent(t *testing.T) { + parent, pcancel := WithCancelCause(Background()) + cause := fmt.Errorf("Because!") + pcancel(cause) + + c, _ := WithCancel(parent) + select { + case <-c.Done(): + default: + t.Errorf("child not done immediately upon construction") + } + if got, want := c.Err(), Canceled; got != want { + t.Errorf("child not canceled; got = %v, want = %v", got, want) + } + if got, want := Cause(c), cause; got != want { + t.Errorf("child has wrong cause; got = %v, want = %v", got, want) + } +} + +func TestWithCancelSimultaneouslyCanceledParent(t *testing.T) { + // Cancel the parent goroutine concurrently with creating a child. + for i := 0; i < 100; i++ { + parent, pcancel := WithCancelCause(Background()) + cause := fmt.Errorf("Because!") + go pcancel(cause) + + c, _ := WithCancel(parent) + <-c.Done() + if got, want := c.Err(), Canceled; got != want { + t.Errorf("child not canceled; got = %v, want = %v", got, want) + } + if got, want := Cause(c), cause; got != want { + t.Errorf("child has wrong cause; got = %v, want = %v", got, want) + } + } +} + +func TestWithValueChecksKey(t *testing.T) { + panicVal := recoveredValue(func() { _ = WithValue(Background(), []byte("foo"), "bar") }) + if panicVal == nil { + t.Error("expected panic") + } + panicVal = recoveredValue(func() { _ = WithValue(Background(), nil, "bar") }) + if got, want := fmt.Sprint(panicVal), "nil key"; got != want { + t.Errorf("panic = %q; want %q", got, want) + } +} + +func TestInvalidDerivedFail(t *testing.T) { + panicVal := recoveredValue(func() { _, _ = WithCancel(nil) }) + if panicVal == nil { + t.Error("expected panic") + } + panicVal = recoveredValue(func() { _, _ = WithDeadline(nil, time.Now().Add(shortDuration)) }) + if panicVal == nil { + t.Error("expected panic") + } + panicVal = recoveredValue(func() { _ = WithValue(nil, "foo", "bar") }) + if panicVal == nil { + t.Error("expected panic") + } +} + +func recoveredValue(fn func()) (v any) { + defer func() { v = recover() }() + fn() + return +} + +func TestDeadlineExceededSupportsTimeout(t *testing.T) { + i, ok := DeadlineExceeded.(interface { + Timeout() bool + }) + if !ok { + t.Fatal("DeadlineExceeded does not support Timeout interface") + } + if !i.Timeout() { + t.Fatal("wrong value for timeout") + } +} +func TestCause(t *testing.T) { + var ( + forever = 1e6 * time.Second + parentCause = fmt.Errorf("parentCause") + childCause = fmt.Errorf("childCause") + tooSlow = fmt.Errorf("tooSlow") + finishedEarly = fmt.Errorf("finishedEarly") + ) + for _, test := range []struct { + name string + ctx func() Context + err error + cause error + }{ + { + name: "Background", + ctx: Background, + err: nil, + cause: nil, + }, + { + name: "TODO", + ctx: TODO, + err: nil, + cause: nil, + }, + { + name: "WithCancel", + ctx: func() Context { + ctx, cancel := WithCancel(Background()) + cancel() + return ctx + }, + err: Canceled, + cause: Canceled, + }, + { + name: "WithCancelCause", + ctx: func() Context { + ctx, cancel := WithCancelCause(Background()) + cancel(parentCause) + return ctx + }, + err: Canceled, + cause: parentCause, + }, + { + name: "WithCancelCause nil", + ctx: func() Context { + ctx, cancel := WithCancelCause(Background()) + cancel(nil) + return ctx + }, + err: Canceled, + cause: Canceled, + }, + { + name: "WithCancelCause: parent cause before child", + ctx: func() Context { + ctx, cancelParent := WithCancelCause(Background()) + ctx, cancelChild := WithCancelCause(ctx) + cancelParent(parentCause) + cancelChild(childCause) + return ctx + }, + err: Canceled, + cause: parentCause, + }, + { + name: "WithCancelCause: parent cause after child", + ctx: func() Context { + ctx, cancelParent := WithCancelCause(Background()) + ctx, cancelChild := WithCancelCause(ctx) + cancelChild(childCause) + cancelParent(parentCause) + return ctx + }, + err: Canceled, + cause: childCause, + }, + { + name: "WithCancelCause: parent cause before nil", + ctx: func() Context { + ctx, cancelParent := WithCancelCause(Background()) + ctx, cancelChild := WithCancel(ctx) + cancelParent(parentCause) + cancelChild() + return ctx + }, + err: Canceled, + cause: parentCause, + }, + { + name: "WithCancelCause: parent cause after nil", + ctx: func() Context { + ctx, cancelParent := WithCancelCause(Background()) + ctx, cancelChild := WithCancel(ctx) + cancelChild() + cancelParent(parentCause) + return ctx + }, + err: Canceled, + cause: Canceled, + }, + { + name: "WithCancelCause: child cause after nil", + ctx: func() Context { + ctx, cancelParent := WithCancel(Background()) + ctx, cancelChild := WithCancelCause(ctx) + cancelParent() + cancelChild(childCause) + return ctx + }, + err: Canceled, + cause: Canceled, + }, + { + name: "WithCancelCause: child cause before nil", + ctx: func() Context { + ctx, cancelParent := WithCancel(Background()) + ctx, cancelChild := WithCancelCause(ctx) + cancelChild(childCause) + cancelParent() + return ctx + }, + err: Canceled, + cause: childCause, + }, + { + name: "WithTimeout", + ctx: func() Context { + ctx, cancel := WithTimeout(Background(), 0) + cancel() + return ctx + }, + err: DeadlineExceeded, + cause: DeadlineExceeded, + }, + { + name: "WithTimeout canceled", + ctx: func() Context { + ctx, cancel := WithTimeout(Background(), forever) + cancel() + return ctx + }, + err: Canceled, + cause: Canceled, + }, + { + name: "WithTimeoutCause", + ctx: func() Context { + ctx, cancel := WithTimeoutCause(Background(), 0, tooSlow) + cancel() + return ctx + }, + err: DeadlineExceeded, + cause: tooSlow, + }, + { + name: "WithTimeoutCause canceled", + ctx: func() Context { + ctx, cancel := WithTimeoutCause(Background(), forever, tooSlow) + cancel() + return ctx + }, + err: Canceled, + cause: Canceled, + }, + { + name: "WithTimeoutCause stacked", + ctx: func() Context { + ctx, cancel := WithCancelCause(Background()) + ctx, _ = WithTimeoutCause(ctx, 0, tooSlow) + cancel(finishedEarly) + return ctx + }, + err: DeadlineExceeded, + cause: tooSlow, + }, + { + name: "WithTimeoutCause stacked canceled", + ctx: func() Context { + ctx, cancel := WithCancelCause(Background()) + ctx, _ = WithTimeoutCause(ctx, forever, tooSlow) + cancel(finishedEarly) + return ctx + }, + err: Canceled, + cause: finishedEarly, + }, + { + name: "WithoutCancel", + ctx: func() Context { + return WithoutCancel(Background()) + }, + err: nil, + cause: nil, + }, + { + name: "WithoutCancel canceled", + ctx: func() Context { + ctx, cancel := WithCancelCause(Background()) + ctx = WithoutCancel(ctx) + cancel(finishedEarly) + return ctx + }, + err: nil, + cause: nil, + }, + { + name: "WithoutCancel timeout", + ctx: func() Context { + ctx, cancel := WithTimeoutCause(Background(), 0, tooSlow) + ctx = WithoutCancel(ctx) + cancel() + return ctx + }, + err: nil, + cause: nil, + }, + { + name: "parent of custom context not canceled", + ctx: func() Context { + ctx, _ := WithCancelCause(Background()) + ctx, cancel2 := newCustomContext(ctx) + cancel2() + return ctx + }, + err: Canceled, + cause: Canceled, + }, + { + name: "parent of custom context is canceled before", + ctx: func() Context { + ctx, cancel1 := WithCancelCause(Background()) + ctx, cancel2 := newCustomContext(ctx) + cancel1(parentCause) + cancel2() + return ctx + }, + err: Canceled, + cause: parentCause, + }, + { + name: "parent of custom context is canceled after", + ctx: func() Context { + ctx, cancel1 := WithCancelCause(Background()) + ctx, cancel2 := newCustomContext(ctx) + cancel2() + cancel1(parentCause) + return ctx + }, + err: Canceled, + // This isn't really right: the child context was canceled before + // the parent context, and shouldn't inherit the parent's cause. + // However, since the child is a custom context, Cause has no way + // to tell which was canceled first and returns the parent's cause. + cause: parentCause, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + ctx := test.ctx() + if got, want := ctx.Err(), test.err; want != got { + t.Errorf("ctx.Err() = %v want %v", got, want) + } + if got, want := Cause(ctx), test.cause; want != got { + t.Errorf("Cause(ctx) = %v want %v", got, want) + } + }) + } +} + +func TestCauseRace(t *testing.T) { + cause := errors.New("TestCauseRace") + ctx, cancel := WithCancelCause(Background()) + go func() { + cancel(cause) + }() + for { + // Poll Cause, rather than waiting for Done, to test that + // access to the underlying cause is synchronized properly. + if err := Cause(ctx); err != nil { + if err != cause { + t.Errorf("Cause returned %v, want %v", err, cause) + } + break + } + runtime.Gosched() + } +} + +func TestWithoutCancel(t *testing.T) { + key, value := "key", "value" + ctx := WithValue(Background(), key, value) + ctx = WithoutCancel(ctx) + if d, ok := ctx.Deadline(); !d.IsZero() || ok != false { + t.Errorf("ctx.Deadline() = %v, %v want zero, false", d, ok) + } + if done := ctx.Done(); done != nil { + t.Errorf("ctx.Deadline() = %v want nil", done) + } + if err := ctx.Err(); err != nil { + t.Errorf("ctx.Err() = %v want nil", err) + } + if v := ctx.Value(key); v != value { + t.Errorf("ctx.Value(%q) = %q want %q", key, v, value) + } +} + +type customDoneContext struct { + Context + donec chan struct{} +} + +func (c *customDoneContext) Done() <-chan struct{} { + return c.donec +} + +func TestCustomContextPropagation(t *testing.T) { + cause := errors.New("TestCustomContextPropagation") + donec := make(chan struct{}) + ctx1, cancel1 := WithCancelCause(Background()) + ctx2 := &customDoneContext{ + Context: ctx1, + donec: donec, + } + ctx3, cancel3 := WithCancel(ctx2) + defer cancel3() + + cancel1(cause) + close(donec) + + <-ctx3.Done() + if got, want := ctx3.Err(), Canceled; got != want { + t.Errorf("child not canceled; got = %v, want = %v", got, want) + } + if got, want := Cause(ctx3), cause; got != want { + t.Errorf("child has wrong cause; got = %v, want = %v", got, want) + } +} + +// customCauseContext is a custom Context used to test context.Cause. +type customCauseContext struct { + mu sync.Mutex + done chan struct{} + err error + + cancelChild CancelFunc +} + +func (ccc *customCauseContext) Deadline() (deadline time.Time, ok bool) { + return +} + +func (ccc *customCauseContext) Done() <-chan struct{} { + ccc.mu.Lock() + defer ccc.mu.Unlock() + return ccc.done +} + +func (ccc *customCauseContext) Err() error { + ccc.mu.Lock() + defer ccc.mu.Unlock() + return ccc.err +} + +func (ccc *customCauseContext) Value(key any) any { + return nil +} + +func (ccc *customCauseContext) cancel() { + ccc.mu.Lock() + ccc.err = Canceled + close(ccc.done) + cancelChild := ccc.cancelChild + ccc.mu.Unlock() + + if cancelChild != nil { + cancelChild() + } +} + +func (ccc *customCauseContext) setCancelChild(cancelChild CancelFunc) { + ccc.cancelChild = cancelChild +} + +func TestCustomContextCause(t *testing.T) { + // Test if we cancel a custom context, Err and Cause return Canceled. + ccc := &customCauseContext{ + done: make(chan struct{}), + } + ccc.cancel() + if got := ccc.Err(); got != Canceled { + t.Errorf("ccc.Err() = %v, want %v", got, Canceled) + } + if got := Cause(ccc); got != Canceled { + t.Errorf("Cause(ccc) = %v, want %v", got, Canceled) + } + + // Test that if we pass a custom context to WithCancelCause, + // and then cancel that child context with a cause, + // that the cause of the child canceled context is correct + // but that the parent custom context is not canceled. + ccc = &customCauseContext{ + done: make(chan struct{}), + } + ctx, causeFunc := WithCancelCause(ccc) + cause := errors.New("TestCustomContextCause") + causeFunc(cause) + if got := ctx.Err(); got != Canceled { + t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled) + } + if got := Cause(ctx); got != cause { + t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, cause) + } + if got := ccc.Err(); got != nil { + t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, nil) + } + if got := Cause(ccc); got != nil { + t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, nil) + } + + // Test that if we now cancel the parent custom context, + // the cause of the child canceled context is still correct, + // and the parent custom context is canceled without a cause. + ccc.cancel() + if got := ctx.Err(); got != Canceled { + t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled) + } + if got := Cause(ctx); got != cause { + t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, cause) + } + if got := ccc.Err(); got != Canceled { + t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, Canceled) + } + if got := Cause(ccc); got != Canceled { + t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, Canceled) + } + + // Test that if we associate a custom context with a child, + // then canceling the custom context cancels the child. + ccc = &customCauseContext{ + done: make(chan struct{}), + } + ctx, cancelFunc := WithCancel(ccc) + ccc.setCancelChild(cancelFunc) + ccc.cancel() + if got := ctx.Err(); got != Canceled { + t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled) + } + if got := Cause(ctx); got != Canceled { + t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, Canceled) + } + if got := ccc.Err(); got != Canceled { + t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, Canceled) + } + if got := Cause(ccc); got != Canceled { + t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, Canceled) + } +} + +func TestAfterFuncCalledAfterCancel(t *testing.T) { + ctx, cancel := WithCancel(Background()) + donec := make(chan struct{}) + stop := AfterFunc(ctx, func() { + close(donec) + }) + select { + case <-donec: + t.Fatalf("AfterFunc called before context is done") + case <-time.After(shortDuration): + } + cancel() + select { + case <-donec: + case <-time.After(veryLongDuration): + t.Fatalf("AfterFunc not called after context is canceled") + } + if stop() { + t.Fatalf("stop() = true, want false") + } +} + +func TestAfterFuncCalledAfterTimeout(t *testing.T) { + ctx, cancel := WithTimeout(Background(), shortDuration) + defer cancel() + donec := make(chan struct{}) + AfterFunc(ctx, func() { + close(donec) + }) + select { + case <-donec: + case <-time.After(veryLongDuration): + t.Fatalf("AfterFunc not called after context is canceled") + } +} + +func TestAfterFuncCalledImmediately(t *testing.T) { + ctx, cancel := WithCancel(Background()) + cancel() + donec := make(chan struct{}) + AfterFunc(ctx, func() { + close(donec) + }) + select { + case <-donec: + case <-time.After(veryLongDuration): + t.Fatalf("AfterFunc not called for already-canceled context") + } +} + +func TestAfterFuncNotCalledAfterStop(t *testing.T) { + ctx, cancel := WithCancel(Background()) + donec := make(chan struct{}) + stop := AfterFunc(ctx, func() { + close(donec) + }) + if !stop() { + t.Fatalf("stop() = false, want true") + } + cancel() + select { + case <-donec: + t.Fatalf("AfterFunc called for already-canceled context") + case <-time.After(shortDuration): + } + if stop() { + t.Fatalf("stop() = true, want false") + } +} + +// This test verifies that canceling a context does not block waiting for AfterFuncs to finish. +func TestAfterFuncCalledAsynchronously(t *testing.T) { + ctx, cancel := WithCancel(Background()) + donec := make(chan struct{}) + stop := AfterFunc(ctx, func() { + // The channel send blocks until donec is read from. + donec <- struct{}{} + }) + defer stop() + cancel() + // After cancel returns, read from donec and unblock the AfterFunc. + select { + case <-donec: + case <-time.After(veryLongDuration): + t.Fatalf("AfterFunc not called after context is canceled") + } +} + +// customContext is a custom Context implementation. +type customContext struct { + parent Context + + doneOnce sync.Once + donec chan struct{} + err error +} + +func newCustomContext(parent Context) (Context, CancelFunc) { + c := &customContext{ + parent: parent, + donec: make(chan struct{}), + } + AfterFunc(parent, func() { + c.doneOnce.Do(func() { + c.err = parent.Err() + close(c.donec) + }) + }) + return c, func() { + c.doneOnce.Do(func() { + c.err = Canceled + close(c.donec) + }) + } +} + +func (c *customContext) Deadline() (time.Time, bool) { + return c.parent.Deadline() +} + +func (c *customContext) Done() <-chan struct{} { + return c.donec +} + +func (c *customContext) Err() error { + select { + case <-c.donec: + return c.err + default: + return nil + } +} + +func (c *customContext) Value(key any) any { + return c.parent.Value(key) +} + +// Issue #75533. +func TestContextErrDoneRace(t *testing.T) { + // 4 iterations reliably reproduced #75533. + for range 10 { + ctx, cancel := WithCancel(Background()) + donec := ctx.Done() + go cancel() + for ctx.Err() == nil { + if runtime.GOARCH == "wasm" { + runtime.Gosched() // need to explicitly yield + } + } + select { + case <-donec: + default: + t.Fatalf("ctx.Err is non-nil, but ctx.Done is not closed") + } + } +} diff --git a/go/src/crypto/crypto.go b/go/src/crypto/crypto.go new file mode 100644 index 0000000000000000000000000000000000000000..0bf9ec834b7d910f23990e133b6caeea5c575012 --- /dev/null +++ b/go/src/crypto/crypto.go @@ -0,0 +1,273 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package crypto collects common cryptographic constants. +package crypto + +import ( + "hash" + "io" + "strconv" +) + +// Hash identifies a cryptographic hash function that is implemented in another +// package. +type Hash uint + +// HashFunc simply returns the value of h so that [Hash] implements [SignerOpts]. +func (h Hash) HashFunc() Hash { + return h +} + +func (h Hash) String() string { + switch h { + case MD4: + return "MD4" + case MD5: + return "MD5" + case SHA1: + return "SHA-1" + case SHA224: + return "SHA-224" + case SHA256: + return "SHA-256" + case SHA384: + return "SHA-384" + case SHA512: + return "SHA-512" + case MD5SHA1: + return "MD5+SHA1" + case RIPEMD160: + return "RIPEMD-160" + case SHA3_224: + return "SHA3-224" + case SHA3_256: + return "SHA3-256" + case SHA3_384: + return "SHA3-384" + case SHA3_512: + return "SHA3-512" + case SHA512_224: + return "SHA-512/224" + case SHA512_256: + return "SHA-512/256" + case BLAKE2s_256: + return "BLAKE2s-256" + case BLAKE2b_256: + return "BLAKE2b-256" + case BLAKE2b_384: + return "BLAKE2b-384" + case BLAKE2b_512: + return "BLAKE2b-512" + default: + return "unknown hash value " + strconv.Itoa(int(h)) + } +} + +const ( + MD4 Hash = 1 + iota // import golang.org/x/crypto/md4 + MD5 // import crypto/md5 + SHA1 // import crypto/sha1 + SHA224 // import crypto/sha256 + SHA256 // import crypto/sha256 + SHA384 // import crypto/sha512 + SHA512 // import crypto/sha512 + MD5SHA1 // no implementation; MD5+SHA1 used for TLS RSA + RIPEMD160 // import golang.org/x/crypto/ripemd160 + SHA3_224 // import crypto/sha3 + SHA3_256 // import crypto/sha3 + SHA3_384 // import crypto/sha3 + SHA3_512 // import crypto/sha3 + SHA512_224 // import crypto/sha512 + SHA512_256 // import crypto/sha512 + BLAKE2s_256 // import golang.org/x/crypto/blake2s + BLAKE2b_256 // import golang.org/x/crypto/blake2b + BLAKE2b_384 // import golang.org/x/crypto/blake2b + BLAKE2b_512 // import golang.org/x/crypto/blake2b + maxHash +) + +var digestSizes = []uint8{ + MD4: 16, + MD5: 16, + SHA1: 20, + SHA224: 28, + SHA256: 32, + SHA384: 48, + SHA512: 64, + SHA512_224: 28, + SHA512_256: 32, + SHA3_224: 28, + SHA3_256: 32, + SHA3_384: 48, + SHA3_512: 64, + MD5SHA1: 36, + RIPEMD160: 20, + BLAKE2s_256: 32, + BLAKE2b_256: 32, + BLAKE2b_384: 48, + BLAKE2b_512: 64, +} + +// Size returns the length, in bytes, of a digest resulting from the given hash +// function. It doesn't require that the hash function in question be linked +// into the program. +func (h Hash) Size() int { + if h > 0 && h < maxHash { + return int(digestSizes[h]) + } + panic("crypto: Size of unknown hash function") +} + +var hashes = make([]func() hash.Hash, maxHash) + +// New returns a new hash.Hash calculating the given hash function. New panics +// if the hash function is not linked into the binary. +func (h Hash) New() hash.Hash { + if h > 0 && h < maxHash { + f := hashes[h] + if f != nil { + return f() + } + } + panic("crypto: requested hash function #" + strconv.Itoa(int(h)) + " is unavailable") +} + +// Available reports whether the given hash function is linked into the binary. +func (h Hash) Available() bool { + return h < maxHash && hashes[h] != nil +} + +// RegisterHash registers a function that returns a new instance of the given +// hash function. This is intended to be called from the init function in +// packages that implement hash functions. +func RegisterHash(h Hash, f func() hash.Hash) { + if h >= maxHash { + panic("crypto: RegisterHash of unknown hash function") + } + hashes[h] = f +} + +// PublicKey represents a public key using an unspecified algorithm. +// +// Although this type is an empty interface for backwards compatibility reasons, +// all public key types in the standard library implement the following interface +// +// interface{ +// Equal(x crypto.PublicKey) bool +// } +// +// which can be used for increased type safety within applications. +type PublicKey any + +// PrivateKey represents a private key using an unspecified algorithm. +// +// Although this type is an empty interface for backwards compatibility reasons, +// all private key types in the standard library implement the following interface +// +// interface{ +// Public() crypto.PublicKey +// Equal(x crypto.PrivateKey) bool +// } +// +// as well as purpose-specific interfaces such as [Signer] and [Decrypter], which +// can be used for increased type safety within applications. +type PrivateKey any + +// Signer is an interface for an opaque private key that can be used for +// signing operations. For example, an RSA key kept in a hardware module. +type Signer interface { + // Public returns the public key corresponding to the opaque, + // private key. + Public() PublicKey + + // Sign signs digest with the private key, possibly using entropy from + // rand. For an RSA key, the resulting signature should be either a + // PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA + // key, it should be a DER-serialised, ASN.1 signature structure. + // + // Hash implements the SignerOpts interface and, in most cases, one can + // simply pass in the hash function used as opts. Sign may also attempt + // to type assert opts to other types in order to obtain algorithm + // specific values. See the documentation in each package for details. + // + // Note that when a signature of a hash of a larger message is needed, + // the caller is responsible for hashing the larger message and passing + // the hash (as digest) and the hash function (as opts) to Sign. + Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error) +} + +// MessageSigner is an interface for an opaque private key that can be used for +// signing operations where the message is not pre-hashed by the caller. +// It is a superset of the Signer interface so that it can be passed to APIs +// which accept Signer, which may try to do an interface upgrade. +// +// MessageSigner.SignMessage and MessageSigner.Sign should produce the same +// result given the same opts. In particular, MessageSigner.SignMessage should +// only accept a zero opts.HashFunc if the Signer would also accept messages +// which are not pre-hashed. +// +// Implementations which do not provide the pre-hashed Sign API should implement +// Signer.Sign by always returning an error. +type MessageSigner interface { + Signer + SignMessage(rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error) +} + +// SignerOpts contains options for signing with a [Signer]. +type SignerOpts interface { + // HashFunc returns an identifier for the hash function used to produce + // the message passed to Signer.Sign, or else zero to indicate that no + // hashing was done. + HashFunc() Hash +} + +// Decrypter is an interface for an opaque private key that can be used for +// asymmetric decryption operations. An example would be an RSA key +// kept in a hardware module. +type Decrypter interface { + // Public returns the public key corresponding to the opaque, + // private key. + Public() PublicKey + + // Decrypt decrypts msg. The opts argument should be appropriate for + // the primitive used. See the documentation in each implementation for + // details. + Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error) +} + +type DecrypterOpts any + +// SignMessage signs msg with signer. If signer implements [MessageSigner], +// [MessageSigner.SignMessage] is called directly. Otherwise, msg is hashed +// with opts.HashFunc() and signed with [Signer.Sign]. +func SignMessage(signer Signer, rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error) { + if ms, ok := signer.(MessageSigner); ok { + return ms.SignMessage(rand, msg, opts) + } + if opts.HashFunc() != 0 { + h := opts.HashFunc().New() + h.Write(msg) + msg = h.Sum(nil) + } + return signer.Sign(rand, msg, opts) +} + +// Decapsulator is an interface for an opaque private KEM key that can be used for +// decapsulation operations. For example, an ML-KEM key kept in a hardware module. +// +// It is implemented, for example, by [crypto/mlkem.DecapsulationKey768]. +type Decapsulator interface { + Encapsulator() Encapsulator + Decapsulate(ciphertext []byte) (sharedKey []byte, err error) +} + +// Encapsulator is an interface for a public KEM key that can be used for +// encapsulation operations. +// +// It is implemented, for example, by [crypto/mlkem.EncapsulationKey768]. +type Encapsulator interface { + Bytes() []byte + Encapsulate() (sharedKey, ciphertext []byte) +} diff --git a/go/src/crypto/crypto_test.go b/go/src/crypto/crypto_test.go new file mode 100644 index 0000000000000000000000000000000000000000..66babcc2fb0d05bf7f4a985cb5ba9256239783f1 --- /dev/null +++ b/go/src/crypto/crypto_test.go @@ -0,0 +1,143 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package crypto_test + +import ( + "bytes" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" + "internal/testenv" + "io" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +type messageSignerOnly struct { + k *rsa.PrivateKey +} + +func (s *messageSignerOnly) Public() crypto.PublicKey { + return s.k.Public() +} + +func (s *messageSignerOnly) Sign(_ io.Reader, _ []byte, _ crypto.SignerOpts) ([]byte, error) { + return nil, errors.New("unimplemented") +} + +func (s *messageSignerOnly) SignMessage(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { + h := opts.HashFunc().New() + h.Write(msg) + digest := h.Sum(nil) + return s.k.Sign(rand, digest, opts) +} + +func TestSignMessage(t *testing.T) { + block, _ := pem.Decode([]byte(strings.ReplaceAll( + `-----BEGIN RSA TESTING KEY----- +MIIEowIBAAKCAQEAsPnoGUOnrpiSqt4XynxA+HRP7S+BSObI6qJ7fQAVSPtRkqso +tWxQYLEYzNEx5ZSHTGypibVsJylvCfuToDTfMul8b/CZjP2Ob0LdpYrNH6l5hvFE +89FU1nZQF15oVLOpUgA7wGiHuEVawrGfey92UE68mOyUVXGweJIVDdxqdMoPvNNU +l86BU02vlBiESxOuox+dWmuVV7vfYZ79Toh/LUK43YvJh+rhv4nKuF7iHjVjBd9s +B6iDjj70HFldzOQ9r8SRI+9NirupPTkF5AKNe6kUhKJ1luB7S27ZkvB3tSTT3P59 +3VVJvnzOjaA1z6Cz+4+eRvcysqhrRgFlwI9TEwIDAQABAoIBAEEYiyDP29vCzx/+ +dS3LqnI5BjUuJhXUnc6AWX/PCgVAO+8A+gZRgvct7PtZb0sM6P9ZcLrweomlGezI +FrL0/6xQaa8bBr/ve/a8155OgcjFo6fZEw3Dz7ra5fbSiPmu4/b/kvrg+Br1l77J +aun6uUAs1f5B9wW+vbR7tzbT/mxaUeDiBzKpe15GwcvbJtdIVMa2YErtRjc1/5B2 +BGVXyvlJv0SIlcIEMsHgnAFOp1ZgQ08aDzvilLq8XVMOahAhP1O2A3X8hKdXPyrx +IVWE9bS9ptTo+eF6eNl+d7htpKGEZHUxinoQpWEBTv+iOoHsVunkEJ3vjLP3lyI/ +fY0NQ1ECgYEA3RBXAjgvIys2gfU3keImF8e/TprLge1I2vbWmV2j6rZCg5r/AS0u +pii5CvJ5/T5vfJPNgPBy8B/yRDs+6PJO1GmnlhOkG9JAIPkv0RBZvR0PMBtbp6nT +Y3yo1lwamBVBfY6rc0sLTzosZh2aGoLzrHNMQFMGaauORzBFpY5lU50CgYEAzPHl +u5DI6Xgep1vr8QvCUuEesCOgJg8Yh1UqVoY/SmQh6MYAv1I9bLGwrb3WW/7kqIoD +fj0aQV5buVZI2loMomtU9KY5SFIsPV+JuUpy7/+VE01ZQM5FdY8wiYCQiVZYju9X +Wz5LxMNoz+gT7pwlLCsC4N+R8aoBk404aF1gum8CgYAJ7VTq7Zj4TFV7Soa/T1eE +k9y8a+kdoYk3BASpCHJ29M5R2KEA7YV9wrBklHTz8VzSTFTbKHEQ5W5csAhoL5Fo +qoHzFFi3Qx7MHESQb9qHyolHEMNx6QdsHUn7rlEnaTTyrXh3ifQtD6C0yTmFXUIS +CW9wKApOrnyKJ9nI0HcuZQKBgQCMtoV6e9VGX4AEfpuHvAAnMYQFgeBiYTkBKltQ +XwozhH63uMMomUmtSG87Sz1TmrXadjAhy8gsG6I0pWaN7QgBuFnzQ/HOkwTm+qKw +AsrZt4zeXNwsH7QXHEJCFnCmqw9QzEoZTrNtHJHpNboBuVnYcoueZEJrP8OnUG3r +UjmopwKBgAqB2KYYMUqAOvYcBnEfLDmyZv9BTVNHbR2lKkMYqv5LlvDaBxVfilE0 +2riO4p6BaAdvzXjKeRrGNEKoHNBpOSfYCOM16NjL8hIZB1CaV3WbT5oY+jp7Mzd5 +7d56RZOE+ERK2uz/7JX9VSsM/LbH9pJibd4e8mikDS9ntciqOH/3 +-----END RSA TESTING KEY-----`, "TESTING KEY", "PRIVATE KEY"))) + k, _ := x509.ParsePKCS1PrivateKey(block.Bytes) + + msg := []byte("hello :)") + + h := crypto.SHA256.New() + h.Write(msg) + digest := h.Sum(nil) + + sig, err := crypto.SignMessage(k, rand.Reader, msg, &rsa.PSSOptions{Hash: crypto.SHA256}) + if err != nil { + t.Fatalf("SignMessage failed with Signer: %s", err) + } + if err := rsa.VerifyPSS(&k.PublicKey, crypto.SHA256, digest, sig, nil); err != nil { + t.Errorf("VerifyPSS failed for Signer signature: %s", err) + } + + sig, err = crypto.SignMessage(&messageSignerOnly{k}, rand.Reader, msg, &rsa.PSSOptions{Hash: crypto.SHA256}) + if err != nil { + t.Fatalf("SignMessage failed with MessageSigner: %s", err) + } + if err := rsa.VerifyPSS(&k.PublicKey, crypto.SHA256, digest, sig, nil); err != nil { + t.Errorf("VerifyPSS failed for MessageSigner signature: %s", err) + } +} + +func TestDisallowedAssemblyInstructions(t *testing.T) { + // This test enforces the cryptography assembly policy rule that we do not + // use BYTE or WORD instructions, since these instructions can obscure what + // the assembly is actually doing. If we do not support specific + // instructions in the assembler, we should not be using them until we do. + // + // Instead of using the output of the 'go tool asm' tool, we take the simple + // approach and just search the text of .s files for usage of BYTE and WORD. + // We do this because the assembler itself will sometimes insert WORD + // instructions for things like function preambles etc. + + boringSigPath := filepath.Join("internal", "boring", "sig") + + matcher, err := regexp.Compile(`(^|;)\s(BYTE|WORD)\s`) + if err != nil { + t.Fatal(err) + } + if err := filepath.WalkDir(filepath.Join(testenv.GOROOT(t), "src/crypto"), func(path string, d fs.DirEntry, err error) error { + if err != nil { + t.Fatal(err) + } + if d.IsDir() || !strings.HasSuffix(path, ".s") { + return nil + } + if strings.Contains(path, boringSigPath) { + return nil + } + + f, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + + i := 1 + for line := range bytes.Lines(f) { + if matcher.Match(line) { + t.Errorf("%s:%d assembly contains BYTE or WORD instruction (%q)", path, i, string(line)) + } + i++ + } + + return nil + }); err != nil { + t.Fatal(err) + } +} diff --git a/go/src/crypto/issue21104_test.go b/go/src/crypto/issue21104_test.go new file mode 100644 index 0000000000000000000000000000000000000000..466208879991e1a12ecf92d34b53d71885ed1b08 --- /dev/null +++ b/go/src/crypto/issue21104_test.go @@ -0,0 +1,61 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package crypto_test + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rc4" + "testing" +) + +func TestRC4OutOfBoundsWrite(t *testing.T) { + // This cipherText is encrypted "0123456789" + cipherText := []byte{238, 41, 187, 114, 151, 2, 107, 13, 178, 63} + cipher, err := rc4.NewCipher([]byte{0}) + if err != nil { + panic(err) + } + test(t, "RC4", cipherText, cipher.XORKeyStream) +} +func TestCTROutOfBoundsWrite(t *testing.T) { + testBlock(t, "CTR", cipher.NewCTR) +} +func TestOFBOutOfBoundsWrite(t *testing.T) { + testBlock(t, "OFB", cipher.NewOFB) +} +func TestCFBEncryptOutOfBoundsWrite(t *testing.T) { + testBlock(t, "CFB Encrypt", cipher.NewCFBEncrypter) +} +func TestCFBDecryptOutOfBoundsWrite(t *testing.T) { + testBlock(t, "CFB Decrypt", cipher.NewCFBDecrypter) +} +func testBlock(t *testing.T, name string, newCipher func(cipher.Block, []byte) cipher.Stream) { + // This cipherText is encrypted "0123456789" + cipherText := []byte{86, 216, 121, 231, 219, 191, 26, 12, 176, 117} + var iv, key [16]byte + block, err := aes.NewCipher(key[:]) + if err != nil { + panic(err) + } + stream := newCipher(block, iv[:]) + test(t, name, cipherText, stream.XORKeyStream) +} +func test(t *testing.T, name string, cipherText []byte, xor func([]byte, []byte)) { + want := "abcdefghij" + plainText := []byte(want) + shorterLen := len(cipherText) / 2 + defer func() { + err := recover() + if err == nil { + t.Errorf("%v XORKeyStream expected to panic on len(dst) < len(src), but didn't", name) + } + const plain = "0123456789" + if plainText[shorterLen] == plain[shorterLen] { + t.Errorf("%v XORKeyStream did out of bounds write, want %v, got %v", name, want, string(plainText)) + } + }() + xor(plainText[:shorterLen], cipherText) +} diff --git a/go/src/crypto/purego_test.go b/go/src/crypto/purego_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ebc9110cecee82bcaea66d2a95987f309a36e633 --- /dev/null +++ b/go/src/crypto/purego_test.go @@ -0,0 +1,67 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package crypto_test + +import ( + "go/build" + "internal/testenv" + "log" + "os" + "strings" + "testing" +) + +// TestPureGoTag checks that when built with the purego build tag, crypto +// packages don't require any assembly. This is used by alternative compilers +// such as TinyGo. See also the "crypto/...:purego" test in cmd/dist, which +// ensures the packages build correctly. +func TestPureGoTag(t *testing.T) { + cmd := testenv.Command(t, testenv.GoToolPath(t), "list", "-e", "crypto/...", "math/big") + cmd = testenv.CleanCmdEnv(cmd) + cmd.Env = append(cmd.Environ(), "GOOS=linux", "GOFIPS140=off") + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + log.Fatalf("loading package list: %v\n%s", err, out) + } + pkgs := strings.Split(strings.TrimSpace(string(out)), "\n") + + cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "dist", "list") + cmd.Stderr = os.Stderr + out, err = testenv.CleanCmdEnv(cmd).Output() + if err != nil { + log.Fatalf("loading architecture list: %v\n%s", err, out) + } + allGOARCH := make(map[string]bool) + for _, pair := range strings.Split(strings.TrimSpace(string(out)), "\n") { + GOARCH := strings.Split(pair, "/")[1] + allGOARCH[GOARCH] = true + } + + for _, pkgName := range pkgs { + if strings.Contains(pkgName, "/boring") { + continue + } + + for GOARCH := range allGOARCH { + context := build.Context{ + GOOS: "linux", // darwin has custom assembly + GOARCH: GOARCH, + GOROOT: testenv.GOROOT(t), + Compiler: build.Default.Compiler, + BuildTags: []string{"purego", "math_big_pure_go"}, + } + + pkg, err := context.Import(pkgName, "", 0) + if err != nil { + t.Fatal(err) + } + if len(pkg.SFiles) == 0 { + continue + } + t.Errorf("package %s has purego assembly files on %s: %v", pkgName, GOARCH, pkg.SFiles) + } + } +} diff --git a/go/src/embed/embed.go b/go/src/embed/embed.go new file mode 100644 index 0000000000000000000000000000000000000000..4d5e418c9024b338171a204839023e3a0d2d6771 --- /dev/null +++ b/go/src/embed/embed.go @@ -0,0 +1,436 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package embed provides access to files embedded in the running Go program. +// +// Go source files that import "embed" can use the //go:embed directive +// to initialize a variable of type string, []byte, or [FS] with the contents of +// files read from the package directory or subdirectories at compile time. +// +// For example, here are three ways to embed a file named hello.txt +// and then print its contents at run time. +// +// Embedding one file into a string: +// +// import _ "embed" +// +// //go:embed hello.txt +// var s string +// print(s) +// +// Embedding one file into a slice of bytes: +// +// import _ "embed" +// +// //go:embed hello.txt +// var b []byte +// print(string(b)) +// +// Embedded one or more files into a file system: +// +// import "embed" +// +// //go:embed hello.txt +// var f embed.FS +// data, _ := f.ReadFile("hello.txt") +// print(string(data)) +// +// # Directives +// +// A //go:embed directive above a variable declaration specifies which files to embed, +// using one or more path.Match patterns. +// +// The directive must immediately precede a line containing the declaration of a single variable. +// Only blank lines and ‘//’ line comments are permitted between the directive and the declaration. +// +// The type of the variable must be a string type, or a slice of a byte type, +// or [FS] (or an alias of [FS]). +// +// For example: +// +// package server +// +// import "embed" +// +// // content holds our static web server content. +// //go:embed image/* template/* +// //go:embed html/index.html +// var content embed.FS +// +// The Go build system will recognize the directives and arrange for the declared variable +// (in the example above, content) to be populated with the matching files from the file system. +// +// The //go:embed directive accepts multiple space-separated patterns for +// brevity, but it can also be repeated, to avoid very long lines when there are +// many patterns. The patterns are interpreted relative to the package directory +// containing the source file. The path separator is a forward slash, even on +// Windows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements, +// nor may they begin or end with a slash. To match everything in the current +// directory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in +// their names, patterns can be written as Go double-quoted or back-quoted +// string literals. +// +// If a pattern names a directory, all files in the subtree rooted at that directory are +// embedded (recursively), except that files with names beginning with ‘.’ or ‘_’ +// are excluded. So the variable in the above example is almost equivalent to: +// +// // content is our static web server content. +// //go:embed image template html/index.html +// var content embed.FS +// +// The difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not. +// Neither embeds ‘image/dir/.tempfile’. +// +// If a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed +// to include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds +// both ‘image/.tempfile’ and ‘image/dir/.tempfile’. +// +// The //go:embed directive can be used with both exported and unexported variables, +// depending on whether the package wants to make the data available to other packages. +// It can only be used with variables at package scope, not with local variables. +// +// Patterns must not match files outside the package's module, such as ‘.git/*’, symbolic links, +// 'vendor/', or any directories containing go.mod (these are separate modules). +// Patterns must not match files whose names include the special punctuation characters " * < > ? ` ' | / \ and :. +// Matches for empty directories are ignored. After that, each pattern in a //go:embed line +// must match at least one file or non-empty directory. +// +// If any patterns are invalid or have invalid matches, the build will fail. +// +// # Strings and Bytes +// +// The //go:embed line for a variable of type string or []byte can have only a single pattern, +// and that pattern can match only a single file. The string or []byte is initialized with +// the contents of that file. +// +// The //go:embed directive requires importing "embed", even when using a string or []byte. +// In source files that don't refer to [embed.FS], use a blank import (import _ "embed"). +// +// # File Systems +// +// For embedding a single file, a variable of type string or []byte is often best. +// The [FS] type enables embedding a tree of files, such as a directory of static +// web server content, as in the example above. +// +// FS implements the [io/fs] package's [FS] interface, so it can be used with any package that +// understands file systems, including [net/http], [text/template], and [html/template]. +// +// For example, given the content variable in the example above, we can write: +// +// http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content)))) +// +// template.ParseFS(content, "*.tmpl") +// +// # Tools +// +// To support tools that analyze Go packages, the patterns found in //go:embed lines +// are available in “go list” output. See the EmbedPatterns, TestEmbedPatterns, +// and XTestEmbedPatterns fields in the “go help list” output. +package embed + +import ( + "errors" + "internal/bytealg" + "internal/stringslite" + "io" + "io/fs" + "time" +) + +// An FS is a read-only collection of files, usually initialized with a //go:embed directive. +// When declared without a //go:embed directive, an FS is an empty file system. +// +// An FS is a read-only value, so it is safe to use from multiple goroutines +// simultaneously and also safe to assign values of type FS to each other. +// +// FS implements fs.FS, so it can be used with any package that understands +// file system interfaces, including net/http, text/template, and html/template. +// +// See the package documentation for more details about initializing an FS. +type FS struct { + // The compiler knows the layout of this struct. + // See cmd/compile/internal/staticdata's WriteEmbed. + // + // The files list is sorted by name but not by simple string comparison. + // Instead, each file's name takes the form "dir/elem" or "dir/elem/". + // The optional trailing slash indicates that the file is itself a directory. + // The files list is sorted first by dir (if dir is missing, it is taken to be ".") + // and then by base, so this list of files: + // + // p + // q/ + // q/r + // q/s/ + // q/s/t + // q/s/u + // q/v + // w + // + // is actually sorted as: + // + // p # dir=. elem=p + // q/ # dir=. elem=q + // w # dir=. elem=w + // q/r # dir=q elem=r + // q/s/ # dir=q elem=s + // q/v # dir=q elem=v + // q/s/t # dir=q/s elem=t + // q/s/u # dir=q/s elem=u + // + // This order brings directory contents together in contiguous sections + // of the list, allowing a directory read to use binary search to find + // the relevant sequence of entries. + files *[]file +} + +// split splits the name into dir and elem as described in the +// comment in the FS struct above. isDir reports whether the +// final trailing slash was present, indicating that name is a directory. +func split(name string) (dir, elem string, isDir bool) { + name, isDir = stringslite.CutSuffix(name, "/") + i := bytealg.LastIndexByteString(name, '/') + if i < 0 { + return ".", name, isDir + } + return name[:i], name[i+1:], isDir +} + +var ( + _ fs.ReadDirFS = FS{} + _ fs.ReadFileFS = FS{} +) + +// A file is a single file in the FS. +// It implements fs.FileInfo and fs.DirEntry. +type file struct { + // The compiler knows the layout of this struct. + // See cmd/compile/internal/staticdata's WriteEmbed. + name string + data string + hash [16]byte // truncated SHA256 hash +} + +var ( + _ fs.FileInfo = (*file)(nil) + _ fs.DirEntry = (*file)(nil) +) + +func (f *file) Name() string { _, elem, _ := split(f.name); return elem } +func (f *file) Size() int64 { return int64(len(f.data)) } +func (f *file) ModTime() time.Time { return time.Time{} } +func (f *file) IsDir() bool { _, _, isDir := split(f.name); return isDir } +func (f *file) Sys() any { return nil } +func (f *file) Type() fs.FileMode { return f.Mode().Type() } +func (f *file) Info() (fs.FileInfo, error) { return f, nil } + +func (f *file) Mode() fs.FileMode { + if f.IsDir() { + return fs.ModeDir | 0555 + } + return 0444 +} + +func (f *file) String() string { + return fs.FormatFileInfo(f) +} + +// dotFile is a file for the root directory, +// which is omitted from the files list in a FS. +var dotFile = &file{name: "./"} + +// lookup returns the named file, or nil if it is not present. +func (f FS) lookup(name string) *file { + if !fs.ValidPath(name) { + // The compiler should never emit a file with an invalid name, + // so this check is not strictly necessary (if name is invalid, + // we shouldn't find a match below), but it's a good backstop anyway. + return nil + } + if name == "." { + return dotFile + } + if f.files == nil { + return nil + } + + // Binary search to find where name would be in the list, + // and then check if name is at that position. + dir, elem, _ := split(name) + files := *f.files + i := sortSearch(len(files), func(i int) bool { + idir, ielem, _ := split(files[i].name) + return idir > dir || idir == dir && ielem >= elem + }) + if i < len(files) && stringslite.TrimSuffix(files[i].name, "/") == name { + return &files[i] + } + return nil +} + +// readDir returns the list of files corresponding to the directory dir. +func (f FS) readDir(dir string) []file { + if f.files == nil { + return nil + } + // Binary search to find where dir starts and ends in the list + // and then return that slice of the list. + files := *f.files + i := sortSearch(len(files), func(i int) bool { + idir, _, _ := split(files[i].name) + return idir >= dir + }) + j := sortSearch(len(files), func(j int) bool { + jdir, _, _ := split(files[j].name) + return jdir > dir + }) + return files[i:j] +} + +// Open opens the named file for reading and returns it as an [fs.File]. +// +// The returned file implements [io.Seeker] and [io.ReaderAt] when the file is not a directory. +func (f FS) Open(name string) (fs.File, error) { + file := f.lookup(name) + if file == nil { + return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist} + } + if file.IsDir() { + return &openDir{file, f.readDir(name), 0}, nil + } + return &openFile{file, 0}, nil +} + +// ReadDir reads and returns the entire named directory. +func (f FS) ReadDir(name string) ([]fs.DirEntry, error) { + file, err := f.Open(name) + if err != nil { + return nil, err + } + dir, ok := file.(*openDir) + if !ok { + return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("not a directory")} + } + list := make([]fs.DirEntry, len(dir.files)) + for i := range list { + list[i] = &dir.files[i] + } + return list, nil +} + +// ReadFile reads and returns the content of the named file. +func (f FS) ReadFile(name string) ([]byte, error) { + file, err := f.Open(name) + if err != nil { + return nil, err + } + ofile, ok := file.(*openFile) + if !ok { + return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("is a directory")} + } + return []byte(ofile.f.data), nil +} + +// An openFile is a regular file open for reading. +type openFile struct { + f *file // the file itself + offset int64 // current read offset +} + +var ( + _ io.Seeker = (*openFile)(nil) + _ io.ReaderAt = (*openFile)(nil) +) + +func (f *openFile) Close() error { return nil } +func (f *openFile) Stat() (fs.FileInfo, error) { return f.f, nil } + +func (f *openFile) Read(b []byte) (int, error) { + if f.offset >= int64(len(f.f.data)) { + return 0, io.EOF + } + if f.offset < 0 { + return 0, &fs.PathError{Op: "read", Path: f.f.name, Err: fs.ErrInvalid} + } + n := copy(b, f.f.data[f.offset:]) + f.offset += int64(n) + return n, nil +} + +func (f *openFile) Seek(offset int64, whence int) (int64, error) { + switch whence { + case 0: + // offset += 0 + case 1: + offset += f.offset + case 2: + offset += int64(len(f.f.data)) + } + if offset < 0 || offset > int64(len(f.f.data)) { + return 0, &fs.PathError{Op: "seek", Path: f.f.name, Err: fs.ErrInvalid} + } + f.offset = offset + return offset, nil +} + +func (f *openFile) ReadAt(b []byte, offset int64) (int, error) { + if offset < 0 || offset > int64(len(f.f.data)) { + return 0, &fs.PathError{Op: "read", Path: f.f.name, Err: fs.ErrInvalid} + } + n := copy(b, f.f.data[offset:]) + if n < len(b) { + return n, io.EOF + } + return n, nil +} + +// An openDir is a directory open for reading. +type openDir struct { + f *file // the directory file itself + files []file // the directory contents + offset int // the read offset, an index into the files slice +} + +func (d *openDir) Close() error { return nil } +func (d *openDir) Stat() (fs.FileInfo, error) { return d.f, nil } + +func (d *openDir) Read([]byte) (int, error) { + return 0, &fs.PathError{Op: "read", Path: d.f.name, Err: errors.New("is a directory")} +} + +func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error) { + n := len(d.files) - d.offset + if n == 0 { + if count <= 0 { + return nil, nil + } + return nil, io.EOF + } + if count > 0 && n > count { + n = count + } + list := make([]fs.DirEntry, n) + for i := range list { + list[i] = &d.files[d.offset+i] + } + d.offset += n + return list, nil +} + +// sortSearch is like sort.Search, avoiding an import. +func sortSearch(n int, f func(int) bool) int { + // Define f(-1) == false and f(n) == true. + // Invariant: f(i-1) == false, f(j) == true. + i, j := 0, n + for i < j { + h := int(uint(i+j) >> 1) // avoid overflow when computing h + // i ≤ h < j + if !f(h) { + i = h + 1 // preserves f(i-1) == false + } else { + j = h // preserves f(j) == true + } + } + // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i. + return i +} diff --git a/go/src/embed/example_test.go b/go/src/embed/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b92eb520092013f4c33e897701c99d0941aec9cb --- /dev/null +++ b/go/src/embed/example_test.go @@ -0,0 +1,23 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package embed_test + +import ( + "embed" + "log" + "net/http" +) + +//go:embed internal/embedtest/testdata/*.txt +var content embed.FS + +func Example() { + mux := http.NewServeMux() + mux.Handle("/", http.FileServer(http.FS(content))) + err := http.ListenAndServe(":8080", mux) + if err != nil { + log.Fatal(err) + } +} diff --git a/go/src/encoding/encoding.go b/go/src/encoding/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..4d288b6d3b9b3e30444b634dd0403ea1245ffff2 --- /dev/null +++ b/go/src/encoding/encoding.go @@ -0,0 +1,78 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package encoding defines interfaces shared by other packages that +// convert data to and from byte-level and textual representations. +// Packages that check for these interfaces include encoding/gob, +// encoding/json, and encoding/xml. As a result, implementing an +// interface once can make a type useful in multiple encodings. +// Standard types that implement these interfaces include time.Time and net.IP. +// The interfaces come in pairs that produce and consume encoded data. +// +// Adding encoding/decoding methods to existing types may constitute a breaking change, +// as they can be used for serialization in communicating with programs +// written with different library versions. +// The policy for packages maintained by the Go project is to only allow +// the addition of marshaling functions if no existing, reasonable marshaling exists. +package encoding + +// BinaryMarshaler is the interface implemented by an object that can +// marshal itself into a binary form. +// +// MarshalBinary encodes the receiver into a binary form and returns the result. +type BinaryMarshaler interface { + MarshalBinary() (data []byte, err error) +} + +// BinaryUnmarshaler is the interface implemented by an object that can +// unmarshal a binary representation of itself. +// +// UnmarshalBinary must be able to decode the form generated by MarshalBinary. +// UnmarshalBinary must copy the data if it wishes to retain the data +// after returning. +type BinaryUnmarshaler interface { + UnmarshalBinary(data []byte) error +} + +// BinaryAppender is the interface implemented by an object +// that can append the binary representation of itself. +// If a type implements both [BinaryAppender] and [BinaryMarshaler], +// then v.MarshalBinary() must be semantically identical to v.AppendBinary(nil). +type BinaryAppender interface { + // AppendBinary appends the binary representation of itself to the end of b + // (allocating a larger slice if necessary) and returns the updated slice. + // + // Implementations must not retain b, nor mutate any bytes within b[:len(b)]. + AppendBinary(b []byte) ([]byte, error) +} + +// TextMarshaler is the interface implemented by an object that can +// marshal itself into a textual form. +// +// MarshalText encodes the receiver into UTF-8-encoded text and returns the result. +type TextMarshaler interface { + MarshalText() (text []byte, err error) +} + +// TextUnmarshaler is the interface implemented by an object that can +// unmarshal a textual representation of itself. +// +// UnmarshalText must be able to decode the form generated by MarshalText. +// UnmarshalText must copy the text if it wishes to retain the text +// after returning. +type TextUnmarshaler interface { + UnmarshalText(text []byte) error +} + +// TextAppender is the interface implemented by an object +// that can append the textual representation of itself. +// If a type implements both [TextAppender] and [TextMarshaler], +// then v.MarshalText() must be semantically identical to v.AppendText(nil). +type TextAppender interface { + // AppendText appends the textual representation of itself to the end of b + // (allocating a larger slice if necessary) and returns the updated slice. + // + // Implementations must not retain b, nor mutate any bytes within b[:len(b)]. + AppendText(b []byte) ([]byte, error) +} diff --git a/go/src/errors/errors.go b/go/src/errors/errors.go new file mode 100644 index 0000000000000000000000000000000000000000..8b926cfe148c448696750baa12b4ce175d4dc033 --- /dev/null +++ b/go/src/errors/errors.go @@ -0,0 +1,90 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package errors implements functions to manipulate errors. +// +// The [New] function creates errors whose only content is a text message. +// +// An error e wraps another error if e's type has one of the methods +// +// Unwrap() error +// Unwrap() []error +// +// If e.Unwrap() returns a non-nil error w or a slice containing w, +// then we say that e wraps w. A nil error returned from e.Unwrap() +// indicates that e does not wrap any error. It is invalid for an +// Unwrap method to return an []error containing a nil error value. +// +// An easy way to create wrapped errors is to call [fmt.Errorf] and apply +// the %w verb to the error argument: +// +// wrapsErr := fmt.Errorf("... %w ...", ..., err, ...) +// +// Successive unwrapping of an error creates a tree. The [Is] and [As] +// functions inspect an error's tree by examining first the error +// itself followed by the tree of each of its children in turn +// (pre-order, depth-first traversal). +// +// See https://go.dev/blog/go1.13-errors for a deeper discussion of the +// philosophy of wrapping and when to wrap. +// +// [Is] examines the tree of its first argument looking for an error that +// matches the second. It reports whether it finds a match. It should be +// used in preference to simple equality checks: +// +// if errors.Is(err, fs.ErrExist) +// +// is preferable to +// +// if err == fs.ErrExist +// +// because the former will succeed if err wraps [io/fs.ErrExist]. +// +// [AsType] examines the tree of its argument looking for an error whose +// type matches its type argument. If it succeeds, it returns the +// corresponding value of that type and true. Otherwise, it returns the +// zero value of that type and false. The form +// +// if perr, ok := errors.AsType[*fs.PathError](err); ok { +// fmt.Println(perr.Path) +// } +// +// is preferable to +// +// if perr, ok := err.(*fs.PathError); ok { +// fmt.Println(perr.Path) +// } +// +// because the former will succeed if err wraps an [*io/fs.PathError]. +package errors + +// New returns an error that formats as the given text. +// Each call to New returns a distinct error value even if the text is identical. +func New(text string) error { + return &errorString{text} +} + +// errorString is a trivial implementation of error. +type errorString struct { + s string +} + +func (e *errorString) Error() string { + return e.s +} + +// ErrUnsupported indicates that a requested operation cannot be performed, +// because it is unsupported. For example, a call to [os.Link] when using a +// file system that does not support hard links. +// +// Functions and methods should not return this error but should instead +// return an error including appropriate context that satisfies +// +// errors.Is(err, errors.ErrUnsupported) +// +// either by directly wrapping ErrUnsupported or by implementing an [Is] method. +// +// Functions and methods should document the cases in which an error +// wrapping this will be returned. +var ErrUnsupported = New("unsupported operation") diff --git a/go/src/errors/errors_test.go b/go/src/errors/errors_test.go new file mode 100644 index 0000000000000000000000000000000000000000..08ed54e041cf03ab83ffe9146c6f08c0cb5daf05 --- /dev/null +++ b/go/src/errors/errors_test.go @@ -0,0 +1,33 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors_test + +import ( + "errors" + "testing" +) + +func TestNewEqual(t *testing.T) { + // Different allocations should not be equal. + if errors.New("abc") == errors.New("abc") { + t.Errorf(`New("abc") == New("abc")`) + } + if errors.New("abc") == errors.New("xyz") { + t.Errorf(`New("abc") == New("xyz")`) + } + + // Same allocation should be equal to itself (not crash). + err := errors.New("jkl") + if err != err { + t.Errorf(`err != err`) + } +} + +func TestErrorMethod(t *testing.T) { + err := errors.New("abc") + if err.Error() != "abc" { + t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc") + } +} diff --git a/go/src/errors/example_test.go b/go/src/errors/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..298612c4eac92c3827c8f70ab68df93d48f79941 --- /dev/null +++ b/go/src/errors/example_test.go @@ -0,0 +1,238 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors_test + +import ( + "errors" + "fmt" + "io/fs" + "os" + "time" +) + +// MyError is an error implementation that includes a time and message. +type MyError struct { + When time.Time + What string +} + +func (e MyError) Error() string { + return fmt.Sprintf("%v: %v", e.When, e.What) +} + +func oops() error { + return MyError{ + time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC), + "the file system has gone away", + } +} + +func Example() { + if err := oops(); err != nil { + fmt.Println(err) + } + // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away +} + +func ExampleNew() { + err := errors.New("emit macho dwarf: elf header corrupted") + if err != nil { + fmt.Print(err) + } + // Output: emit macho dwarf: elf header corrupted +} + +func OopsNew() error { + return errors.New("an error") +} + +var ErrSentinel = errors.New("an error") + +func OopsSentinel() error { + return ErrSentinel +} + +// Each call to [errors.New] returns an unique instance of the error, +// even if the arguments are the same. To match against errors +// created by [errors.New], declare a sentinel error and reuse it. +func ExampleNew_unique() { + err1 := OopsNew() + err2 := OopsNew() + fmt.Println("Errors using distinct errors.New calls:") + fmt.Printf("Is(%q, %q) = %v\n", err1, err2, errors.Is(err1, err2)) + + err3 := OopsSentinel() + err4 := OopsSentinel() + fmt.Println() + fmt.Println("Errors using a sentinel error:") + fmt.Printf("Is(%q, %q) = %v\n", err3, err4, errors.Is(err3, err4)) + + // Output: + // Errors using distinct errors.New calls: + // Is("an error", "an error") = false + // + // Errors using a sentinel error: + // Is("an error", "an error") = true +} + +// The fmt package's Errorf function lets us use the package's formatting +// features to create descriptive error messages. +func ExampleNew_errorf() { + const name, id = "bimmler", 17 + err := fmt.Errorf("user %q (id %d) not found", name, id) + if err != nil { + fmt.Print(err) + } + // Output: user "bimmler" (id 17) not found +} + +func ExampleJoin() { + err1 := errors.New("err1") + err2 := errors.New("err2") + err := errors.Join(err1, err2) + fmt.Println(err) + if errors.Is(err, err1) { + fmt.Println("err is err1") + } + if errors.Is(err, err2) { + fmt.Println("err is err2") + } + fmt.Println(err.(interface{ Unwrap() []error }).Unwrap()) + // Output: + // err1 + // err2 + // err is err1 + // err is err2 + // [err1 err2] +} + +func ExampleIs() { + if _, err := os.Open("non-existing"); err != nil { + if errors.Is(err, fs.ErrNotExist) { + fmt.Println("file does not exist") + } else { + fmt.Println(err) + } + } + + // Output: + // file does not exist +} + +type MyIsError struct { + err string +} + +func (e MyIsError) Error() string { + return e.err +} +func (e MyIsError) Is(err error) bool { + return err == fs.ErrPermission +} + +// Custom errors can implement a method "Is(error) bool" to match other error values, +// overriding the default matching of [errors.Is]. +func ExampleIs_custom_match() { + var err error = MyIsError{"an error"} + fmt.Println("Error equals fs.ErrPermission:", err == fs.ErrPermission) + fmt.Println("Error is fs.ErrPermission:", errors.Is(err, fs.ErrPermission)) + + // Output: + // Error equals fs.ErrPermission: false + // Error is fs.ErrPermission: true +} + +func ExampleAs() { + if _, err := os.Open("non-existing"); err != nil { + var pathError *fs.PathError + if errors.As(err, &pathError) { + fmt.Println("Failed at path:", pathError.Path) + } else { + fmt.Println(err) + } + } + + // Output: + // Failed at path: non-existing +} + +func ExampleAsType() { + if _, err := os.Open("non-existing"); err != nil { + if pathError, ok := errors.AsType[*fs.PathError](err); ok { + fmt.Println("Failed at path:", pathError.Path) + } else { + fmt.Println(err) + } + } + // Output: + // Failed at path: non-existing +} + +type MyAsError struct { + err string +} + +func (e MyAsError) Error() string { + return e.err +} +func (e MyAsError) As(target any) bool { + pe, ok := target.(**fs.PathError) + if !ok { + return false + } + *pe = &fs.PathError{ + Op: "custom", + Path: "/", + Err: errors.New(e.err), + } + return true +} + +// Custom errors can implement a method "As(any) bool" to match against other error types, +// overriding the default matching of [errors.As]. +func ExampleAs_custom_match() { + var err error = MyAsError{"an error"} + fmt.Println("Error:", err) + fmt.Printf("TypeOf err: %T\n", err) + + var pathError *fs.PathError + ok := errors.As(err, &pathError) + fmt.Println("Error as fs.PathError:", ok) + fmt.Println("fs.PathError:", pathError) + + // Output: + // Error: an error + // TypeOf err: errors_test.MyAsError + // Error as fs.PathError: true + // fs.PathError: custom /: an error +} + +// Custom errors can implement a method "As(any) bool" to match against other error types, +// overriding the default matching of [errors.AsType]. +func ExampleAsType_custom_match() { + var err error = MyAsError{"an error"} + fmt.Println("Error:", err) + fmt.Printf("TypeOf err: %T\n", err) + + pathError, ok := errors.AsType[*fs.PathError](err) + fmt.Println("Error as fs.PathError:", ok) + fmt.Println("fs.PathError:", pathError) + + // Output: + // Error: an error + // TypeOf err: errors_test.MyAsError + // Error as fs.PathError: true + // fs.PathError: custom /: an error +} + +func ExampleUnwrap() { + err1 := errors.New("error1") + err2 := fmt.Errorf("error2: [%w]", err1) + fmt.Println(err2) + fmt.Println(errors.Unwrap(err2)) + // Output: + // error2: [error1] + // error1 +} diff --git a/go/src/errors/join.go b/go/src/errors/join.go new file mode 100644 index 0000000000000000000000000000000000000000..730bf7043c683f93dee2270aec25b13380c987b6 --- /dev/null +++ b/go/src/errors/join.go @@ -0,0 +1,63 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors + +import ( + "unsafe" +) + +// Join returns an error that wraps the given errors. +// Any nil error values are discarded. +// Join returns nil if every value in errs is nil. +// The error formats as the concatenation of the strings obtained +// by calling the Error method of each element of errs, with a newline +// between each string. +// +// A non-nil error returned by Join implements the Unwrap() []error method. +// The errors may be inspected with [Is] and [As]. +func Join(errs ...error) error { + n := 0 + for _, err := range errs { + if err != nil { + n++ + } + } + if n == 0 { + return nil + } + e := &joinError{ + errs: make([]error, 0, n), + } + for _, err := range errs { + if err != nil { + e.errs = append(e.errs, err) + } + } + return e +} + +type joinError struct { + errs []error +} + +func (e *joinError) Error() string { + // Since Join returns nil if every value in errs is nil, + // e.errs cannot be empty. + if len(e.errs) == 1 { + return e.errs[0].Error() + } + + b := []byte(e.errs[0].Error()) + for _, err := range e.errs[1:] { + b = append(b, '\n') + b = append(b, err.Error()...) + } + // At this point, b has at least one byte '\n'. + return unsafe.String(&b[0], len(b)) +} + +func (e *joinError) Unwrap() []error { + return e.errs +} diff --git a/go/src/errors/join_test.go b/go/src/errors/join_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8ee4d7f77be8856c1cd4d60fdafd2b5d0eb5cbff --- /dev/null +++ b/go/src/errors/join_test.go @@ -0,0 +1,76 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors_test + +import ( + "errors" + "reflect" + "testing" +) + +func TestJoinReturnsNil(t *testing.T) { + if err := errors.Join(); err != nil { + t.Errorf("errors.Join() = %v, want nil", err) + } + if err := errors.Join(nil); err != nil { + t.Errorf("errors.Join(nil) = %v, want nil", err) + } + if err := errors.Join(nil, nil); err != nil { + t.Errorf("errors.Join(nil, nil) = %v, want nil", err) + } +} + +func TestJoin(t *testing.T) { + err1 := errors.New("err1") + err2 := errors.New("err2") + merr := multiErr{errors.New("err3")} + for _, test := range []struct { + errs []error + want []error + }{{ + errs: []error{err1}, + want: []error{err1}, + }, { + errs: []error{err1, err2}, + want: []error{err1, err2}, + }, { + errs: []error{err1, nil, err2}, + want: []error{err1, err2}, + }, { + errs: []error{merr}, + want: []error{merr}, + }} { + got := errors.Join(test.errs...).(interface{ Unwrap() []error }).Unwrap() + if !reflect.DeepEqual(got, test.want) { + t.Errorf("Join(%v) = %v; want %v", test.errs, got, test.want) + } + if len(got) != cap(got) { + t.Errorf("Join(%v) returns errors with len=%v, cap=%v; want len==cap", test.errs, len(got), cap(got)) + } + } +} + +func TestJoinErrorMethod(t *testing.T) { + err1 := errors.New("err1") + err2 := errors.New("err2") + for _, test := range []struct { + errs []error + want string + }{{ + errs: []error{err1}, + want: "err1", + }, { + errs: []error{err1, err2}, + want: "err1\nerr2", + }, { + errs: []error{err1, nil, err2}, + want: "err1\nerr2", + }} { + got := errors.Join(test.errs...).Error() + if got != test.want { + t.Errorf("Join(%v).Error() = %q; want %q", test.errs, got, test.want) + } + } +} diff --git a/go/src/errors/wrap.go b/go/src/errors/wrap.go new file mode 100644 index 0000000000000000000000000000000000000000..e4a5ca33d5e0e7ef3b05c24eb5a516a749decea1 --- /dev/null +++ b/go/src/errors/wrap.go @@ -0,0 +1,209 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors + +import ( + "internal/reflectlite" +) + +// Unwrap returns the result of calling the Unwrap method on err, if err's +// type contains an Unwrap method returning error. +// Otherwise, Unwrap returns nil. +// +// Unwrap only calls a method of the form "Unwrap() error". +// In particular Unwrap does not unwrap errors returned by [Join]. +func Unwrap(err error) error { + u, ok := err.(interface { + Unwrap() error + }) + if !ok { + return nil + } + return u.Unwrap() +} + +// Is reports whether any error in err's tree matches target. +// The target must be comparable. +// +// The tree consists of err itself, followed by the errors obtained by repeatedly +// calling its Unwrap() error or Unwrap() []error method. When err wraps multiple +// errors, Is examines err followed by a depth-first traversal of its children. +// +// An error is considered to match a target if it is equal to that target or if +// it implements a method Is(error) bool such that Is(target) returns true. +// +// An error type might provide an Is method so it can be treated as equivalent +// to an existing error. For example, if MyError defines +// +// func (m MyError) Is(target error) bool { return target == fs.ErrExist } +// +// then Is(MyError{}, fs.ErrExist) returns true. See [syscall.Errno.Is] for +// an example in the standard library. An Is method should only shallowly +// compare err and the target and not call [Unwrap] on either. +func Is(err, target error) bool { + if err == nil || target == nil { + return err == target + } + + isComparable := reflectlite.TypeOf(target).Comparable() + return is(err, target, isComparable) +} + +func is(err, target error, targetComparable bool) bool { + for { + if targetComparable && err == target { + return true + } + if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) { + return true + } + switch x := err.(type) { + case interface{ Unwrap() error }: + err = x.Unwrap() + if err == nil { + return false + } + case interface{ Unwrap() []error }: + for _, err := range x.Unwrap() { + if is(err, target, targetComparable) { + return true + } + } + return false + default: + return false + } + } +} + +// As finds the first error in err's tree that matches target, and if one is found, sets +// target to that error value and returns true. Otherwise, it returns false. +// +// For most uses, prefer [AsType]. As is equivalent to [AsType] but sets its target +// argument rather than returning the matching error and doesn't require its target +// argument to implement error. +// +// The tree consists of err itself, followed by the errors obtained by repeatedly +// calling its Unwrap() error or Unwrap() []error method. When err wraps multiple +// errors, As examines err followed by a depth-first traversal of its children. +// +// An error matches target if the error's concrete value is assignable to the value +// pointed to by target, or if the error has a method As(any) bool such that +// As(target) returns true. In the latter case, the As method is responsible for +// setting target. +// +// An error type might provide an As method so it can be treated as if it were a +// different error type. +// +// As panics if target is not a non-nil pointer to either a type that implements +// error, or to any interface type. +func As(err error, target any) bool { + if err == nil { + return false + } + if target == nil { + panic("errors: target cannot be nil") + } + val := reflectlite.ValueOf(target) + typ := val.Type() + if typ.Kind() != reflectlite.Ptr || val.IsNil() { + panic("errors: target must be a non-nil pointer") + } + targetType := typ.Elem() + if targetType.Kind() != reflectlite.Interface && !targetType.Implements(errorType) { + panic("errors: *target must be interface or implement error") + } + return as(err, target, val, targetType) +} + +func as(err error, target any, targetVal reflectlite.Value, targetType reflectlite.Type) bool { + for { + if reflectlite.TypeOf(err).AssignableTo(targetType) { + targetVal.Elem().Set(reflectlite.ValueOf(err)) + return true + } + if x, ok := err.(interface{ As(any) bool }); ok && x.As(target) { + return true + } + switch x := err.(type) { + case interface{ Unwrap() error }: + err = x.Unwrap() + if err == nil { + return false + } + case interface{ Unwrap() []error }: + for _, err := range x.Unwrap() { + if err == nil { + continue + } + if as(err, target, targetVal, targetType) { + return true + } + } + return false + default: + return false + } + } +} + +var errorType = reflectlite.TypeOf((*error)(nil)).Elem() + +// AsType finds the first error in err's tree that matches the type E, and +// if one is found, returns that error value and true. Otherwise, it +// returns the zero value of E and false. +// +// The tree consists of err itself, followed by the errors obtained by +// repeatedly calling its Unwrap() error or Unwrap() []error method. When +// err wraps multiple errors, AsType examines err followed by a +// depth-first traversal of its children. +// +// An error err matches the type E if the type assertion err.(E) holds, +// or if the error has a method As(any) bool such that err.As(target) +// returns true when target is a non-nil *E. In the latter case, the As +// method is responsible for setting target. +func AsType[E error](err error) (E, bool) { + if err == nil { + var zero E + return zero, false + } + var pe *E // lazily initialized + return asType(err, &pe) +} + +func asType[E error](err error, ppe **E) (_ E, _ bool) { + for { + if e, ok := err.(E); ok { + return e, true + } + if x, ok := err.(interface{ As(any) bool }); ok { + if *ppe == nil { + *ppe = new(E) + } + if x.As(*ppe) { + return **ppe, true + } + } + switch x := err.(type) { + case interface{ Unwrap() error }: + err = x.Unwrap() + if err == nil { + return + } + case interface{ Unwrap() []error }: + for _, err := range x.Unwrap() { + if err == nil { + continue + } + if x, ok := asType(err, ppe); ok { + return x, true + } + } + return + default: + return + } + } +} diff --git a/go/src/errors/wrap_test.go b/go/src/errors/wrap_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81c795a6bb8b18355ae73f4398c9ac8c755c91df --- /dev/null +++ b/go/src/errors/wrap_test.go @@ -0,0 +1,438 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors_test + +import ( + "errors" + "fmt" + "io/fs" + "os" + "reflect" + "testing" +) + +func TestIs(t *testing.T) { + err1 := errors.New("1") + erra := wrapped{"wrap 2", err1} + errb := wrapped{"wrap 3", erra} + + err3 := errors.New("3") + + poser := &poser{"either 1 or 3", func(err error) bool { + return err == err1 || err == err3 + }} + + testCases := []struct { + err error + target error + match bool + }{ + {nil, nil, true}, + {nil, err1, false}, + {err1, nil, false}, + {err1, err1, true}, + {erra, err1, true}, + {errb, err1, true}, + {err1, err3, false}, + {erra, err3, false}, + {errb, err3, false}, + {poser, err1, true}, + {poser, err3, true}, + {poser, erra, false}, + {poser, errb, false}, + {errorUncomparable{}, errorUncomparable{}, true}, + {errorUncomparable{}, &errorUncomparable{}, false}, + {&errorUncomparable{}, errorUncomparable{}, true}, + {&errorUncomparable{}, &errorUncomparable{}, false}, + {errorUncomparable{}, err1, false}, + {&errorUncomparable{}, err1, false}, + {multiErr{}, err1, false}, + {multiErr{err1, err3}, err1, true}, + {multiErr{err3, err1}, err1, true}, + {multiErr{err1, err3}, errors.New("x"), false}, + {multiErr{err3, errb}, errb, true}, + {multiErr{err3, errb}, erra, true}, + {multiErr{err3, errb}, err1, true}, + {multiErr{errb, err3}, err1, true}, + {multiErr{poser}, err1, true}, + {multiErr{poser}, err3, true}, + {multiErr{nil}, nil, false}, + } + for _, tc := range testCases { + t.Run("", func(t *testing.T) { + if got := errors.Is(tc.err, tc.target); got != tc.match { + t.Errorf("Is(%v, %v) = %v, want %v", tc.err, tc.target, got, tc.match) + } + }) + } +} + +type poser struct { + msg string + f func(error) bool +} + +var poserPathErr = &fs.PathError{Op: "poser"} + +func (p *poser) Error() string { return p.msg } +func (p *poser) Is(err error) bool { return p.f(err) } +func (p *poser) As(err any) bool { + switch x := err.(type) { + case **poser: + *x = p + case *errorT: + *x = errorT{"poser"} + case **fs.PathError: + *x = poserPathErr + default: + return false + } + return true +} + +func TestAs(t *testing.T) { + var errT errorT + var errP *fs.PathError + var timeout interface{ Timeout() bool } + var p *poser + _, errF := os.Open("non-existing") + poserErr := &poser{"oh no", nil} + + testCases := []struct { + err error + target any + match bool + want any // value of target on match + }{{ + nil, + &errP, + false, + nil, + }, { + wrapped{"pitied the fool", errorT{"T"}}, + &errT, + true, + errorT{"T"}, + }, { + errF, + &errP, + true, + errF, + }, { + errorT{}, + &errP, + false, + nil, + }, { + wrapped{"wrapped", nil}, + &errT, + false, + nil, + }, { + &poser{"error", nil}, + &errT, + true, + errorT{"poser"}, + }, { + &poser{"path", nil}, + &errP, + true, + poserPathErr, + }, { + poserErr, + &p, + true, + poserErr, + }, { + errors.New("err"), + &timeout, + false, + nil, + }, { + errF, + &timeout, + true, + errF, + }, { + wrapped{"path error", errF}, + &timeout, + true, + errF, + }, { + multiErr{}, + &errT, + false, + nil, + }, { + multiErr{errors.New("a"), errorT{"T"}}, + &errT, + true, + errorT{"T"}, + }, { + multiErr{errorT{"T"}, errors.New("a")}, + &errT, + true, + errorT{"T"}, + }, { + multiErr{errorT{"a"}, errorT{"b"}}, + &errT, + true, + errorT{"a"}, + }, { + multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}}, + &errT, + true, + errorT{"a"}, + }, { + multiErr{wrapped{"path error", errF}}, + &timeout, + true, + errF, + }, { + multiErr{nil}, + &errT, + false, + nil, + }} + for i, tc := range testCases { + name := fmt.Sprintf("%d:As(Errorf(..., %v), %v)", i, tc.err, tc.target) + // Clear the target pointer, in case it was set in a previous test. + rtarget := reflect.ValueOf(tc.target) + rtarget.Elem().Set(reflect.Zero(reflect.TypeOf(tc.target).Elem())) + t.Run(name, func(t *testing.T) { + match := errors.As(tc.err, tc.target) + if match != tc.match { + t.Fatalf("match: got %v; want %v", match, tc.match) + } + if !match { + return + } + if got := rtarget.Elem().Interface(); got != tc.want { + t.Fatalf("got %#v, want %#v", got, tc.want) + } + }) + } +} + +func TestAsValidation(t *testing.T) { + var s string + testCases := []any{ + nil, + (*int)(nil), + "error", + &s, + } + err := errors.New("error") + for _, tc := range testCases { + t.Run(fmt.Sprintf("%T(%v)", tc, tc), func(t *testing.T) { + defer func() { + recover() + }() + if errors.As(err, tc) { + t.Errorf("As(err, %T(%v)) = true, want false", tc, tc) + return + } + t.Errorf("As(err, %T(%v)) did not panic", tc, tc) + }) + } +} + +func TestAsType(t *testing.T) { + var errT errorT + var errP *fs.PathError + type timeout interface { + Timeout() bool + error + } + _, errF := os.Open("non-existing") + poserErr := &poser{"oh no", nil} + + testAsType(t, + nil, + errP, + false, + ) + testAsType(t, + wrapped{"pitied the fool", errorT{"T"}}, + errorT{"T"}, + true, + ) + testAsType(t, + errF, + errF, + true, + ) + testAsType(t, + errT, + errP, + false, + ) + testAsType(t, + wrapped{"wrapped", nil}, + errT, + false, + ) + testAsType(t, + &poser{"error", nil}, + errorT{"poser"}, + true, + ) + testAsType(t, + &poser{"path", nil}, + poserPathErr, + true, + ) + testAsType(t, + poserErr, + poserErr, + true, + ) + testAsType(t, + errors.New("err"), + timeout(nil), + false, + ) + testAsType(t, + errF, + errF.(timeout), + true) + testAsType(t, + wrapped{"path error", errF}, + errF.(timeout), + true, + ) + testAsType(t, + multiErr{}, + errT, + false, + ) + testAsType(t, + multiErr{errors.New("a"), errorT{"T"}}, + errorT{"T"}, + true, + ) + testAsType(t, + multiErr{errorT{"T"}, errors.New("a")}, + errorT{"T"}, + true, + ) + testAsType(t, + multiErr{errorT{"a"}, errorT{"b"}}, + errorT{"a"}, + true, + ) + testAsType(t, + multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}}, + errorT{"a"}, + true, + ) + testAsType(t, + multiErr{wrapped{"path error", errF}}, + errF.(timeout), + true, + ) + testAsType(t, + multiErr{nil}, + errT, + false, + ) +} + +type compError interface { + comparable + error +} + +func testAsType[E compError](t *testing.T, err error, want E, wantOK bool) { + t.Helper() + name := fmt.Sprintf("AsType[%T](Errorf(..., %v))", want, err) + t.Run(name, func(t *testing.T) { + got, gotOK := errors.AsType[E](err) + if gotOK != wantOK || got != want { + t.Fatalf("got %v, %t; want %v, %t", got, gotOK, want, wantOK) + } + }) +} + +func BenchmarkIs(b *testing.B) { + err1 := errors.New("1") + err2 := multiErr{multiErr{multiErr{err1, errorT{"a"}}, errorT{"b"}}} + + for i := 0; i < b.N; i++ { + if !errors.Is(err2, err1) { + b.Fatal("Is failed") + } + } +} + +func BenchmarkAs(b *testing.B) { + err := multiErr{multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}}} + for i := 0; i < b.N; i++ { + var target errorT + if !errors.As(err, &target) { + b.Fatal("As failed") + } + } +} + +func BenchmarkAsType(b *testing.B) { + err := multiErr{multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}}} + for range b.N { + if _, ok := errors.AsType[errorT](err); !ok { + b.Fatal("AsType failed") + } + } +} + +func TestUnwrap(t *testing.T) { + err1 := errors.New("1") + erra := wrapped{"wrap 2", err1} + + testCases := []struct { + err error + want error + }{ + {nil, nil}, + {wrapped{"wrapped", nil}, nil}, + {err1, nil}, + {erra, err1}, + {wrapped{"wrap 3", erra}, erra}, + } + for _, tc := range testCases { + if got := errors.Unwrap(tc.err); got != tc.want { + t.Errorf("Unwrap(%v) = %v, want %v", tc.err, got, tc.want) + } + } +} + +type errorT struct{ s string } + +func (e errorT) Error() string { return fmt.Sprintf("errorT(%s)", e.s) } + +type wrapped struct { + msg string + err error +} + +func (e wrapped) Error() string { return e.msg } +func (e wrapped) Unwrap() error { return e.err } + +type multiErr []error + +func (m multiErr) Error() string { return "multiError" } +func (m multiErr) Unwrap() []error { return []error(m) } + +type errorUncomparable struct { + f []string +} + +func (errorUncomparable) Error() string { + return "uncomparable error" +} + +func (errorUncomparable) Is(target error) bool { + _, ok := target.(errorUncomparable) + return ok +} diff --git a/go/src/expvar/expvar.go b/go/src/expvar/expvar.go new file mode 100644 index 0000000000000000000000000000000000000000..4f66848f1fe4cf94ea9b50f02beef556ec57270d --- /dev/null +++ b/go/src/expvar/expvar.go @@ -0,0 +1,417 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package expvar provides a standardized interface to public variables, such +// as operation counters in servers. It exposes these variables via HTTP at +// /debug/vars in JSON format. As of Go 1.22, the /debug/vars request must +// use GET. +// +// Operations to set or modify these public variables are atomic. +// +// In addition to adding the HTTP handler, this package registers the +// following variables: +// +// cmdline os.Args +// memstats runtime.Memstats +// +// The package is sometimes only imported for the side effect of +// registering its HTTP handler and the above variables. To use it +// this way, link this package into your program: +// +// import _ "expvar" +package expvar + +import ( + "encoding/json" + "internal/godebug" + "log" + "math" + "net/http" + "os" + "runtime" + "slices" + "strconv" + "sync" + "sync/atomic" + "unicode/utf8" +) + +// Var is an abstract type for all exported variables. +type Var interface { + // String returns a valid JSON value for the variable. + // Types with String methods that do not return valid JSON + // (such as time.Time) must not be used as a Var. + String() string +} + +type jsonVar interface { + // appendJSON appends the JSON representation of the receiver to b. + appendJSON(b []byte) []byte +} + +// Int is a 64-bit integer variable that satisfies the [Var] interface. +type Int struct { + i atomic.Int64 +} + +func (v *Int) Value() int64 { + return v.i.Load() +} + +func (v *Int) String() string { + return string(v.appendJSON(nil)) +} + +func (v *Int) appendJSON(b []byte) []byte { + return strconv.AppendInt(b, v.i.Load(), 10) +} + +func (v *Int) Add(delta int64) { + v.i.Add(delta) +} + +func (v *Int) Set(value int64) { + v.i.Store(value) +} + +// Float is a 64-bit float variable that satisfies the [Var] interface. +type Float struct { + f atomic.Uint64 +} + +func (v *Float) Value() float64 { + return math.Float64frombits(v.f.Load()) +} + +func (v *Float) String() string { + return string(v.appendJSON(nil)) +} + +func (v *Float) appendJSON(b []byte) []byte { + return strconv.AppendFloat(b, math.Float64frombits(v.f.Load()), 'g', -1, 64) +} + +// Add adds delta to v. +func (v *Float) Add(delta float64) { + for { + cur := v.f.Load() + curVal := math.Float64frombits(cur) + nxtVal := curVal + delta + nxt := math.Float64bits(nxtVal) + if v.f.CompareAndSwap(cur, nxt) { + return + } + } +} + +// Set sets v to value. +func (v *Float) Set(value float64) { + v.f.Store(math.Float64bits(value)) +} + +// Map is a string-to-Var map variable that satisfies the [Var] interface. +type Map struct { + m sync.Map // map[string]Var + keysMu sync.RWMutex + keys []string // sorted +} + +// KeyValue represents a single entry in a [Map]. +type KeyValue struct { + Key string + Value Var +} + +func (v *Map) String() string { + return string(v.appendJSON(nil)) +} + +func (v *Map) appendJSON(b []byte) []byte { + return v.appendJSONMayExpand(b, false) +} + +func (v *Map) appendJSONMayExpand(b []byte, expand bool) []byte { + afterCommaDelim := byte(' ') + mayAppendNewline := func(b []byte) []byte { return b } + if expand { + afterCommaDelim = '\n' + mayAppendNewline = func(b []byte) []byte { return append(b, '\n') } + } + + b = append(b, '{') + b = mayAppendNewline(b) + first := true + v.Do(func(kv KeyValue) { + if !first { + b = append(b, ',', afterCommaDelim) + } + first = false + b = appendJSONQuote(b, kv.Key) + b = append(b, ':', ' ') + switch v := kv.Value.(type) { + case nil: + b = append(b, "null"...) + case jsonVar: + b = v.appendJSON(b) + default: + b = append(b, v.String()...) + } + }) + b = mayAppendNewline(b) + b = append(b, '}') + b = mayAppendNewline(b) + return b +} + +// Init removes all keys from the map. +func (v *Map) Init() *Map { + v.keysMu.Lock() + defer v.keysMu.Unlock() + v.keys = v.keys[:0] + v.m.Clear() + return v +} + +// addKey updates the sorted list of keys in v.keys. +func (v *Map) addKey(key string) { + v.keysMu.Lock() + defer v.keysMu.Unlock() + // Using insertion sort to place key into the already-sorted v.keys. + i, found := slices.BinarySearch(v.keys, key) + if found { + return + } + v.keys = slices.Insert(v.keys, i, key) +} + +func (v *Map) Get(key string) Var { + i, _ := v.m.Load(key) + av, _ := i.(Var) + return av +} + +func (v *Map) Set(key string, av Var) { + // Before we store the value, check to see whether the key is new. Try a Load + // before LoadOrStore: LoadOrStore causes the key interface to escape even on + // the Load path. + if _, ok := v.m.Load(key); !ok { + if _, dup := v.m.LoadOrStore(key, av); !dup { + v.addKey(key) + return + } + } + + v.m.Store(key, av) +} + +// Add adds delta to the *[Int] value stored under the given map key. +func (v *Map) Add(key string, delta int64) { + i, ok := v.m.Load(key) + if !ok { + var dup bool + i, dup = v.m.LoadOrStore(key, new(Int)) + if !dup { + v.addKey(key) + } + } + + // Add to Int; ignore otherwise. + if iv, ok := i.(*Int); ok { + iv.Add(delta) + } +} + +// AddFloat adds delta to the *[Float] value stored under the given map key. +func (v *Map) AddFloat(key string, delta float64) { + i, ok := v.m.Load(key) + if !ok { + var dup bool + i, dup = v.m.LoadOrStore(key, new(Float)) + if !dup { + v.addKey(key) + } + } + + // Add to Float; ignore otherwise. + if iv, ok := i.(*Float); ok { + iv.Add(delta) + } +} + +// Delete deletes the given key from the map. +func (v *Map) Delete(key string) { + v.keysMu.Lock() + defer v.keysMu.Unlock() + i, found := slices.BinarySearch(v.keys, key) + if found { + v.keys = slices.Delete(v.keys, i, i+1) + v.m.Delete(key) + } +} + +// Do calls f for each entry in the map. +// The map is locked during the iteration, +// but existing entries may be concurrently updated. +func (v *Map) Do(f func(KeyValue)) { + v.keysMu.RLock() + defer v.keysMu.RUnlock() + for _, k := range v.keys { + i, _ := v.m.Load(k) + val, _ := i.(Var) + f(KeyValue{k, val}) + } +} + +// String is a string variable, and satisfies the [Var] interface. +type String struct { + s atomic.Value // string +} + +func (v *String) Value() string { + p, _ := v.s.Load().(string) + return p +} + +// String implements the [Var] interface. To get the unquoted string +// use [String.Value]. +func (v *String) String() string { + return string(v.appendJSON(nil)) +} + +func (v *String) appendJSON(b []byte) []byte { + return appendJSONQuote(b, v.Value()) +} + +func (v *String) Set(value string) { + v.s.Store(value) +} + +// Func implements [Var] by calling the function +// and formatting the returned value using JSON. +type Func func() any + +func (f Func) Value() any { + return f() +} + +func (f Func) String() string { + v, _ := json.Marshal(f()) + return string(v) +} + +// All published variables. +var vars Map + +// Publish declares a named exported variable. This should be called from a +// package's init function when it creates its Vars. If the name is already +// registered then this will log.Panic. +func Publish(name string, v Var) { + if _, dup := vars.m.LoadOrStore(name, v); dup { + log.Panicln("Reuse of exported var name:", name) + } + vars.keysMu.Lock() + defer vars.keysMu.Unlock() + vars.keys = append(vars.keys, name) + slices.Sort(vars.keys) +} + +// Get retrieves a named exported variable. It returns nil if the name has +// not been registered. +func Get(name string) Var { + return vars.Get(name) +} + +// Convenience functions for creating new exported variables. + +func NewInt(name string) *Int { + v := new(Int) + Publish(name, v) + return v +} + +func NewFloat(name string) *Float { + v := new(Float) + Publish(name, v) + return v +} + +func NewMap(name string) *Map { + v := new(Map).Init() + Publish(name, v) + return v +} + +func NewString(name string) *String { + v := new(String) + Publish(name, v) + return v +} + +// Do calls f for each exported variable. +// The global variable map is locked during the iteration, +// but existing entries may be concurrently updated. +func Do(f func(KeyValue)) { + vars.Do(f) +} + +func expvarHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(vars.appendJSONMayExpand(nil, true)) +} + +// Handler returns the expvar HTTP Handler. +// +// This is only needed to install the handler in a non-standard location. +func Handler() http.Handler { + return http.HandlerFunc(expvarHandler) +} + +func cmdline() any { + return os.Args +} + +func memstats() any { + stats := new(runtime.MemStats) + runtime.ReadMemStats(stats) + return *stats +} + +func init() { + if godebug.New("httpmuxgo121").Value() == "1" { + http.HandleFunc("/debug/vars", expvarHandler) + } else { + http.HandleFunc("GET /debug/vars", expvarHandler) + } + Publish("cmdline", Func(cmdline)) + Publish("memstats", Func(memstats)) +} + +// TODO: Use json.appendString instead. +func appendJSONQuote(b []byte, s string) []byte { + const hex = "0123456789abcdef" + b = append(b, '"') + for _, r := range s { + switch { + case r < ' ' || r == '\\' || r == '"' || r == '<' || r == '>' || r == '&' || r == '\u2028' || r == '\u2029': + switch r { + case '\\', '"': + b = append(b, '\\', byte(r)) + case '\n': + b = append(b, '\\', 'n') + case '\r': + b = append(b, '\\', 'r') + case '\t': + b = append(b, '\\', 't') + default: + b = append(b, '\\', 'u', hex[(r>>12)&0xf], hex[(r>>8)&0xf], hex[(r>>4)&0xf], hex[(r>>0)&0xf]) + } + case r < utf8.RuneSelf: + b = append(b, byte(r)) + default: + b = utf8.AppendRune(b, r) + } + } + b = append(b, '"') + return b +} diff --git a/go/src/expvar/expvar_test.go b/go/src/expvar/expvar_test.go new file mode 100644 index 0000000000000000000000000000000000000000..def84179532e4e3530ac5ffcaa74e4fe164c0e70 --- /dev/null +++ b/go/src/expvar/expvar_test.go @@ -0,0 +1,669 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package expvar + +import ( + "bytes" + "crypto/sha1" + "encoding/json" + "fmt" + "net" + "net/http/httptest" + "reflect" + "runtime" + "strconv" + "sync" + "sync/atomic" + "testing" +) + +// RemoveAll removes all exported variables. +// This is for tests only. +func RemoveAll() { + vars.keysMu.Lock() + defer vars.keysMu.Unlock() + for _, k := range vars.keys { + vars.m.Delete(k) + } + vars.keys = nil +} + +func TestNil(t *testing.T) { + RemoveAll() + val := Get("missing") + if val != nil { + t.Errorf("got %v, want nil", val) + } +} + +func TestInt(t *testing.T) { + RemoveAll() + reqs := NewInt("requests") + if i := reqs.Value(); i != 0 { + t.Errorf("reqs.Value() = %v, want 0", i) + } + if reqs != Get("requests").(*Int) { + t.Errorf("Get() failed.") + } + + reqs.Add(1) + reqs.Add(3) + if i := reqs.Value(); i != 4 { + t.Errorf("reqs.Value() = %v, want 4", i) + } + + if s := reqs.String(); s != "4" { + t.Errorf("reqs.String() = %q, want \"4\"", s) + } + + reqs.Set(-2) + if i := reqs.Value(); i != -2 { + t.Errorf("reqs.Value() = %v, want -2", i) + } +} + +func BenchmarkIntAdd(b *testing.B) { + var v Int + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + v.Add(1) + } + }) +} + +func BenchmarkIntSet(b *testing.B) { + var v Int + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + v.Set(1) + } + }) +} + +func TestFloat(t *testing.T) { + RemoveAll() + reqs := NewFloat("requests-float") + if reqs.f.Load() != 0.0 { + t.Errorf("reqs.f = %v, want 0", reqs.f.Load()) + } + if reqs != Get("requests-float").(*Float) { + t.Errorf("Get() failed.") + } + + reqs.Add(1.5) + reqs.Add(1.25) + if v := reqs.Value(); v != 2.75 { + t.Errorf("reqs.Value() = %v, want 2.75", v) + } + + if s := reqs.String(); s != "2.75" { + t.Errorf("reqs.String() = %q, want \"4.64\"", s) + } + + reqs.Add(-2) + if v := reqs.Value(); v != 0.75 { + t.Errorf("reqs.Value() = %v, want 0.75", v) + } +} + +func BenchmarkFloatAdd(b *testing.B) { + var f Float + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + f.Add(1.0) + } + }) +} + +func BenchmarkFloatSet(b *testing.B) { + var f Float + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + f.Set(1.0) + } + }) +} + +func TestString(t *testing.T) { + RemoveAll() + name := NewString("my-name") + if s := name.Value(); s != "" { + t.Errorf(`NewString("my-name").Value() = %q, want ""`, s) + } + + name.Set("Mike") + if s, want := name.String(), `"Mike"`; s != want { + t.Errorf(`after name.Set("Mike"), name.String() = %q, want %q`, s, want) + } + if s, want := name.Value(), "Mike"; s != want { + t.Errorf(`after name.Set("Mike"), name.Value() = %q, want %q`, s, want) + } + + // Make sure we produce safe JSON output. + name.Set("<") + if s, want := name.String(), "\"\\u003c\""; s != want { + t.Errorf(`after name.Set("<"), name.String() = %q, want %q`, s, want) + } +} + +func BenchmarkStringSet(b *testing.B) { + var s String + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + s.Set("red") + } + }) +} + +func TestMapInit(t *testing.T) { + RemoveAll() + colors := NewMap("bike-shed-colors") + colors.Add("red", 1) + colors.Add("blue", 1) + colors.Add("chartreuse", 1) + + n := 0 + colors.Do(func(KeyValue) { n++ }) + if n != 3 { + t.Errorf("after three Add calls with distinct keys, Do should invoke f 3 times; got %v", n) + } + + colors.Init() + + n = 0 + colors.Do(func(KeyValue) { n++ }) + if n != 0 { + t.Errorf("after Init, Do should invoke f 0 times; got %v", n) + } +} + +func TestMapDelete(t *testing.T) { + RemoveAll() + colors := NewMap("bike-shed-colors") + + colors.Add("red", 1) + colors.Add("red", 2) + colors.Add("blue", 4) + + n := 0 + colors.Do(func(KeyValue) { n++ }) + if n != 2 { + t.Errorf("after two Add calls with distinct keys, Do should invoke f 2 times; got %v", n) + } + + colors.Delete("red") + if v := colors.Get("red"); v != nil { + t.Errorf("removed red, Get should return nil; got %v", v) + } + n = 0 + colors.Do(func(KeyValue) { n++ }) + if n != 1 { + t.Errorf("removed red, Do should invoke f 1 times; got %v", n) + } + + colors.Delete("notfound") + n = 0 + colors.Do(func(KeyValue) { n++ }) + if n != 1 { + t.Errorf("attempted to remove notfound, Do should invoke f 1 times; got %v", n) + } + + colors.Delete("blue") + colors.Delete("blue") + if v := colors.Get("blue"); v != nil { + t.Errorf("removed blue, Get should return nil; got %v", v) + } + n = 0 + colors.Do(func(KeyValue) { n++ }) + if n != 0 { + t.Errorf("all keys removed, Do should invoke f 0 times; got %v", n) + } +} + +func TestMapCounter(t *testing.T) { + RemoveAll() + colors := NewMap("bike-shed-colors") + + colors.Add("red", 1) + colors.Add("red", 2) + colors.Add("blue", 4) + colors.AddFloat(`green "midori"`, 4.125) + if x := colors.Get("red").(*Int).Value(); x != 3 { + t.Errorf("colors.m[\"red\"] = %v, want 3", x) + } + if x := colors.Get("blue").(*Int).Value(); x != 4 { + t.Errorf("colors.m[\"blue\"] = %v, want 4", x) + } + if x := colors.Get(`green "midori"`).(*Float).Value(); x != 4.125 { + t.Errorf("colors.m[`green \"midori\"] = %v, want 4.125", x) + } + + // colors.String() should be '{"red":3, "blue":4}', + // though the order of red and blue could vary. + s := colors.String() + var j any + err := json.Unmarshal([]byte(s), &j) + if err != nil { + t.Errorf("colors.String() isn't valid JSON: %v", err) + } + m, ok := j.(map[string]any) + if !ok { + t.Error("colors.String() didn't produce a map.") + } + red := m["red"] + x, ok := red.(float64) + if !ok { + t.Error("red.Kind() is not a number.") + } + if x != 3 { + t.Errorf("red = %v, want 3", x) + } +} + +func TestMapNil(t *testing.T) { + RemoveAll() + const key = "key" + m := NewMap("issue527719") + m.Set(key, nil) + s := m.String() + var j any + if err := json.Unmarshal([]byte(s), &j); err != nil { + t.Fatalf("m.String() == %q isn't valid JSON: %v", s, err) + } + m2, ok := j.(map[string]any) + if !ok { + t.Fatalf("m.String() produced %T, wanted a map", j) + } + v, ok := m2[key] + if !ok { + t.Fatalf("missing %q in %v", key, m2) + } + if v != nil { + t.Fatalf("m[%q] = %v, want nil", key, v) + } +} + +func BenchmarkMapSet(b *testing.B) { + m := new(Map).Init() + + v := new(Int) + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + m.Set("red", v) + } + }) +} + +func BenchmarkMapSetDifferent(b *testing.B) { + procKeys := make([][]string, runtime.GOMAXPROCS(0)) + for i := range procKeys { + keys := make([]string, 4) + for j := range keys { + keys[j] = fmt.Sprint(i, j) + } + procKeys[i] = keys + } + + m := new(Map).Init() + v := new(Int) + b.ResetTimer() + + var n int32 + b.RunParallel(func(pb *testing.PB) { + i := int(atomic.AddInt32(&n, 1)-1) % len(procKeys) + keys := procKeys[i] + + for pb.Next() { + for _, k := range keys { + m.Set(k, v) + } + } + }) +} + +// BenchmarkMapSetDifferentRandom simulates such a case where the concerned +// keys of Map.Set are generated dynamically and as a result insertion is +// out of order and the number of the keys may be large. +func BenchmarkMapSetDifferentRandom(b *testing.B) { + keys := make([]string, 100) + for i := range keys { + keys[i] = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprint(i)))) + } + + v := new(Int) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m := new(Map).Init() + for _, k := range keys { + m.Set(k, v) + } + } +} + +func BenchmarkMapSetString(b *testing.B) { + m := new(Map).Init() + + v := new(String) + v.Set("Hello, !") + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + m.Set("red", v) + } + }) +} + +func BenchmarkMapAddSame(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + m := new(Map).Init() + m.Add("red", 1) + m.Add("red", 1) + m.Add("red", 1) + m.Add("red", 1) + } + }) +} + +func BenchmarkMapAddDifferent(b *testing.B) { + procKeys := make([][]string, runtime.GOMAXPROCS(0)) + for i := range procKeys { + keys := make([]string, 4) + for j := range keys { + keys[j] = fmt.Sprint(i, j) + } + procKeys[i] = keys + } + + b.ResetTimer() + + var n int32 + b.RunParallel(func(pb *testing.PB) { + i := int(atomic.AddInt32(&n, 1)-1) % len(procKeys) + keys := procKeys[i] + + for pb.Next() { + m := new(Map).Init() + for _, k := range keys { + m.Add(k, 1) + } + } + }) +} + +// BenchmarkMapAddDifferentRandom simulates such a case where that the concerned +// keys of Map.Add are generated dynamically and as a result insertion is out of +// order and the number of the keys may be large. +func BenchmarkMapAddDifferentRandom(b *testing.B) { + keys := make([]string, 100) + for i := range keys { + keys[i] = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprint(i)))) + } + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m := new(Map).Init() + for _, k := range keys { + m.Add(k, 1) + } + } +} + +func BenchmarkMapAddSameSteadyState(b *testing.B) { + m := new(Map).Init() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + m.Add("red", 1) + } + }) +} + +func BenchmarkMapAddDifferentSteadyState(b *testing.B) { + procKeys := make([][]string, runtime.GOMAXPROCS(0)) + for i := range procKeys { + keys := make([]string, 4) + for j := range keys { + keys[j] = fmt.Sprint(i, j) + } + procKeys[i] = keys + } + + m := new(Map).Init() + b.ResetTimer() + + var n int32 + b.RunParallel(func(pb *testing.PB) { + i := int(atomic.AddInt32(&n, 1)-1) % len(procKeys) + keys := procKeys[i] + + for pb.Next() { + for _, k := range keys { + m.Add(k, 1) + } + } + }) +} + +func TestFunc(t *testing.T) { + RemoveAll() + var x any = []string{"a", "b"} + f := Func(func() any { return x }) + if s, exp := f.String(), `["a","b"]`; s != exp { + t.Errorf(`f.String() = %q, want %q`, s, exp) + } + if v := f.Value(); !reflect.DeepEqual(v, x) { + t.Errorf(`f.Value() = %q, want %q`, v, x) + } + + x = 17 + if s, exp := f.String(), `17`; s != exp { + t.Errorf(`f.String() = %q, want %q`, s, exp) + } +} + +func TestHandler(t *testing.T) { + RemoveAll() + m := NewMap("map1") + m.Add("a", 1) + m.Add("z", 2) + m2 := NewMap("map2") + for i := 0; i < 9; i++ { + m2.Add(strconv.Itoa(i), int64(i)) + } + rr := httptest.NewRecorder() + rr.Body = new(bytes.Buffer) + expvarHandler(rr, nil) + want := `{ +"map1": {"a": 1, "z": 2}, +"map2": {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8} +} +` + if got := rr.Body.String(); got != want { + t.Errorf("HTTP handler wrote:\n%s\nWant:\n%s", got, want) + } +} + +func BenchmarkMapString(b *testing.B) { + var m, m1, m2 Map + m.Set("map1", &m1) + m1.Add("a", 1) + m1.Add("z", 2) + m.Set("map2", &m2) + for i := 0; i < 9; i++ { + m2.Add(strconv.Itoa(i), int64(i)) + } + var s1, s2 String + m.Set("str1", &s1) + s1.Set("hello, world!") + m.Set("str2", &s2) + s2.Set("fizz buzz") + b.ResetTimer() + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = m.String() + } +} + +func BenchmarkRealworldExpvarUsage(b *testing.B) { + var ( + bytesSent Int + bytesRead Int + ) + + // The benchmark creates GOMAXPROCS client/server pairs. + // Each pair creates 4 goroutines: client reader/writer and server reader/writer. + // The benchmark stresses concurrent reading and writing to the same connection. + // Such pattern is used in net/http and net/rpc. + + b.StopTimer() + + P := runtime.GOMAXPROCS(0) + N := b.N / P + W := 1000 + + // Setup P client/server connections. + clients := make([]net.Conn, P) + servers := make([]net.Conn, P) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + b.Fatalf("Listen failed: %v", err) + } + defer ln.Close() + done := make(chan bool, 1) + go func() { + for p := 0; p < P; p++ { + s, err := ln.Accept() + if err != nil { + b.Errorf("Accept failed: %v", err) + done <- false + return + } + servers[p] = s + } + done <- true + }() + for p := 0; p < P; p++ { + c, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + <-done + b.Fatalf("Dial failed: %v", err) + } + clients[p] = c + } + if !<-done { + b.FailNow() + } + + b.StartTimer() + + var wg sync.WaitGroup + wg.Add(4 * P) + for p := 0; p < P; p++ { + // Client writer. + go func(c net.Conn) { + defer wg.Done() + var buf [1]byte + for i := 0; i < N; i++ { + v := byte(i) + for w := 0; w < W; w++ { + v *= v + } + buf[0] = v + n, err := c.Write(buf[:]) + if err != nil { + b.Errorf("Write failed: %v", err) + return + } + + bytesSent.Add(int64(n)) + } + }(clients[p]) + + // Pipe between server reader and server writer. + pipe := make(chan byte, 128) + + // Server reader. + go func(s net.Conn) { + defer wg.Done() + var buf [1]byte + for i := 0; i < N; i++ { + n, err := s.Read(buf[:]) + + if err != nil { + b.Errorf("Read failed: %v", err) + return + } + + bytesRead.Add(int64(n)) + pipe <- buf[0] + } + }(servers[p]) + + // Server writer. + go func(s net.Conn) { + defer wg.Done() + var buf [1]byte + for i := 0; i < N; i++ { + v := <-pipe + for w := 0; w < W; w++ { + v *= v + } + buf[0] = v + n, err := s.Write(buf[:]) + if err != nil { + b.Errorf("Write failed: %v", err) + return + } + + bytesSent.Add(int64(n)) + } + s.Close() + }(servers[p]) + + // Client reader. + go func(c net.Conn) { + defer wg.Done() + var buf [1]byte + for i := 0; i < N; i++ { + n, err := c.Read(buf[:]) + + if err != nil { + b.Errorf("Read failed: %v", err) + return + } + + bytesRead.Add(int64(n)) + } + c.Close() + }(clients[p]) + } + wg.Wait() +} + +func TestAppendJSONQuote(t *testing.T) { + var b []byte + for i := 0; i < 128; i++ { + b = append(b, byte(i)) + } + b = append(b, "\u2028\u2029"...) + got := string(appendJSONQuote(nil, string(b[:]))) + want := `"` + + `\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\t\n\u000b\u000c\r\u000e\u000f` + + `\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f` + + ` !\"#$%\u0026'()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_` + + "`" + `abcdefghijklmnopqrstuvwxyz{|}~` + "\x7f" + `\u2028\u2029"` + if got != want { + t.Errorf("appendJSONQuote mismatch:\ngot %v\nwant %v", got, want) + } +} diff --git a/go/src/flag/example_flagset_test.go b/go/src/flag/example_flagset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..cb177e2171e133d8ca8b3a655b2116a50e60676a --- /dev/null +++ b/go/src/flag/example_flagset_test.go @@ -0,0 +1,57 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package flag_test + +import ( + "flag" + "fmt" + "time" +) + +func ExampleFlagSet() { + + start := func(args []string) { + // A real program (not an example) would use flag.ExitOnError. + fs := flag.NewFlagSet("start", flag.ContinueOnError) + addr := fs.String("addr", ":8080", "`address` to listen on") + if err := fs.Parse(args); err != nil { + fmt.Printf("error: %s", err) + return + } + fmt.Printf("starting server on %s\n", *addr) + } + + stop := func(args []string) { + fs := flag.NewFlagSet("stop", flag.ContinueOnError) + timeout := fs.Duration("timeout", time.Second, "stop timeout duration") + if err := fs.Parse(args); err != nil { + fmt.Printf("error: %s", err) + return + } + fmt.Printf("stopping server (timeout=%v)\n", *timeout) + } + + main := func(args []string) { + subArgs := args[2:] // Drop program name and command. + switch args[1] { + case "start": + start(subArgs) + case "stop": + stop(subArgs) + default: + fmt.Printf("error: unknown command - %q\n", args[1]) + // In a real program (not an example) print to os.Stderr and exit the program with non-zero value. + } + } + + main([]string{"httpd", "start", "-addr", ":9999"}) + main([]string{"httpd", "stop"}) + main([]string{"http", "start", "-log-level", "verbose"}) + + // Output: + // starting server on :9999 + // stopping server (timeout=1s) + // error: flag provided but not defined: -log-level +} diff --git a/go/src/flag/example_func_test.go b/go/src/flag/example_func_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac9f9858dfa0013228006cd1bdcb85137a07390c --- /dev/null +++ b/go/src/flag/example_func_test.go @@ -0,0 +1,57 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package flag_test + +import ( + "errors" + "flag" + "fmt" + "net" + "os" +) + +func ExampleFunc() { + fs := flag.NewFlagSet("ExampleFunc", flag.ContinueOnError) + fs.SetOutput(os.Stdout) + var ip net.IP + fs.Func("ip", "`IP address` to parse", func(s string) error { + ip = net.ParseIP(s) + if ip == nil { + return errors.New("could not parse IP") + } + return nil + }) + fs.Parse([]string{"-ip", "127.0.0.1"}) + fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback()) + + // 256 is not a valid IPv4 component + fs.Parse([]string{"-ip", "256.0.0.1"}) + fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback()) + + // Output: + // {ip: 127.0.0.1, loopback: true} + // + // invalid value "256.0.0.1" for flag -ip: could not parse IP + // Usage of ExampleFunc: + // -ip IP address + // IP address to parse + // {ip: , loopback: false} +} + +func ExampleBoolFunc() { + fs := flag.NewFlagSet("ExampleBoolFunc", flag.ContinueOnError) + fs.SetOutput(os.Stdout) + + fs.BoolFunc("log", "logs a dummy message", func(s string) error { + fmt.Println("dummy message:", s) + return nil + }) + fs.Parse([]string{"-log"}) + fs.Parse([]string{"-log=0"}) + + // Output: + // dummy message: true + // dummy message: 0 +} diff --git a/go/src/flag/example_test.go b/go/src/flag/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..088447d43f6195cec3b72c45ac20801c4776ba43 --- /dev/null +++ b/go/src/flag/example_test.go @@ -0,0 +1,85 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// These examples demonstrate more intricate uses of the flag package. +package flag_test + +import ( + "errors" + "flag" + "fmt" + "strings" + "time" +) + +// Example 1: A single string flag called "species" with default value "gopher". +var species = flag.String("species", "gopher", "the species we are studying") + +// Example 2: Two flags sharing a variable, so we can have a shorthand. +// The order of initialization is undefined, so make sure both use the +// same default value. They must be set up with an init function. +var gopherType string + +func init() { + const ( + defaultGopher = "pocket" + usage = "the variety of gopher" + ) + flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage) + flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)") +} + +// Example 3: A user-defined flag type, a slice of durations. +type interval []time.Duration + +// String is the method to format the flag's value, part of the flag.Value interface. +// The String method's output will be used in diagnostics. +func (i *interval) String() string { + return fmt.Sprint(*i) +} + +// Set is the method to set the flag value, part of the flag.Value interface. +// Set's argument is a string to be parsed to set the flag. +// It's a comma-separated list, so we split it. +func (i *interval) Set(value string) error { + // If we wanted to allow the flag to be set multiple times, + // accumulating values, we would delete this if statement. + // That would permit usages such as + // -deltaT 10s -deltaT 15s + // and other combinations. + if len(*i) > 0 { + return errors.New("interval flag already set") + } + for _, dt := range strings.Split(value, ",") { + duration, err := time.ParseDuration(dt) + if err != nil { + return err + } + *i = append(*i, duration) + } + return nil +} + +// Define a flag to accumulate durations. Because it has a special type, +// we need to use the Var function and therefore create the flag during +// init. + +var intervalFlag interval + +func init() { + // Tie the command-line flag to the intervalFlag variable and + // set a usage message. + flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") +} + +func Example() { + // All the interesting pieces are with the variables declared above, but + // to enable the flag package to see the flags defined there, one must + // execute, typically at the start of main (not init!): + // flag.Parse() + // We don't call it here because this code is a function called "Example" + // that is part of the testing suite for the package, which has already + // parsed the flags. When viewed at pkg.go.dev, however, the function is + // renamed to "main" and it could be run as a standalone example. +} diff --git a/go/src/flag/example_textvar_test.go b/go/src/flag/example_textvar_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8b8cbf6b6c8f6b8040096d75edcd97a830512214 --- /dev/null +++ b/go/src/flag/example_textvar_test.go @@ -0,0 +1,35 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package flag_test + +import ( + "flag" + "fmt" + "net" + "os" +) + +func ExampleTextVar() { + fs := flag.NewFlagSet("ExampleTextVar", flag.ContinueOnError) + fs.SetOutput(os.Stdout) + var ip net.IP + fs.TextVar(&ip, "ip", net.IPv4(192, 168, 0, 100), "`IP address` to parse") + fs.Parse([]string{"-ip", "127.0.0.1"}) + fmt.Printf("{ip: %v}\n\n", ip) + + // 256 is not a valid IPv4 component + ip = nil + fs.Parse([]string{"-ip", "256.0.0.1"}) + fmt.Printf("{ip: %v}\n\n", ip) + + // Output: + // {ip: 127.0.0.1} + // + // invalid value "256.0.0.1" for flag -ip: invalid IP address: 256.0.0.1 + // Usage of ExampleTextVar: + // -ip IP address + // IP address to parse (default 192.168.0.100) + // {ip: } +} diff --git a/go/src/flag/example_value_test.go b/go/src/flag/example_value_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9d464c62e876b94a07fde8d8cb61b180826ae7c1 --- /dev/null +++ b/go/src/flag/example_value_test.go @@ -0,0 +1,44 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package flag_test + +import ( + "flag" + "fmt" + "net/url" +) + +type URLValue struct { + URL *url.URL +} + +func (v URLValue) String() string { + if v.URL != nil { + return v.URL.String() + } + return "" +} + +func (v URLValue) Set(s string) error { + if u, err := url.Parse(s); err != nil { + return err + } else { + *v.URL = *u + } + return nil +} + +var u = &url.URL{} + +func ExampleValue() { + fs := flag.NewFlagSet("ExampleValue", flag.ExitOnError) + fs.Var(&URLValue{u}, "url", "URL to parse") + + fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"}) + fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path) + + // Output: + // {scheme: "https", host: "golang.org", path: "/pkg/flag/"} +} diff --git a/go/src/flag/export_test.go b/go/src/flag/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9ef93ed6c5be1d0ea9949a150b7e92e6b3d59d44 --- /dev/null +++ b/go/src/flag/export_test.go @@ -0,0 +1,24 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package flag + +import ( + "io" + "os" +) + +// Additional routines compiled into the package only during testing. + +var DefaultUsage = Usage + +// ResetForTesting clears all flag state and sets the usage function as directed. +// After calling ResetForTesting, parse errors in flag handling will not +// exit the program. +func ResetForTesting(usage func()) { + CommandLine = NewFlagSet(os.Args[0], ContinueOnError) + CommandLine.SetOutput(io.Discard) + CommandLine.Usage = commandLineUsage + Usage = usage +} diff --git a/go/src/flag/flag.go b/go/src/flag/flag.go new file mode 100644 index 0000000000000000000000000000000000000000..71902f7f5913e908665dd2c1ab66ea28bce1c36b --- /dev/null +++ b/go/src/flag/flag.go @@ -0,0 +1,1238 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package flag implements command-line flag parsing. + +# Usage + +Define flags using [flag.String], [Bool], [Int], etc. + +This declares an integer flag, -n, stored in the pointer nFlag, with type *int: + + import "flag" + var nFlag = flag.Int("n", 1234, "help message for flag n") + +If you like, you can bind the flag to a variable using the Var() functions. + + var flagvar int + func init() { + flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + } + +Or you can create custom flags that satisfy the Value interface (with +pointer receivers) and couple them to flag parsing by + + flag.Var(&flagVal, "name", "help message for flagname") + +For such flags, the default value is just the initial value of the variable. + +After all flags are defined, call + + flag.Parse() + +to parse the command line into the defined flags. + +Flags may then be used directly. If you're using the flags themselves, +they are all pointers; if you bind to variables, they're values. + + fmt.Println("ip has value ", *ip) + fmt.Println("flagvar has value ", flagvar) + +After parsing, the arguments following the flags are available as the +slice [flag.Args] or individually as [flag.Arg](i). +The arguments are indexed from 0 through [flag.NArg]-1. + +# Command line flag syntax + +The following forms are permitted: + + -flag + --flag // double dashes are also permitted + -flag=x + -flag x // non-boolean flags only + +One or two dashes may be used; they are equivalent. +The last form is not permitted for boolean flags because the +meaning of the command + + cmd -x * + +where * is a Unix shell wildcard, will change if there is a file +called 0, false, etc. You must use the -flag=false form to turn +off a boolean flag. + +Flag parsing stops just before the first non-flag argument +("-" is a non-flag argument) or after the terminator "--". + +Integer flags accept 1234, 0664, 0x1234 and may be negative. +Boolean flags may be: + + 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False + +Duration flags accept any input valid for time.ParseDuration. + +The default set of command-line flags is controlled by +top-level functions. The [FlagSet] type allows one to define +independent sets of flags, such as to implement subcommands +in a command-line interface. The methods of [FlagSet] are +analogous to the top-level functions for the command-line +flag set. +*/ +package flag + +import ( + "encoding" + "errors" + "fmt" + "io" + "os" + "reflect" + "runtime" + "slices" + "strconv" + "strings" + "time" +) + +// ErrHelp is the error returned if the -help or -h flag is invoked +// but no such flag is defined. +var ErrHelp = errors.New("flag: help requested") + +// errParse is returned by Set if a flag's value fails to parse, such as with an invalid integer for Int. +// It then gets wrapped through failf to provide more information. +var errParse = errors.New("parse error") + +// errRange is returned by Set if a flag's value is out of range. +// It then gets wrapped through failf to provide more information. +var errRange = errors.New("value out of range") + +func numError(err error) error { + ne, ok := err.(*strconv.NumError) + if !ok { + return err + } + if ne.Err == strconv.ErrSyntax { + return errParse + } + if ne.Err == strconv.ErrRange { + return errRange + } + return err +} + +// -- bool Value +type boolValue bool + +func newBoolValue(val bool, p *bool) *boolValue { + *p = val + return (*boolValue)(p) +} + +func (b *boolValue) Set(s string) error { + v, err := strconv.ParseBool(s) + if err != nil { + err = errParse + } + *b = boolValue(v) + return err +} + +func (b *boolValue) Get() any { return bool(*b) } + +func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } + +func (b *boolValue) IsBoolFlag() bool { return true } + +// optional interface to indicate boolean flags that can be +// supplied without "=value" text +type boolFlag interface { + Value + IsBoolFlag() bool +} + +// -- int Value +type intValue int + +func newIntValue(val int, p *int) *intValue { + *p = val + return (*intValue)(p) +} + +func (i *intValue) Set(s string) error { + v, err := strconv.ParseInt(s, 0, strconv.IntSize) + if err != nil { + err = numError(err) + } + *i = intValue(v) + return err +} + +func (i *intValue) Get() any { return int(*i) } + +func (i *intValue) String() string { return strconv.Itoa(int(*i)) } + +// -- int64 Value +type int64Value int64 + +func newInt64Value(val int64, p *int64) *int64Value { + *p = val + return (*int64Value)(p) +} + +func (i *int64Value) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 64) + if err != nil { + err = numError(err) + } + *i = int64Value(v) + return err +} + +func (i *int64Value) Get() any { return int64(*i) } + +func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } + +// -- uint Value +type uintValue uint + +func newUintValue(val uint, p *uint) *uintValue { + *p = val + return (*uintValue)(p) +} + +func (i *uintValue) Set(s string) error { + v, err := strconv.ParseUint(s, 0, strconv.IntSize) + if err != nil { + err = numError(err) + } + *i = uintValue(v) + return err +} + +func (i *uintValue) Get() any { return uint(*i) } + +func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } + +// -- uint64 Value +type uint64Value uint64 + +func newUint64Value(val uint64, p *uint64) *uint64Value { + *p = val + return (*uint64Value)(p) +} + +func (i *uint64Value) Set(s string) error { + v, err := strconv.ParseUint(s, 0, 64) + if err != nil { + err = numError(err) + } + *i = uint64Value(v) + return err +} + +func (i *uint64Value) Get() any { return uint64(*i) } + +func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } + +// -- string Value +type stringValue string + +func newStringValue(val string, p *string) *stringValue { + *p = val + return (*stringValue)(p) +} + +func (s *stringValue) Set(val string) error { + *s = stringValue(val) + return nil +} + +func (s *stringValue) Get() any { return string(*s) } + +func (s *stringValue) String() string { return string(*s) } + +// -- float64 Value +type float64Value float64 + +func newFloat64Value(val float64, p *float64) *float64Value { + *p = val + return (*float64Value)(p) +} + +func (f *float64Value) Set(s string) error { + v, err := strconv.ParseFloat(s, 64) + if err != nil { + err = numError(err) + } + *f = float64Value(v) + return err +} + +func (f *float64Value) Get() any { return float64(*f) } + +func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } + +// -- time.Duration Value +type durationValue time.Duration + +func newDurationValue(val time.Duration, p *time.Duration) *durationValue { + *p = val + return (*durationValue)(p) +} + +func (d *durationValue) Set(s string) error { + v, err := time.ParseDuration(s) + if err != nil { + err = errParse + } + *d = durationValue(v) + return err +} + +func (d *durationValue) Get() any { return time.Duration(*d) } + +func (d *durationValue) String() string { return (*time.Duration)(d).String() } + +// -- encoding.TextUnmarshaler Value +type textValue struct{ p encoding.TextUnmarshaler } + +func newTextValue(val encoding.TextMarshaler, p encoding.TextUnmarshaler) textValue { + ptrVal := reflect.ValueOf(p) + if ptrVal.Kind() != reflect.Ptr { + panic("variable value type must be a pointer") + } + defVal := reflect.ValueOf(val) + if defVal.Kind() == reflect.Ptr { + defVal = defVal.Elem() + } + if defVal.Type() != ptrVal.Type().Elem() { + panic(fmt.Sprintf("default type does not match variable type: %v != %v", defVal.Type(), ptrVal.Type().Elem())) + } + ptrVal.Elem().Set(defVal) + return textValue{p} +} + +func (v textValue) Set(s string) error { + return v.p.UnmarshalText([]byte(s)) +} + +func (v textValue) Get() any { + return v.p +} + +func (v textValue) String() string { + if m, ok := v.p.(encoding.TextMarshaler); ok { + if b, err := m.MarshalText(); err == nil { + return string(b) + } + } + return "" +} + +// -- func Value +type funcValue func(string) error + +func (f funcValue) Set(s string) error { return f(s) } + +func (f funcValue) String() string { return "" } + +// -- boolFunc Value +type boolFuncValue func(string) error + +func (f boolFuncValue) Set(s string) error { return f(s) } + +func (f boolFuncValue) String() string { return "" } + +func (f boolFuncValue) IsBoolFlag() bool { return true } + +// Value is the interface to the dynamic value stored in a flag. +// (The default value is represented as a string.) +// +// If a Value has an IsBoolFlag() bool method returning true, +// the command-line parser makes -name equivalent to -name=true +// rather than using the next command-line argument. +// +// Set is called once, in command line order, for each flag present. +// The flag package may call the [String] method with a zero-valued receiver, +// such as a nil pointer. +type Value interface { + String() string + Set(string) error +} + +// Getter is an interface that allows the contents of a [Value] to be retrieved. +// It wraps the [Value] interface, rather than being part of it, because it +// appeared after Go 1 and its compatibility rules. All [Value] types provided +// by this package satisfy the [Getter] interface, except the type used by [Func]. +type Getter interface { + Value + Get() any +} + +// ErrorHandling defines how [FlagSet.Parse] behaves if the parse fails. +type ErrorHandling int + +// These constants cause [FlagSet.Parse] to behave as described if the parse fails. +const ( + ContinueOnError ErrorHandling = iota // Return a descriptive error. + ExitOnError // Call os.Exit(2) or for -h/-help Exit(0). + PanicOnError // Call panic with a descriptive error. +) + +// A FlagSet represents a set of defined flags. The zero value of a FlagSet +// has no name and has [ContinueOnError] error handling. +// +// [Flag] names must be unique within a FlagSet. An attempt to define a flag whose +// name is already in use will cause a panic. +type FlagSet struct { + // Usage is the function called when an error occurs while parsing flags. + // The field is a function (not a method) that may be changed to point to + // a custom error handler. What happens after Usage is called depends + // on the ErrorHandling setting; for the command line, this defaults + // to ExitOnError, which exits the program after calling Usage. + Usage func() + + name string + parsed bool + actual map[string]*Flag + formal map[string]*Flag + args []string // arguments after flags + errorHandling ErrorHandling + output io.Writer // nil means stderr; use Output() accessor + undef map[string]string // flags which didn't exist at the time of Set +} + +// A Flag represents the state of a flag. +type Flag struct { + Name string // name as it appears on command line + Usage string // help message + Value Value // value as set + DefValue string // default value (as text); for usage message +} + +// sortFlags returns the flags as a slice in lexicographical sorted order. +func sortFlags(flags map[string]*Flag) []*Flag { + result := make([]*Flag, len(flags)) + i := 0 + for _, f := range flags { + result[i] = f + i++ + } + slices.SortFunc(result, func(a, b *Flag) int { + return strings.Compare(a.Name, b.Name) + }) + return result +} + +// Output returns the destination for usage and error messages. [os.Stderr] is returned if +// output was not set or was set to nil. +func (f *FlagSet) Output() io.Writer { + if f.output == nil { + return os.Stderr + } + return f.output +} + +// Name returns the name of the flag set. +func (f *FlagSet) Name() string { + return f.name +} + +// ErrorHandling returns the error handling behavior of the flag set. +func (f *FlagSet) ErrorHandling() ErrorHandling { + return f.errorHandling +} + +// SetOutput sets the destination for usage and error messages. +// If output is nil, [os.Stderr] is used. +func (f *FlagSet) SetOutput(output io.Writer) { + f.output = output +} + +// VisitAll visits the flags in lexicographical order, calling fn for each. +// It visits all flags, even those not set. +func (f *FlagSet) VisitAll(fn func(*Flag)) { + for _, flag := range sortFlags(f.formal) { + fn(flag) + } +} + +// VisitAll visits the command-line flags in lexicographical order, calling +// fn for each. It visits all flags, even those not set. +func VisitAll(fn func(*Flag)) { + CommandLine.VisitAll(fn) +} + +// Visit visits the flags in lexicographical order, calling fn for each. +// It visits only those flags that have been set. +func (f *FlagSet) Visit(fn func(*Flag)) { + for _, flag := range sortFlags(f.actual) { + fn(flag) + } +} + +// Visit visits the command-line flags in lexicographical order, calling fn +// for each. It visits only those flags that have been set. +func Visit(fn func(*Flag)) { + CommandLine.Visit(fn) +} + +// Lookup returns the [Flag] structure of the named flag, returning nil if none exists. +func (f *FlagSet) Lookup(name string) *Flag { + return f.formal[name] +} + +// Lookup returns the [Flag] structure of the named command-line flag, +// returning nil if none exists. +func Lookup(name string) *Flag { + return CommandLine.formal[name] +} + +// Set sets the value of the named flag. +func (f *FlagSet) Set(name, value string) error { + return f.set(name, value) +} +func (f *FlagSet) set(name, value string) error { + flag, ok := f.formal[name] + if !ok { + // Remember that a flag that isn't defined is being set. + // We return an error in this case, but in addition if + // subsequently that flag is defined, we want to panic + // at the definition point. + // This is a problem which occurs if both the definition + // and the Set call are in init code and for whatever + // reason the init code changes evaluation order. + // See issue 57411. + _, file, line, ok := runtime.Caller(2) + if !ok { + file = "?" + line = 0 + } + if f.undef == nil { + f.undef = map[string]string{} + } + f.undef[name] = fmt.Sprintf("%s:%d", file, line) + + return fmt.Errorf("no such flag -%v", name) + } + err := flag.Value.Set(value) + if err != nil { + return err + } + if f.actual == nil { + f.actual = make(map[string]*Flag) + } + f.actual[name] = flag + return nil +} + +// Set sets the value of the named command-line flag. +func Set(name, value string) error { + return CommandLine.set(name, value) +} + +// isZeroValue determines whether the string represents the zero +// value for a flag. +func isZeroValue(flag *Flag, value string) (ok bool, err error) { + // Build a zero value of the flag's Value type, and see if the + // result of calling its String method equals the value passed in. + // This works unless the Value type is itself an interface type. + typ := reflect.TypeOf(flag.Value) + var z reflect.Value + if typ.Kind() == reflect.Pointer { + z = reflect.New(typ.Elem()) + } else { + z = reflect.Zero(typ) + } + // Catch panics calling the String method, which shouldn't prevent the + // usage message from being printed, but that we should report to the + // user so that they know to fix their code. + defer func() { + if e := recover(); e != nil { + if typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + err = fmt.Errorf("panic calling String method on zero %v for flag %s: %v", typ, flag.Name, e) + } + }() + return value == z.Interface().(Value).String(), nil +} + +// UnquoteUsage extracts a back-quoted name from the usage +// string for a flag and returns it and the un-quoted usage. +// Given "a `name` to show" it returns ("name", "a name to show"). +// If there are no back quotes, the name is an educated guess of the +// type of the flag's value, or the empty string if the flag is boolean. +func UnquoteUsage(flag *Flag) (name string, usage string) { + // Look for a back-quoted name, but avoid the strings package. + usage = flag.Usage + for i := 0; i < len(usage); i++ { + if usage[i] == '`' { + for j := i + 1; j < len(usage); j++ { + if usage[j] == '`' { + name = usage[i+1 : j] + usage = usage[:i] + name + usage[j+1:] + return name, usage + } + } + break // Only one back quote; use type name. + } + } + // No explicit name, so use type if we can find one. + name = "value" + switch fv := flag.Value.(type) { + case boolFlag: + if fv.IsBoolFlag() { + name = "" + } + case *durationValue: + name = "duration" + case *float64Value: + name = "float" + case *intValue, *int64Value: + name = "int" + case *stringValue: + name = "string" + case *uintValue, *uint64Value: + name = "uint" + } + return +} + +// PrintDefaults prints, to standard error unless configured otherwise, the +// default values of all defined command-line flags in the set. See the +// documentation for the global function PrintDefaults for more information. +func (f *FlagSet) PrintDefaults() { + var isZeroValueErrs []error + f.VisitAll(func(flag *Flag) { + var b strings.Builder + fmt.Fprintf(&b, " -%s", flag.Name) // Two spaces before -; see next two comments. + name, usage := UnquoteUsage(flag) + if len(name) > 0 { + b.WriteString(" ") + b.WriteString(name) + } + // Boolean flags of one ASCII letter are so common we + // treat them specially, putting their usage on the same line. + if b.Len() <= 4 { // space, space, '-', 'x'. + b.WriteString("\t") + } else { + // Four spaces before the tab triggers good alignment + // for both 4- and 8-space tab stops. + b.WriteString("\n \t") + } + b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t")) + + // Print the default value only if it differs to the zero value + // for this flag type. + if isZero, err := isZeroValue(flag, flag.DefValue); err != nil { + isZeroValueErrs = append(isZeroValueErrs, err) + } else if !isZero { + if _, ok := flag.Value.(*stringValue); ok { + // put quotes on the value + fmt.Fprintf(&b, " (default %q)", flag.DefValue) + } else { + fmt.Fprintf(&b, " (default %v)", flag.DefValue) + } + } + fmt.Fprint(f.Output(), b.String(), "\n") + }) + // If calling String on any zero flag.Values triggered a panic, print + // the messages after the full set of defaults so that the programmer + // knows to fix the panic. + if errs := isZeroValueErrs; len(errs) > 0 { + fmt.Fprintln(f.Output()) + for _, err := range errs { + fmt.Fprintln(f.Output(), err) + } + } +} + +// PrintDefaults prints, to standard error unless configured otherwise, +// a usage message showing the default settings of all defined +// command-line flags. +// For an integer valued flag x, the default output has the form +// +// -x int +// usage-message-for-x (default 7) +// +// The usage message will appear on a separate line for anything but +// a bool flag with a one-byte name. For bool flags, the type is +// omitted and if the flag name is one byte the usage message appears +// on the same line. The parenthetical default is omitted if the +// default is the zero value for the type. The listed type, here int, +// can be changed by placing a back-quoted name in the flag's usage +// string; the first such item in the message is taken to be a parameter +// name to show in the message and the back quotes are stripped from +// the message when displayed. For instance, given +// +// flag.String("I", "", "search `directory` for include files") +// +// the output will be +// +// -I directory +// search directory for include files. +// +// To change the destination for flag messages, call [CommandLine].SetOutput. +func PrintDefaults() { + CommandLine.PrintDefaults() +} + +// defaultUsage is the default function to print a usage message. +func (f *FlagSet) defaultUsage() { + if f.name == "" { + fmt.Fprintf(f.Output(), "Usage:\n") + } else { + fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name) + } + f.PrintDefaults() +} + +// NOTE: Usage is not just defaultUsage(CommandLine) +// because it serves (via godoc flag Usage) as the example +// for how to write your own usage function. + +// Usage prints a usage message documenting all defined command-line flags +// to [CommandLine]'s output, which by default is [os.Stderr]. +// It is called when an error occurs while parsing flags. +// The function is a variable that may be changed to point to a custom function. +// By default it prints a simple header and calls [PrintDefaults]; for details about the +// format of the output and how to control it, see the documentation for [PrintDefaults]. +// Custom usage functions may choose to exit the program; by default exiting +// happens anyway as the command line's error handling strategy is set to +// [ExitOnError]. +var Usage = func() { + fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0]) + PrintDefaults() +} + +// NFlag returns the number of flags that have been set. +func (f *FlagSet) NFlag() int { return len(f.actual) } + +// NFlag returns the number of command-line flags that have been set. +func NFlag() int { return len(CommandLine.actual) } + +// Arg returns the i'th argument. Arg(0) is the first remaining argument +// after flags have been processed. Arg returns an empty string if the +// requested element does not exist. +func (f *FlagSet) Arg(i int) string { + if i < 0 || i >= len(f.args) { + return "" + } + return f.args[i] +} + +// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument +// after flags have been processed. Arg returns an empty string if the +// requested element does not exist. +func Arg(i int) string { + return CommandLine.Arg(i) +} + +// NArg is the number of arguments remaining after flags have been processed. +func (f *FlagSet) NArg() int { return len(f.args) } + +// NArg is the number of arguments remaining after flags have been processed. +func NArg() int { return len(CommandLine.args) } + +// Args returns the non-flag arguments. +func (f *FlagSet) Args() []string { return f.args } + +// Args returns the non-flag command-line arguments. +func Args() []string { return CommandLine.args } + +// BoolVar defines a bool flag with specified name, default value, and usage string. +// The argument p points to a bool variable in which to store the value of the flag. +func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { + f.Var(newBoolValue(value, p), name, usage) +} + +// BoolVar defines a bool flag with specified name, default value, and usage string. +// The argument p points to a bool variable in which to store the value of the flag. +func BoolVar(p *bool, name string, value bool, usage string) { + CommandLine.Var(newBoolValue(value, p), name, usage) +} + +// Bool defines a bool flag with specified name, default value, and usage string. +// The return value is the address of a bool variable that stores the value of the flag. +func (f *FlagSet) Bool(name string, value bool, usage string) *bool { + p := new(bool) + f.BoolVar(p, name, value, usage) + return p +} + +// Bool defines a bool flag with specified name, default value, and usage string. +// The return value is the address of a bool variable that stores the value of the flag. +func Bool(name string, value bool, usage string) *bool { + return CommandLine.Bool(name, value, usage) +} + +// IntVar defines an int flag with specified name, default value, and usage string. +// The argument p points to an int variable in which to store the value of the flag. +func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { + f.Var(newIntValue(value, p), name, usage) +} + +// IntVar defines an int flag with specified name, default value, and usage string. +// The argument p points to an int variable in which to store the value of the flag. +func IntVar(p *int, name string, value int, usage string) { + CommandLine.Var(newIntValue(value, p), name, usage) +} + +// Int defines an int flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +func (f *FlagSet) Int(name string, value int, usage string) *int { + p := new(int) + f.IntVar(p, name, value, usage) + return p +} + +// Int defines an int flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +func Int(name string, value int, usage string) *int { + return CommandLine.Int(name, value, usage) +} + +// Int64Var defines an int64 flag with specified name, default value, and usage string. +// The argument p points to an int64 variable in which to store the value of the flag. +func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { + f.Var(newInt64Value(value, p), name, usage) +} + +// Int64Var defines an int64 flag with specified name, default value, and usage string. +// The argument p points to an int64 variable in which to store the value of the flag. +func Int64Var(p *int64, name string, value int64, usage string) { + CommandLine.Var(newInt64Value(value, p), name, usage) +} + +// Int64 defines an int64 flag with specified name, default value, and usage string. +// The return value is the address of an int64 variable that stores the value of the flag. +func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { + p := new(int64) + f.Int64Var(p, name, value, usage) + return p +} + +// Int64 defines an int64 flag with specified name, default value, and usage string. +// The return value is the address of an int64 variable that stores the value of the flag. +func Int64(name string, value int64, usage string) *int64 { + return CommandLine.Int64(name, value, usage) +} + +// UintVar defines a uint flag with specified name, default value, and usage string. +// The argument p points to a uint variable in which to store the value of the flag. +func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { + f.Var(newUintValue(value, p), name, usage) +} + +// UintVar defines a uint flag with specified name, default value, and usage string. +// The argument p points to a uint variable in which to store the value of the flag. +func UintVar(p *uint, name string, value uint, usage string) { + CommandLine.Var(newUintValue(value, p), name, usage) +} + +// Uint defines a uint flag with specified name, default value, and usage string. +// The return value is the address of a uint variable that stores the value of the flag. +func (f *FlagSet) Uint(name string, value uint, usage string) *uint { + p := new(uint) + f.UintVar(p, name, value, usage) + return p +} + +// Uint defines a uint flag with specified name, default value, and usage string. +// The return value is the address of a uint variable that stores the value of the flag. +func Uint(name string, value uint, usage string) *uint { + return CommandLine.Uint(name, value, usage) +} + +// Uint64Var defines a uint64 flag with specified name, default value, and usage string. +// The argument p points to a uint64 variable in which to store the value of the flag. +func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { + f.Var(newUint64Value(value, p), name, usage) +} + +// Uint64Var defines a uint64 flag with specified name, default value, and usage string. +// The argument p points to a uint64 variable in which to store the value of the flag. +func Uint64Var(p *uint64, name string, value uint64, usage string) { + CommandLine.Var(newUint64Value(value, p), name, usage) +} + +// Uint64 defines a uint64 flag with specified name, default value, and usage string. +// The return value is the address of a uint64 variable that stores the value of the flag. +func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { + p := new(uint64) + f.Uint64Var(p, name, value, usage) + return p +} + +// Uint64 defines a uint64 flag with specified name, default value, and usage string. +// The return value is the address of a uint64 variable that stores the value of the flag. +func Uint64(name string, value uint64, usage string) *uint64 { + return CommandLine.Uint64(name, value, usage) +} + +// StringVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a string variable in which to store the value of the flag. +func (f *FlagSet) StringVar(p *string, name string, value string, usage string) { + f.Var(newStringValue(value, p), name, usage) +} + +// StringVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a string variable in which to store the value of the flag. +func StringVar(p *string, name string, value string, usage string) { + CommandLine.Var(newStringValue(value, p), name, usage) +} + +// String defines a string flag with specified name, default value, and usage string. +// The return value is the address of a string variable that stores the value of the flag. +func (f *FlagSet) String(name string, value string, usage string) *string { + p := new(string) + f.StringVar(p, name, value, usage) + return p +} + +// String defines a string flag with specified name, default value, and usage string. +// The return value is the address of a string variable that stores the value of the flag. +func String(name string, value string, usage string) *string { + return CommandLine.String(name, value, usage) +} + +// Float64Var defines a float64 flag with specified name, default value, and usage string. +// The argument p points to a float64 variable in which to store the value of the flag. +func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) { + f.Var(newFloat64Value(value, p), name, usage) +} + +// Float64Var defines a float64 flag with specified name, default value, and usage string. +// The argument p points to a float64 variable in which to store the value of the flag. +func Float64Var(p *float64, name string, value float64, usage string) { + CommandLine.Var(newFloat64Value(value, p), name, usage) +} + +// Float64 defines a float64 flag with specified name, default value, and usage string. +// The return value is the address of a float64 variable that stores the value of the flag. +func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { + p := new(float64) + f.Float64Var(p, name, value, usage) + return p +} + +// Float64 defines a float64 flag with specified name, default value, and usage string. +// The return value is the address of a float64 variable that stores the value of the flag. +func Float64(name string, value float64, usage string) *float64 { + return CommandLine.Float64(name, value, usage) +} + +// DurationVar defines a time.Duration flag with specified name, default value, and usage string. +// The argument p points to a time.Duration variable in which to store the value of the flag. +// The flag accepts a value acceptable to time.ParseDuration. +func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { + f.Var(newDurationValue(value, p), name, usage) +} + +// DurationVar defines a time.Duration flag with specified name, default value, and usage string. +// The argument p points to a time.Duration variable in which to store the value of the flag. +// The flag accepts a value acceptable to time.ParseDuration. +func DurationVar(p *time.Duration, name string, value time.Duration, usage string) { + CommandLine.Var(newDurationValue(value, p), name, usage) +} + +// Duration defines a time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a time.Duration variable that stores the value of the flag. +// The flag accepts a value acceptable to time.ParseDuration. +func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration { + p := new(time.Duration) + f.DurationVar(p, name, value, usage) + return p +} + +// Duration defines a time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a time.Duration variable that stores the value of the flag. +// The flag accepts a value acceptable to time.ParseDuration. +func Duration(name string, value time.Duration, usage string) *time.Duration { + return CommandLine.Duration(name, value, usage) +} + +// TextVar defines a flag with a specified name, default value, and usage string. +// The argument p must be a pointer to a variable that will hold the value +// of the flag, and p must implement encoding.TextUnmarshaler. +// If the flag is used, the flag value will be passed to p's UnmarshalText method. +// The type of the default value must be the same as the type of p. +func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) { + f.Var(newTextValue(value, p), name, usage) +} + +// TextVar defines a flag with a specified name, default value, and usage string. +// The argument p must be a pointer to a variable that will hold the value +// of the flag, and p must implement encoding.TextUnmarshaler. +// If the flag is used, the flag value will be passed to p's UnmarshalText method. +// The type of the default value must be the same as the type of p. +func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) { + CommandLine.Var(newTextValue(value, p), name, usage) +} + +// Func defines a flag with the specified name and usage string. +// Each time the flag is seen, fn is called with the value of the flag. +// If fn returns a non-nil error, it will be treated as a flag value parsing error. +func (f *FlagSet) Func(name, usage string, fn func(string) error) { + f.Var(funcValue(fn), name, usage) +} + +// Func defines a flag with the specified name and usage string. +// Each time the flag is seen, fn is called with the value of the flag. +// If fn returns a non-nil error, it will be treated as a flag value parsing error. +func Func(name, usage string, fn func(string) error) { + CommandLine.Func(name, usage, fn) +} + +// BoolFunc defines a flag with the specified name and usage string without requiring values. +// Each time the flag is seen, fn is called with the value of the flag. +// If fn returns a non-nil error, it will be treated as a flag value parsing error. +func (f *FlagSet) BoolFunc(name, usage string, fn func(string) error) { + f.Var(boolFuncValue(fn), name, usage) +} + +// BoolFunc defines a flag with the specified name and usage string without requiring values. +// Each time the flag is seen, fn is called with the value of the flag. +// If fn returns a non-nil error, it will be treated as a flag value parsing error. +func BoolFunc(name, usage string, fn func(string) error) { + CommandLine.BoolFunc(name, usage, fn) +} + +// Var defines a flag with the specified name and usage string. The type and +// value of the flag are represented by the first argument, of type [Value], which +// typically holds a user-defined implementation of [Value]. For instance, the +// caller could create a flag that turns a comma-separated string into a slice +// of strings by giving the slice the methods of [Value]; in particular, [Set] would +// decompose the comma-separated string into the slice. +func (f *FlagSet) Var(value Value, name string, usage string) { + // Flag must not begin "-" or contain "=". + if strings.HasPrefix(name, "-") { + panic(f.sprintf("flag %q begins with -", name)) + } else if strings.Contains(name, "=") { + panic(f.sprintf("flag %q contains =", name)) + } + + // Remember the default value as a string; it won't change. + flag := &Flag{name, usage, value, value.String()} + _, alreadythere := f.formal[name] + if alreadythere { + var msg string + if f.name == "" { + msg = f.sprintf("flag redefined: %s", name) + } else { + msg = f.sprintf("%s flag redefined: %s", f.name, name) + } + panic(msg) // Happens only if flags are declared with identical names + } + if pos := f.undef[name]; pos != "" { + panic(fmt.Sprintf("flag %s set at %s before being defined", name, pos)) + } + if f.formal == nil { + f.formal = make(map[string]*Flag) + } + f.formal[name] = flag +} + +// Var defines a flag with the specified name and usage string. The type and +// value of the flag are represented by the first argument, of type [Value], which +// typically holds a user-defined implementation of [Value]. For instance, the +// caller could create a flag that turns a comma-separated string into a slice +// of strings by giving the slice the methods of [Value]; in particular, [Set] would +// decompose the comma-separated string into the slice. +func Var(value Value, name string, usage string) { + CommandLine.Var(value, name, usage) +} + +// sprintf formats the message, prints it to output, and returns it. +func (f *FlagSet) sprintf(format string, a ...any) string { + msg := fmt.Sprintf(format, a...) + fmt.Fprintln(f.Output(), msg) + return msg +} + +// failf prints to standard error a formatted error and usage message and +// returns the error. +func (f *FlagSet) failf(format string, a ...any) error { + msg := f.sprintf(format, a...) + f.usage() + return errors.New(msg) +} + +// usage calls the Usage method for the flag set if one is specified, +// or the appropriate default usage function otherwise. +func (f *FlagSet) usage() { + if f.Usage == nil { + f.defaultUsage() + } else { + f.Usage() + } +} + +// parseOne parses one flag. It reports whether a flag was seen. +func (f *FlagSet) parseOne() (bool, error) { + if len(f.args) == 0 { + return false, nil + } + s := f.args[0] + if len(s) < 2 || s[0] != '-' { + return false, nil + } + numMinuses := 1 + if s[1] == '-' { + numMinuses++ + if len(s) == 2 { // "--" terminates the flags + f.args = f.args[1:] + return false, nil + } + } + name := s[numMinuses:] + if len(name) == 0 || name[0] == '-' || name[0] == '=' { + return false, f.failf("bad flag syntax: %s", s) + } + + // it's a flag. does it have an argument? + f.args = f.args[1:] + hasValue := false + value := "" + for i := 1; i < len(name); i++ { // equals cannot be first + if name[i] == '=' { + value = name[i+1:] + hasValue = true + name = name[0:i] + break + } + } + + flag, ok := f.formal[name] + if !ok { + if name == "help" || name == "h" { // special case for nice help message. + f.usage() + return false, ErrHelp + } + return false, f.failf("flag provided but not defined: -%s", name) + } + + if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg + if hasValue { + if err := fv.Set(value); err != nil { + return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err) + } + } else { + if err := fv.Set("true"); err != nil { + return false, f.failf("invalid boolean flag %s: %v", name, err) + } + } + } else { + // It must have a value, which might be the next argument. + if !hasValue && len(f.args) > 0 { + // value is the next arg + hasValue = true + value, f.args = f.args[0], f.args[1:] + } + if !hasValue { + return false, f.failf("flag needs an argument: -%s", name) + } + if err := flag.Value.Set(value); err != nil { + return false, f.failf("invalid value %q for flag -%s: %v", value, name, err) + } + } + if f.actual == nil { + f.actual = make(map[string]*Flag) + } + f.actual[name] = flag + return true, nil +} + +// Parse parses flag definitions from the argument list, which should not +// include the command name. Must be called after all flags in the [FlagSet] +// are defined and before flags are accessed by the program. +// The return value will be [ErrHelp] if -help or -h were set but not defined. +func (f *FlagSet) Parse(arguments []string) error { + f.parsed = true + f.args = arguments + for { + seen, err := f.parseOne() + if seen { + continue + } + if err == nil { + break + } + switch f.errorHandling { + case ContinueOnError: + return err + case ExitOnError: + if err == ErrHelp { + os.Exit(0) + } + os.Exit(2) + case PanicOnError: + panic(err) + } + } + return nil +} + +// Parsed reports whether f.Parse has been called. +func (f *FlagSet) Parsed() bool { + return f.parsed +} + +// Parse parses the command-line flags from [os.Args][1:]. Must be called +// after all flags are defined and before flags are accessed by the program. +func Parse() { + // Ignore errors; CommandLine is set for ExitOnError. + CommandLine.Parse(os.Args[1:]) +} + +// Parsed reports whether the command-line flags have been parsed. +func Parsed() bool { + return CommandLine.Parsed() +} + +// CommandLine is the default set of command-line flags, parsed from [os.Args]. +// The top-level functions such as [BoolVar], [Arg], and so on are wrappers for the +// methods of CommandLine. +var CommandLine *FlagSet + +func init() { + // It's possible for execl to hand us an empty os.Args. + if len(os.Args) == 0 { + CommandLine = NewFlagSet("", ExitOnError) + } else { + CommandLine = NewFlagSet(os.Args[0], ExitOnError) + } + + // Override generic FlagSet default Usage with call to global Usage. + // Note: This is not CommandLine.Usage = Usage, + // because we want any eventual call to use any updated value of Usage, + // not the value it has when this line is run. + CommandLine.Usage = commandLineUsage +} + +func commandLineUsage() { + Usage() +} + +// NewFlagSet returns a new, empty flag set with the specified name and +// error handling property. If the name is not empty, it will be printed +// in the default usage message and in error messages. +func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { + f := &FlagSet{ + name: name, + errorHandling: errorHandling, + } + f.Usage = f.defaultUsage + return f +} + +// Init sets the name and error handling property for a flag set. +// By default, the zero [FlagSet] uses an empty name and the +// [ContinueOnError] error handling policy. +func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { + f.name = name + f.errorHandling = errorHandling +} diff --git a/go/src/flag/flag_test.go b/go/src/flag/flag_test.go new file mode 100644 index 0000000000000000000000000000000000000000..278ae7e4e02aac1abf279e6764af7a20390051af --- /dev/null +++ b/go/src/flag/flag_test.go @@ -0,0 +1,858 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package flag_test + +import ( + "bytes" + . "flag" + "fmt" + "internal/testenv" + "io" + "os" + "os/exec" + "regexp" + "runtime" + "slices" + "strconv" + "strings" + "testing" + "time" +) + +func boolString(s string) string { + if s == "0" { + return "false" + } + return "true" +} + +func TestEverything(t *testing.T) { + ResetForTesting(nil) + Bool("test_bool", false, "bool value") + Int("test_int", 0, "int value") + Int64("test_int64", 0, "int64 value") + Uint("test_uint", 0, "uint value") + Uint64("test_uint64", 0, "uint64 value") + String("test_string", "0", "string value") + Float64("test_float64", 0, "float64 value") + Duration("test_duration", 0, "time.Duration value") + Func("test_func", "func value", func(string) error { return nil }) + BoolFunc("test_boolfunc", "func", func(string) error { return nil }) + + m := make(map[string]*Flag) + desired := "0" + visitor := func(f *Flag) { + if len(f.Name) > 5 && f.Name[0:5] == "test_" { + m[f.Name] = f + ok := false + switch { + case f.Value.String() == desired: + ok = true + case f.Name == "test_bool" && f.Value.String() == boolString(desired): + ok = true + case f.Name == "test_duration" && f.Value.String() == desired+"s": + ok = true + case f.Name == "test_func" && f.Value.String() == "": + ok = true + case f.Name == "test_boolfunc" && f.Value.String() == "": + ok = true + } + if !ok { + t.Error("Visit: bad value", f.Value.String(), "for", f.Name) + } + } + } + VisitAll(visitor) + if len(m) != 10 { + t.Error("VisitAll misses some flags") + for k, v := range m { + t.Log(k, *v) + } + } + m = make(map[string]*Flag) + Visit(visitor) + if len(m) != 0 { + t.Errorf("Visit sees unset flags") + for k, v := range m { + t.Log(k, *v) + } + } + // Now set all flags + Set("test_bool", "true") + Set("test_int", "1") + Set("test_int64", "1") + Set("test_uint", "1") + Set("test_uint64", "1") + Set("test_string", "1") + Set("test_float64", "1") + Set("test_duration", "1s") + Set("test_func", "1") + Set("test_boolfunc", "") + desired = "1" + Visit(visitor) + if len(m) != 10 { + t.Error("Visit fails after set") + for k, v := range m { + t.Log(k, *v) + } + } + // Now test they're visited in sort order. + var flagNames []string + Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) }) + if !slices.IsSorted(flagNames) { + t.Errorf("flag names not sorted: %v", flagNames) + } +} + +func TestGet(t *testing.T) { + ResetForTesting(nil) + Bool("test_bool", true, "bool value") + Int("test_int", 1, "int value") + Int64("test_int64", 2, "int64 value") + Uint("test_uint", 3, "uint value") + Uint64("test_uint64", 4, "uint64 value") + String("test_string", "5", "string value") + Float64("test_float64", 6, "float64 value") + Duration("test_duration", 7, "time.Duration value") + + visitor := func(f *Flag) { + if len(f.Name) > 5 && f.Name[0:5] == "test_" { + g, ok := f.Value.(Getter) + if !ok { + t.Errorf("Visit: value does not satisfy Getter: %T", f.Value) + return + } + switch f.Name { + case "test_bool": + ok = g.Get() == true + case "test_int": + ok = g.Get() == int(1) + case "test_int64": + ok = g.Get() == int64(2) + case "test_uint": + ok = g.Get() == uint(3) + case "test_uint64": + ok = g.Get() == uint64(4) + case "test_string": + ok = g.Get() == "5" + case "test_float64": + ok = g.Get() == float64(6) + case "test_duration": + ok = g.Get() == time.Duration(7) + } + if !ok { + t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), f.Name) + } + } + } + VisitAll(visitor) +} + +func TestUsage(t *testing.T) { + called := false + ResetForTesting(func() { called = true }) + if CommandLine.Parse([]string{"-x"}) == nil { + t.Error("parse did not fail for unknown flag") + } + if !called { + t.Error("did not call Usage for unknown flag") + } +} + +func testParse(f *FlagSet, t *testing.T) { + if f.Parsed() { + t.Error("f.Parse() = true before Parse") + } + boolFlag := f.Bool("bool", false, "bool value") + bool2Flag := f.Bool("bool2", false, "bool2 value") + intFlag := f.Int("int", 0, "int value") + int64Flag := f.Int64("int64", 0, "int64 value") + uintFlag := f.Uint("uint", 0, "uint value") + uint64Flag := f.Uint64("uint64", 0, "uint64 value") + stringFlag := f.String("string", "0", "string value") + float64Flag := f.Float64("float64", 0, "float64 value") + durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") + extra := "one-extra-argument" + args := []string{ + "-bool", + "-bool2=true", + "--int", "22", + "--int64", "0x23", + "-uint", "24", + "--uint64", "25", + "-string", "hello", + "-float64", "2718e28", + "-duration", "2m", + extra, + } + if err := f.Parse(args); err != nil { + t.Fatal(err) + } + if !f.Parsed() { + t.Error("f.Parse() = false after Parse") + } + if *boolFlag != true { + t.Error("bool flag should be true, is ", *boolFlag) + } + if *bool2Flag != true { + t.Error("bool2 flag should be true, is ", *bool2Flag) + } + if *intFlag != 22 { + t.Error("int flag should be 22, is ", *intFlag) + } + if *int64Flag != 0x23 { + t.Error("int64 flag should be 0x23, is ", *int64Flag) + } + if *uintFlag != 24 { + t.Error("uint flag should be 24, is ", *uintFlag) + } + if *uint64Flag != 25 { + t.Error("uint64 flag should be 25, is ", *uint64Flag) + } + if *stringFlag != "hello" { + t.Error("string flag should be `hello`, is ", *stringFlag) + } + if *float64Flag != 2718e28 { + t.Error("float64 flag should be 2718e28, is ", *float64Flag) + } + if *durationFlag != 2*time.Minute { + t.Error("duration flag should be 2m, is ", *durationFlag) + } + if len(f.Args()) != 1 { + t.Error("expected one argument, got", len(f.Args())) + } else if f.Args()[0] != extra { + t.Errorf("expected argument %q got %q", extra, f.Args()[0]) + } +} + +func TestParse(t *testing.T) { + ResetForTesting(func() { t.Error("bad parse") }) + testParse(CommandLine, t) +} + +func TestFlagSetParse(t *testing.T) { + testParse(NewFlagSet("test", ContinueOnError), t) +} + +// Declare a user-defined flag type. +type flagVar []string + +func (f *flagVar) String() string { + return fmt.Sprint([]string(*f)) +} + +func (f *flagVar) Set(value string) error { + *f = append(*f, value) + return nil +} + +func TestUserDefined(t *testing.T) { + var flags FlagSet + flags.Init("test", ContinueOnError) + flags.SetOutput(io.Discard) + var v flagVar + flags.Var(&v, "v", "usage") + if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil { + t.Error(err) + } + if len(v) != 3 { + t.Fatal("expected 3 args; got ", len(v)) + } + expect := "[1 2 3]" + if v.String() != expect { + t.Errorf("expected value %q got %q", expect, v.String()) + } +} + +func TestUserDefinedFunc(t *testing.T) { + flags := NewFlagSet("test", ContinueOnError) + flags.SetOutput(io.Discard) + var ss []string + flags.Func("v", "usage", func(s string) error { + ss = append(ss, s) + return nil + }) + if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil { + t.Error(err) + } + if len(ss) != 3 { + t.Fatal("expected 3 args; got ", len(ss)) + } + expect := "[1 2 3]" + if got := fmt.Sprint(ss); got != expect { + t.Errorf("expected value %q got %q", expect, got) + } + // test usage + var buf strings.Builder + flags.SetOutput(&buf) + flags.Parse([]string{"-h"}) + if usage := buf.String(); !strings.Contains(usage, "usage") { + t.Errorf("usage string not included: %q", usage) + } + // test Func error + flags = NewFlagSet("test", ContinueOnError) + flags.SetOutput(io.Discard) + flags.Func("v", "usage", func(s string) error { + return fmt.Errorf("test error") + }) + // flag not set, so no error + if err := flags.Parse(nil); err != nil { + t.Error(err) + } + // flag set, expect error + if err := flags.Parse([]string{"-v", "1"}); err == nil { + t.Error("expected error; got none") + } else if errMsg := err.Error(); !strings.Contains(errMsg, "test error") { + t.Errorf(`error should contain "test error"; got %q`, errMsg) + } +} + +func TestUserDefinedForCommandLine(t *testing.T) { + const help = "HELP" + var result string + ResetForTesting(func() { result = help }) + Usage() + if result != help { + t.Fatalf("got %q; expected %q", result, help) + } +} + +// Declare a user-defined boolean flag type. +type boolFlagVar struct { + count int +} + +func (b *boolFlagVar) String() string { + return fmt.Sprintf("%d", b.count) +} + +func (b *boolFlagVar) Set(value string) error { + if value == "true" { + b.count++ + } + return nil +} + +func (b *boolFlagVar) IsBoolFlag() bool { + return b.count < 4 +} + +func TestUserDefinedBool(t *testing.T) { + var flags FlagSet + flags.Init("test", ContinueOnError) + flags.SetOutput(io.Discard) + var b boolFlagVar + var err error + flags.Var(&b, "b", "usage") + if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil { + if b.count < 4 { + t.Error(err) + } + } + + if b.count != 4 { + t.Errorf("want: %d; got: %d", 4, b.count) + } + + if err == nil { + t.Error("expected error; got none") + } +} + +func TestUserDefinedBoolUsage(t *testing.T) { + var flags FlagSet + flags.Init("test", ContinueOnError) + var buf bytes.Buffer + flags.SetOutput(&buf) + var b boolFlagVar + flags.Var(&b, "b", "X") + b.count = 0 + // b.IsBoolFlag() will return true and usage will look boolean. + flags.PrintDefaults() + got := buf.String() + want := " -b\tX\n" + if got != want { + t.Errorf("false: want %q; got %q", want, got) + } + b.count = 4 + // b.IsBoolFlag() will return false and usage will look non-boolean. + flags.PrintDefaults() + got = buf.String() + want = " -b\tX\n -b value\n \tX\n" + if got != want { + t.Errorf("false: want %q; got %q", want, got) + } +} + +func TestSetOutput(t *testing.T) { + var flags FlagSet + var buf strings.Builder + flags.SetOutput(&buf) + flags.Init("test", ContinueOnError) + flags.Parse([]string{"-unknown"}) + if out := buf.String(); !strings.Contains(out, "-unknown") { + t.Logf("expected output mentioning unknown; got %q", out) + } +} + +// This tests that one can reset the flags. This still works but not well, and is +// superseded by FlagSet. +func TestChangingArgs(t *testing.T) { + ResetForTesting(func() { t.Fatal("bad parse") }) + oldArgs := os.Args + defer func() { os.Args = oldArgs }() + os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"} + before := Bool("before", false, "") + if err := CommandLine.Parse(os.Args[1:]); err != nil { + t.Fatal(err) + } + cmd := Arg(0) + os.Args = Args() + after := Bool("after", false, "") + Parse() + args := Args() + + if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { + t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) + } +} + +// Test that -help invokes the usage message and returns ErrHelp. +func TestHelp(t *testing.T) { + var helpCalled = false + fs := NewFlagSet("help test", ContinueOnError) + fs.Usage = func() { helpCalled = true } + var flag bool + fs.BoolVar(&flag, "flag", false, "regular flag") + // Regular flag invocation should work + err := fs.Parse([]string{"-flag=true"}) + if err != nil { + t.Fatal("expected no error; got ", err) + } + if !flag { + t.Error("flag was not set by -flag") + } + if helpCalled { + t.Error("help called for regular flag") + helpCalled = false // reset for next test + } + // Help flag should work as expected. + err = fs.Parse([]string{"-help"}) + if err == nil { + t.Fatal("error expected") + } + if err != ErrHelp { + t.Fatal("expected ErrHelp; got ", err) + } + if !helpCalled { + t.Fatal("help was not called") + } + // If we define a help flag, that should override. + var help bool + fs.BoolVar(&help, "help", false, "help flag") + helpCalled = false + err = fs.Parse([]string{"-help"}) + if err != nil { + t.Fatal("expected no error for defined -help; got ", err) + } + if helpCalled { + t.Fatal("help was called; should not have been for defined help flag") + } +} + +// zeroPanicker is a flag.Value whose String method panics if its dontPanic +// field is false. +type zeroPanicker struct { + dontPanic bool + v string +} + +func (f *zeroPanicker) Set(s string) error { + f.v = s + return nil +} + +func (f *zeroPanicker) String() string { + if !f.dontPanic { + panic("panic!") + } + return f.v +} + +const defaultOutput = ` -A for bootstrapping, allow 'any' type + -Alongflagname + disable bounds checking + -C a boolean defaulting to true (default true) + -D path + set relative path for local imports + -E string + issue 23543 (default "0") + -F number + a non-zero number (default 2.7) + -G float + a float that defaults to zero + -M string + a multiline + help + string + -N int + a non-zero int (default 27) + -O a flag + multiline help string (default true) + -V list + a list of strings (default [a b]) + -Z int + an int that defaults to zero + -ZP0 value + a flag whose String method panics when it is zero + -ZP1 value + a flag whose String method panics when it is zero + -maxT timeout + set timeout for dial + +panic calling String method on zero flag_test.zeroPanicker for flag ZP0: panic! +panic calling String method on zero flag_test.zeroPanicker for flag ZP1: panic! +` + +func TestPrintDefaults(t *testing.T) { + fs := NewFlagSet("print defaults test", ContinueOnError) + var buf strings.Builder + fs.SetOutput(&buf) + fs.Bool("A", false, "for bootstrapping, allow 'any' type") + fs.Bool("Alongflagname", false, "disable bounds checking") + fs.Bool("C", true, "a boolean defaulting to true") + fs.String("D", "", "set relative `path` for local imports") + fs.String("E", "0", "issue 23543") + fs.Float64("F", 2.7, "a non-zero `number`") + fs.Float64("G", 0, "a float that defaults to zero") + fs.String("M", "", "a multiline\nhelp\nstring") + fs.Int("N", 27, "a non-zero int") + fs.Bool("O", true, "a flag\nmultiline help string") + fs.Var(&flagVar{"a", "b"}, "V", "a `list` of strings") + fs.Int("Z", 0, "an int that defaults to zero") + fs.Var(&zeroPanicker{true, ""}, "ZP0", "a flag whose String method panics when it is zero") + fs.Var(&zeroPanicker{true, "something"}, "ZP1", "a flag whose String method panics when it is zero") + fs.Duration("maxT", 0, "set `timeout` for dial") + fs.PrintDefaults() + got := buf.String() + if got != defaultOutput { + t.Errorf("got:\n%q\nwant:\n%q", got, defaultOutput) + } +} + +// Issue 19230: validate range of Int and Uint flag values. +func TestIntFlagOverflow(t *testing.T) { + if strconv.IntSize != 32 { + return + } + ResetForTesting(nil) + Int("i", 0, "") + Uint("u", 0, "") + if err := Set("i", "2147483648"); err == nil { + t.Error("unexpected success setting Int") + } + if err := Set("u", "4294967296"); err == nil { + t.Error("unexpected success setting Uint") + } +} + +// Issue 20998: Usage should respect CommandLine.output. +func TestUsageOutput(t *testing.T) { + ResetForTesting(DefaultUsage) + var buf strings.Builder + CommandLine.SetOutput(&buf) + defer func(old []string) { os.Args = old }(os.Args) + os.Args = []string{"app", "-i=1", "-unknown"} + Parse() + const want = "flag provided but not defined: -i\nUsage of app:\n" + if got := buf.String(); got != want { + t.Errorf("output = %q; want %q", got, want) + } +} + +func TestGetters(t *testing.T) { + expectedName := "flag set" + expectedErrorHandling := ContinueOnError + expectedOutput := io.Writer(os.Stderr) + fs := NewFlagSet(expectedName, expectedErrorHandling) + + if fs.Name() != expectedName { + t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName) + } + if fs.ErrorHandling() != expectedErrorHandling { + t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling) + } + if fs.Output() != expectedOutput { + t.Errorf("unexpected output: got %#v, expected %#v", fs.Output(), expectedOutput) + } + + expectedName = "gopher" + expectedErrorHandling = ExitOnError + expectedOutput = os.Stdout + fs.Init(expectedName, expectedErrorHandling) + fs.SetOutput(expectedOutput) + + if fs.Name() != expectedName { + t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName) + } + if fs.ErrorHandling() != expectedErrorHandling { + t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling) + } + if fs.Output() != expectedOutput { + t.Errorf("unexpected output: got %v, expected %v", fs.Output(), expectedOutput) + } +} + +func TestParseError(t *testing.T) { + for _, typ := range []string{"bool", "int", "int64", "uint", "uint64", "float64", "duration"} { + fs := NewFlagSet("parse error test", ContinueOnError) + fs.SetOutput(io.Discard) + _ = fs.Bool("bool", false, "") + _ = fs.Int("int", 0, "") + _ = fs.Int64("int64", 0, "") + _ = fs.Uint("uint", 0, "") + _ = fs.Uint64("uint64", 0, "") + _ = fs.Float64("float64", 0, "") + _ = fs.Duration("duration", 0, "") + // Strings cannot give errors. + args := []string{"-" + typ + "=x"} + err := fs.Parse(args) // x is not a valid setting for any flag. + if err == nil { + t.Errorf("Parse(%q)=%v; expected parse error", args, err) + continue + } + if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "parse error") { + t.Errorf("Parse(%q)=%v; expected parse error", args, err) + } + } +} + +func TestRangeError(t *testing.T) { + bad := []string{ + "-int=123456789012345678901", + "-int64=123456789012345678901", + "-uint=123456789012345678901", + "-uint64=123456789012345678901", + "-float64=1e1000", + } + for _, arg := range bad { + fs := NewFlagSet("parse error test", ContinueOnError) + fs.SetOutput(io.Discard) + _ = fs.Int("int", 0, "") + _ = fs.Int64("int64", 0, "") + _ = fs.Uint("uint", 0, "") + _ = fs.Uint64("uint64", 0, "") + _ = fs.Float64("float64", 0, "") + // Strings cannot give errors, and bools and durations do not return strconv.NumError. + err := fs.Parse([]string{arg}) + if err == nil { + t.Errorf("Parse(%q)=%v; expected range error", arg, err) + continue + } + if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "value out of range") { + t.Errorf("Parse(%q)=%v; expected range error", arg, err) + } + } +} + +func TestExitCode(t *testing.T) { + testenv.MustHaveExec(t) + + magic := 123 + if os.Getenv("GO_CHILD_FLAG") != "" { + fs := NewFlagSet("test", ExitOnError) + if os.Getenv("GO_CHILD_FLAG_HANDLE") != "" { + var b bool + fs.BoolVar(&b, os.Getenv("GO_CHILD_FLAG_HANDLE"), false, "") + } + fs.Parse([]string{os.Getenv("GO_CHILD_FLAG")}) + os.Exit(magic) + } + + tests := []struct { + flag string + flagHandle string + expectExit int + }{ + { + flag: "-h", + expectExit: 0, + }, + { + flag: "-help", + expectExit: 0, + }, + { + flag: "-undefined", + expectExit: 2, + }, + { + flag: "-h", + flagHandle: "h", + expectExit: magic, + }, + { + flag: "-help", + flagHandle: "help", + expectExit: magic, + }, + } + + for _, test := range tests { + cmd := exec.Command(testenv.Executable(t), "-test.run=^TestExitCode$") + cmd.Env = append( + os.Environ(), + "GO_CHILD_FLAG="+test.flag, + "GO_CHILD_FLAG_HANDLE="+test.flagHandle, + ) + cmd.Run() + got := cmd.ProcessState.ExitCode() + // ExitCode is either 0 or 1 on Plan 9. + if runtime.GOOS == "plan9" && test.expectExit != 0 { + test.expectExit = 1 + } + if got != test.expectExit { + t.Errorf("unexpected exit code for test case %+v \n: got %d, expect %d", + test, got, test.expectExit) + } + } +} + +func mustPanic(t *testing.T, testName string, expected string, f func()) { + t.Helper() + defer func() { + switch msg := recover().(type) { + case nil: + t.Errorf("%s\n: expected panic(%q), but did not panic", testName, expected) + case string: + if ok, _ := regexp.MatchString(expected, msg); !ok { + t.Errorf("%s\n: expected panic(%q), but got panic(%q)", testName, expected, msg) + } + default: + t.Errorf("%s\n: expected panic(%q), but got panic(%T%v)", testName, expected, msg, msg) + } + }() + f() +} + +func TestInvalidFlags(t *testing.T) { + tests := []struct { + flag string + errorMsg string + }{ + { + flag: "-foo", + errorMsg: "flag \"-foo\" begins with -", + }, + { + flag: "foo=bar", + errorMsg: "flag \"foo=bar\" contains =", + }, + } + + for _, test := range tests { + testName := fmt.Sprintf("FlagSet.Var(&v, %q, \"\")", test.flag) + + fs := NewFlagSet("", ContinueOnError) + buf := &strings.Builder{} + fs.SetOutput(buf) + + mustPanic(t, testName, test.errorMsg, func() { + var v flagVar + fs.Var(&v, test.flag, "") + }) + if msg := test.errorMsg + "\n"; msg != buf.String() { + t.Errorf("%s\n: unexpected output: expected %q, bug got %q", testName, msg, buf) + } + } +} + +func TestRedefinedFlags(t *testing.T) { + tests := []struct { + flagSetName string + errorMsg string + }{ + { + flagSetName: "", + errorMsg: "flag redefined: foo", + }, + { + flagSetName: "fs", + errorMsg: "fs flag redefined: foo", + }, + } + + for _, test := range tests { + testName := fmt.Sprintf("flag redefined in FlagSet(%q)", test.flagSetName) + + fs := NewFlagSet(test.flagSetName, ContinueOnError) + buf := &strings.Builder{} + fs.SetOutput(buf) + + var v flagVar + fs.Var(&v, "foo", "") + + mustPanic(t, testName, test.errorMsg, func() { + fs.Var(&v, "foo", "") + }) + if msg := test.errorMsg + "\n"; msg != buf.String() { + t.Errorf("%s\n: unexpected output: expected %q, bug got %q", testName, msg, buf) + } + } +} + +func TestUserDefinedBoolFunc(t *testing.T) { + flags := NewFlagSet("test", ContinueOnError) + flags.SetOutput(io.Discard) + var ss []string + flags.BoolFunc("v", "usage", func(s string) error { + ss = append(ss, s) + return nil + }) + if err := flags.Parse([]string{"-v", "", "-v", "1", "-v=2"}); err != nil { + t.Error(err) + } + if len(ss) != 1 { + t.Fatalf("got %d args; want 1 arg", len(ss)) + } + want := "[true]" + if got := fmt.Sprint(ss); got != want { + t.Errorf("got %q; want %q", got, want) + } + // test usage + var buf strings.Builder + flags.SetOutput(&buf) + flags.Parse([]string{"-h"}) + if usage := buf.String(); !strings.Contains(usage, "usage") { + t.Errorf("usage string not included: %q", usage) + } + // test BoolFunc error + flags = NewFlagSet("test", ContinueOnError) + flags.SetOutput(io.Discard) + flags.BoolFunc("v", "usage", func(s string) error { + return fmt.Errorf("test error") + }) + // flag not set, so no error + if err := flags.Parse(nil); err != nil { + t.Error(err) + } + // flag set, expect error + if err := flags.Parse([]string{"-v", ""}); err == nil { + t.Error("got err == nil; want err != nil") + } else if errMsg := err.Error(); !strings.Contains(errMsg, "test error") { + t.Errorf(`got %q; error should contain "test error"`, errMsg) + } +} + +func TestDefineAfterSet(t *testing.T) { + flags := NewFlagSet("test", ContinueOnError) + // Set by itself doesn't panic. + flags.Set("myFlag", "value") + + // Define-after-set panics. + mustPanic(t, "DefineAfterSet", "flag myFlag set at .*/flag_test.go:.* before being defined", func() { + _ = flags.String("myFlag", "default", "usage") + }) +} diff --git a/go/src/fmt/doc.go b/go/src/fmt/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..46f30b44e9a72289772d7078377e61db9259c896 --- /dev/null +++ b/go/src/fmt/doc.go @@ -0,0 +1,399 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package fmt implements formatted I/O with functions analogous +to C's printf and scanf. The format 'verbs' are derived from C's but +are simpler. + +# Printing + +There are four families of printing functions defined by their output destination. +[Print], [Println] and [Printf] write to [os.Stdout]; +[Sprint], [Sprintln] and [Sprintf] return a string; +[Fprint], [Fprintln] and [Fprintf] write to an [io.Writer]; and +[Append], [Appendln] and [Appendf] append the output to a byte slice. + +The functions within each family do the formatting according to the end of the name. +Print, Sprint, Fprint and Append use the default format for each argument, +adding a space between operands when neither is a string. +Println, Sprintln, Fprintln and Appendln always add spaces and append a newline. +Printf, Sprintf, Fprintf and Appendf use a sequence of "verbs" to control the formatting. + +The verbs: + +General: + + %v the value in a default format + when printing structs, the plus flag (%+v) adds field names + %#v a Go-syntax representation of the value + (floating-point infinities and NaNs print as ±Inf and NaN) + %T a Go-syntax representation of the type of the value + %% a literal percent sign; consumes no value + +Boolean: + + %t the word true or false + +Integer: + + %b base 2 + %c the character represented by the corresponding Unicode code point + %d base 10 + %o base 8 + %O base 8 with 0o prefix + %q a single-quoted character literal safely escaped with Go syntax. + %x base 16, with lower-case letters for a-f + %X base 16, with upper-case letters for A-F + %U Unicode format: U+1234; same as "U+%04X" + +Floating-point and complex constituents: + + %b decimalless scientific notation with exponent a power of two, + in the manner of strconv.FormatFloat with the 'b' format, + e.g. -123456p-78 + %e scientific notation, e.g. -1.234456e+78 + %E scientific notation, e.g. -1.234456E+78 + %f decimal point but no exponent, e.g. 123.456 + %F synonym for %f + %g %e for large exponents, %f otherwise. Precision is discussed below. + %G %E for large exponents, %F otherwise + %x hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20 + %X upper-case hexadecimal notation, e.g. -0X1.23ABCP+20 + + The exponent is always a decimal integer. + For formats other than %b the exponent is at least two digits. + +String and slice of bytes (treated equivalently with these verbs): + + %s the uninterpreted bytes of the string or slice + %q a double-quoted string safely escaped with Go syntax + %x base 16, lower-case, two characters per byte + %X base 16, upper-case, two characters per byte + +Slice: + + %p address of 0th element in base 16 notation, with leading 0x + +Pointer: + + %p base 16 notation, with leading 0x + The %b, %d, %o, %x and %X verbs also work with pointers, + formatting the value exactly as if it were an integer. + +The default format for %v is: + + bool: %t + int, int8 etc.: %d + uint, uint8 etc.: %d, %#x if printed with %#v + float32, complex64, etc: %g + string: %s + chan: %p + pointer: %p + +For compound objects, the elements are printed using these rules, recursively, +laid out like this: + + struct: {field0 field1 ...} + array, slice: [elem0 elem1 ...] + maps: map[key1:value1 key2:value2 ...] + pointer to above: &{}, &[], &map[] + +Width is specified by an optional decimal number immediately preceding the verb. +If absent, the width is whatever is necessary to represent the value. +Precision is specified after the (optional) width by a period followed by a +decimal number. If no period is present, a default precision is used. +A period with no following number specifies a precision of zero. +Examples: + + %f default width, default precision + %9f width 9, default precision + %.2f default width, precision 2 + %9.2f width 9, precision 2 + %9.f width 9, precision 0 + +Width and precision are measured in units of Unicode code points, +that is, runes. (This differs from C's printf where the +units are always measured in bytes.) Either or both of the flags +may be replaced with the character '*', causing their values to be +obtained from the next operand (preceding the one to format), +which must be of type int. + +For most values, width is the minimum number of runes to output, +padding the formatted form with spaces if necessary. + +For strings, byte slices and byte arrays, however, precision +limits the length of the input to be formatted (not the size of +the output), truncating if necessary. Normally it is measured in +runes, but for these types when formatted with the %x or %X format +it is measured in bytes. + +For floating-point values, width sets the minimum width of the field and +precision sets the number of places after the decimal, if appropriate, +except that for %g/%G precision sets the maximum number of significant +digits (trailing zeros are removed). For example, given 12.345 the format +%6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f +and %#g is 6; for %g it is the smallest number of digits necessary to identify +the value uniquely. + +For complex numbers, the width and precision apply to the two +components independently and the result is parenthesized, so %f applied +to 1.2+3.4i produces (1.200000+3.400000i). + +When formatting a single integer code point or a rune string (type []rune) +with %q, invalid Unicode code points are changed to the Unicode replacement +character, U+FFFD, as in [strconv.QuoteRune]. + +Other flags: + + '+' always print a sign for numeric values; + guarantee ASCII-only output for %q (%+q) + '-' pad with spaces on the right rather than the left (left-justify the field) + '#' alternate format: add leading 0b for binary (%#b), 0 for octal (%#o), + 0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p); + for %q, print a raw (backquoted) string if [strconv.CanBackquote] + returns true; + always print a decimal point for %e, %E, %f, %F, %g and %G; + do not remove trailing zeros for %g and %G; + write e.g. U+0078 'x' if the character is printable for %U (%#U) + ' ' (space) leave a space for elided sign in numbers (% d); + put spaces between bytes printing strings or slices in hex (% x, % X) + '0' pad with leading zeros rather than spaces; + for numbers, this moves the padding after the sign + +Flags are ignored by verbs that do not expect them. +For example there is no alternate decimal format, so %#d and %d +behave identically. + +For each Printf-like function, there is also a Print function +that takes no format and is equivalent to saying %v for every +operand. Another variant Println inserts blanks between +operands and appends a newline. + +Regardless of the verb, if an operand is an interface value, +the internal concrete value is used, not the interface itself. +Thus: + + var i interface{} = 23 + fmt.Printf("%v\n", i) + +will print 23. + +Except when printed using the verbs %T and %p, special +formatting considerations apply for operands that implement +certain interfaces. In order of application: + +1. If the operand is a [reflect.Value], the operand is replaced by the +concrete value that it holds, and printing continues with the next rule. + +2. If an operand implements the [Formatter] interface, it will +be invoked. In this case the interpretation of verbs and flags is +controlled by that implementation. + +3. If the %v verb is used with the # flag (%#v) and the operand +implements the [GoStringer] interface, that will be invoked. + +If the format (which is implicitly %v for [Println] etc.) is valid +for a string (%s %q %x %X), or is %v but not %#v, +the following two rules apply: + +4. If an operand implements the error interface, the Error method +will be invoked to convert the object to a string, which will then +be formatted as required by the verb (if any). + +5. If an operand implements method String() string, that method +will be invoked to convert the object to a string, which will then +be formatted as required by the verb (if any). + +For compound operands such as slices and structs, the format +applies to the elements of each operand, recursively, not to the +operand as a whole. Thus %q will quote each element of a slice +of strings, and %6.2f will control formatting for each element +of a floating-point array. + +However, when printing a byte slice with a string-like verb +(%s %q %x %X), it is treated identically to a string, as a single item. + +To avoid recursion in cases such as + + type X string + func (x X) String() string { return Sprintf("<%s>", x) } + +convert the value before recurring: + + func (x X) String() string { return Sprintf("<%s>", string(x)) } + +Infinite recursion can also be triggered by self-referential data +structures, such as a slice that contains itself as an element, if +that type has a String method. Such pathologies are rare, however, +and the package does not protect against them. + +When printing a struct, fmt cannot and therefore does not invoke +formatting methods such as Error or String on unexported fields. + +# Explicit argument indexes + +In [Printf], [Sprintf], [Fprintf], and [Appendf], the default behavior is for each +formatting verb to format successive arguments passed in the call. +However, the notation [n] immediately before the verb indicates that the +nth one-indexed argument is to be formatted instead. The same notation +before a '*' for a width or precision selects the argument index holding +the value. After processing a bracketed expression [n], subsequent verbs +will use arguments n+1, n+2, etc. unless otherwise directed. + +For example, + + fmt.Sprintf("%[2]d %[1]d\n", 11, 22) + +will yield "22 11", while + + fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6) + +equivalent to + + fmt.Sprintf("%6.2f", 12.0) + +will yield " 12.00". Because an explicit index affects subsequent verbs, +this notation can be used to print the same values multiple times +by resetting the index for the first argument to be repeated: + + fmt.Sprintf("%d %d %#[1]x %#x", 16, 17) + +will yield "16 17 0x10 0x11". + +# Format errors + +If an invalid argument is given for a verb, such as providing +a string to %d, the generated string will contain a +description of the problem, as in these examples: + + Wrong type or unknown verb: %!verb(type=value) + Printf("%d", "hi"): %!d(string=hi) + Too many arguments: %!(EXTRA type=value) + Printf("hi", "guys"): hi%!(EXTRA string=guys) + Too few arguments: %!verb(MISSING) + Printf("hi%d"): hi%!d(MISSING) + Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC) + Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi + Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi + Invalid or invalid use of argument index: %!(BADINDEX) + Printf("%*[2]d", 7): %!d(BADINDEX) + Printf("%.[2]d", 7): %!d(BADINDEX) + +All errors begin with the string "%!" followed sometimes +by a single character (the verb) and end with a parenthesized +description. + +If an Error or String method triggers a panic when called by a +print routine, the fmt package reformats the error message +from the panic, decorating it with an indication that it came +through the fmt package. For example, if a String method +calls panic("bad"), the resulting formatted message will look +like + + %!s(PANIC=bad) + +The %!s just shows the print verb in use when the failure +occurred. If the panic is caused by a nil receiver to an Error, +String, or GoString method, however, the output is the undecorated +string, "". + +# Scanning + +An analogous set of functions scans formatted text to yield +values. [Scan], [Scanf] and [Scanln] read from [os.Stdin]; [Fscan], +[Fscanf] and [Fscanln] read from a specified [io.Reader]; [Sscan], +[Sscanf] and [Sscanln] read from an argument string. + +[Scan], [Fscan], [Sscan] treat newlines in the input as spaces. + +[Scanln], [Fscanln] and [Sscanln] stop scanning at a newline and +require that the items be followed by a newline or EOF. + +[Scanf], [Fscanf], and [Sscanf] parse the arguments according to a +format string, analogous to that of [Printf]. In the text that +follows, 'space' means any Unicode whitespace character +except newline. + +In the format string, a verb introduced by the % character +consumes and parses input; these verbs are described in more +detail below. A character other than %, space, or newline in +the format consumes exactly that input character, which must +be present. A newline with zero or more spaces before it in +the format string consumes zero or more spaces in the input +followed by a single newline or the end of the input. A space +following a newline in the format string consumes zero or more +spaces in the input. Otherwise, any run of one or more spaces +in the format string consumes as many spaces as possible in +the input. Unless the run of spaces in the format string +appears adjacent to a newline, the run must consume at least +one space from the input or find the end of the input. + +The handling of spaces and newlines differs from that of C's +scanf family: in C, newlines are treated as any other space, +and it is never an error when a run of spaces in the format +string finds no spaces to consume in the input. + +The verbs behave analogously to those of [Printf]. +For example, %x will scan an integer as a hexadecimal number, +and %v will scan the default representation format for the value. +The [Printf] verbs %p and %T and the flags # and + are not implemented. +For floating-point and complex values, all valid formatting verbs +(%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept +both decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8") +and digit-separating underscores (for example: "3.14159_26535_89793"). + +Input processed by verbs is implicitly space-delimited: the +implementation of every verb except %c starts by discarding +leading spaces from the remaining input, and the %s verb +(and %v reading into a string) stops consuming input at the first +space or newline character. + +The familiar base-setting prefixes 0b (binary), 0o and 0 (octal), +and 0x (hexadecimal) are accepted when scanning integers +without a format or with the %v verb, as are digit-separating +underscores. + +Width is interpreted in the input text but there is no +syntax for scanning with a precision (no %5.2f, just %5f). +If width is provided, it applies after leading spaces are +trimmed and specifies the maximum number of runes to read +to satisfy the verb. For example, + + Sscanf(" 1234567 ", "%5s%d", &s, &i) + +will set s to "12345" and i to 67 while + + Sscanf(" 12 34 567 ", "%5s%d", &s, &i) + +will set s to "12" and i to 34. + +In all the scanning functions, a carriage return followed +immediately by a newline is treated as a plain newline +(\r\n means the same as \n). + +In all the scanning functions, if an operand implements method +[Scan] (that is, it implements the [Scanner] interface) that +method will be used to scan the text for that operand. Also, +if the number of arguments scanned is less than the number of +arguments provided, an error is returned. + +All arguments to be scanned must be either pointers to basic +types or implementations of the [Scanner] interface. + +Like [Scanf] and [Fscanf], [Sscanf] need not consume its entire input. +There is no way to recover how much of the input string [Sscanf] used. + +Note: [Fscan] etc. can read one character (rune) past the input +they return, which means that a loop calling a scan routine +may skip some of the input. This is usually a problem only +when there is no space between input values. If the reader +provided to [Fscan] implements ReadRune, that method will be used +to read characters. If the reader also implements UnreadRune, +that method will be used to save the character and successive +calls will not lose data. To attach ReadRune and UnreadRune +methods to a reader without that capability, use +[bufio.NewReader]. +*/ +package fmt diff --git a/go/src/fmt/errors.go b/go/src/fmt/errors.go new file mode 100644 index 0000000000000000000000000000000000000000..a0ce7ada346dbc0dbb122e1c5006c1ab89bb1e69 --- /dev/null +++ b/go/src/fmt/errors.go @@ -0,0 +1,94 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt + +import ( + "errors" + "internal/stringslite" + "slices" +) + +// Errorf formats according to a format specifier and returns the string as a +// value that satisfies error. +// +// If the format specifier includes a %w verb with an error operand, +// the returned error will implement an Unwrap method returning the operand. +// If there is more than one %w verb, the returned error will implement an +// Unwrap method returning a []error containing all the %w operands in the +// order they appear in the arguments. +// It is invalid to supply the %w verb with an operand that does not implement +// the error interface. The %w verb is otherwise a synonym for %v. +func Errorf(format string, a ...any) (err error) { + // This function has been split in a somewhat unnatural way + // so that both it and the errors.New call can be inlined. + if err = errorf(format, a...); err != nil { + return err + } + // No formatting was needed. We can avoid some allocations and other work. + // See https://go.dev/cl/708836 for details. + return errors.New(format) +} + +// errorf formats and returns an error value, or nil if no formatting is required. +func errorf(format string, a ...any) error { + if len(a) == 0 && stringslite.IndexByte(format, '%') == -1 { + return nil + } + p := newPrinter() + p.wrapErrs = true + p.doPrintf(format, a) + s := string(p.buf) + var err error + switch len(p.wrappedErrs) { + case 0: + err = errors.New(s) + case 1: + w := &wrapError{msg: s} + w.err, _ = a[p.wrappedErrs[0]].(error) + err = w + default: + if p.reordered { + slices.Sort(p.wrappedErrs) + } + var errs []error + for i, argNum := range p.wrappedErrs { + if i > 0 && p.wrappedErrs[i-1] == argNum { + continue + } + if e, ok := a[argNum].(error); ok { + errs = append(errs, e) + } + } + err = &wrapErrors{s, errs} + } + p.free() + return err +} + +type wrapError struct { + msg string + err error +} + +func (e *wrapError) Error() string { + return e.msg +} + +func (e *wrapError) Unwrap() error { + return e.err +} + +type wrapErrors struct { + msg string + errs []error +} + +func (e *wrapErrors) Error() string { + return e.msg +} + +func (e *wrapErrors) Unwrap() []error { + return e.errs +} diff --git a/go/src/fmt/errors_test.go b/go/src/fmt/errors_test.go new file mode 100644 index 0000000000000000000000000000000000000000..52bf42d0a623a682dd03fd5016f2af90a48001ba --- /dev/null +++ b/go/src/fmt/errors_test.go @@ -0,0 +1,116 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + "errors" + "fmt" + "reflect" + "testing" +) + +func TestErrorf(t *testing.T) { + // noVetErrorf is an alias for fmt.Errorf that does not trigger vet warnings for + // %w format strings. + noVetErrorf := fmt.Errorf + + wrapped := errors.New("inner error") + for _, test := range []struct { + err error + wantText string + wantUnwrap error + wantSplit []error + }{{ + err: fmt.Errorf("%w", wrapped), + wantText: "inner error", + wantUnwrap: wrapped, + }, { + err: fmt.Errorf("added context: %w", wrapped), + wantText: "added context: inner error", + wantUnwrap: wrapped, + }, { + err: fmt.Errorf("%w with added context", wrapped), + wantText: "inner error with added context", + wantUnwrap: wrapped, + }, { + err: fmt.Errorf("%s %w %v", "prefix", wrapped, "suffix"), + wantText: "prefix inner error suffix", + wantUnwrap: wrapped, + }, { + err: fmt.Errorf("%[2]s: %[1]w", wrapped, "positional verb"), + wantText: "positional verb: inner error", + wantUnwrap: wrapped, + }, { + err: fmt.Errorf("%v", wrapped), + wantText: "inner error", + }, { + err: fmt.Errorf("added context: %v", wrapped), + wantText: "added context: inner error", + }, { + err: fmt.Errorf("%v with added context", wrapped), + wantText: "inner error with added context", + }, { + err: noVetErrorf("%w is not an error", "not-an-error"), + wantText: "%!w(string=not-an-error) is not an error", + }, { + err: fmt.Errorf("no verbs"), + wantText: "no verbs", + }, { + err: noVetErrorf("no verbs with extra arg", "extra"), + wantText: "no verbs with extra arg%!(EXTRA string=extra)", + }, { + err: noVetErrorf("too many verbs: %w %v"), + wantText: "too many verbs: %!w(MISSING) %!v(MISSING)", + }, { + err: noVetErrorf("wrapped two errors: %w %w", errString("1"), errString("2")), + wantText: "wrapped two errors: 1 2", + wantSplit: []error{errString("1"), errString("2")}, + }, { + err: noVetErrorf("wrapped three errors: %w %w %w", errString("1"), errString("2"), errString("3")), + wantText: "wrapped three errors: 1 2 3", + wantSplit: []error{errString("1"), errString("2"), errString("3")}, + }, { + err: noVetErrorf("wrapped nil error: %w %w %w", errString("1"), nil, errString("2")), + wantText: "wrapped nil error: 1 %!w() 2", + wantSplit: []error{errString("1"), errString("2")}, + }, { + err: noVetErrorf("wrapped one non-error: %w %w %w", errString("1"), "not-an-error", errString("3")), + wantText: "wrapped one non-error: 1 %!w(string=not-an-error) 3", + wantSplit: []error{errString("1"), errString("3")}, + }, { + err: fmt.Errorf("wrapped errors out of order: %[3]w %[2]w %[1]w", errString("1"), errString("2"), errString("3")), + wantText: "wrapped errors out of order: 3 2 1", + wantSplit: []error{errString("1"), errString("2"), errString("3")}, + }, { + err: fmt.Errorf("wrapped several times: %[1]w %[1]w %[2]w %[1]w", errString("1"), errString("2")), + wantText: "wrapped several times: 1 1 2 1", + wantSplit: []error{errString("1"), errString("2")}, + }, { + err: fmt.Errorf("%w", nil), + wantText: "%!w()", + wantUnwrap: nil, // still nil + }} { + if got, want := errors.Unwrap(test.err), test.wantUnwrap; got != want { + t.Errorf("Formatted error: %v\nerrors.Unwrap() = %v, want %v", test.err, got, want) + } + if got, want := splitErr(test.err), test.wantSplit; !reflect.DeepEqual(got, want) { + t.Errorf("Formatted error: %v\nUnwrap() []error = %v, want %v", test.err, got, want) + } + if got, want := test.err.Error(), test.wantText; got != want { + t.Errorf("err.Error() = %q, want %q", got, want) + } + } +} + +func splitErr(err error) []error { + if e, ok := err.(interface{ Unwrap() []error }); ok { + return e.Unwrap() + } + return nil +} + +type errString string + +func (e errString) Error() string { return string(e) } diff --git a/go/src/fmt/example_test.go b/go/src/fmt/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5962834226b9d58564eafa1b240a9ff4e99171fc --- /dev/null +++ b/go/src/fmt/example_test.go @@ -0,0 +1,365 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + "fmt" + "io" + "math" + "os" + "strings" + "time" +) + +// The Errorf function lets us use formatting features +// to create descriptive error messages. +func ExampleErrorf() { + const name, id = "bueller", 17 + err := fmt.Errorf("user %q (id %d) not found", name, id) + fmt.Println(err.Error()) + + // Output: user "bueller" (id 17) not found +} + +func ExampleFscanf() { + var ( + i int + b bool + s string + ) + r := strings.NewReader("5 true gophers") + n, err := fmt.Fscanf(r, "%d %t %s", &i, &b, &s) + if err != nil { + fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err) + } + fmt.Println(i, b, s) + fmt.Println(n) + // Output: + // 5 true gophers + // 3 +} + +func ExampleFscanln() { + s := `dmr 1771 1.61803398875 + ken 271828 3.14159` + r := strings.NewReader(s) + var a string + var b int + var c float64 + for { + n, err := fmt.Fscanln(r, &a, &b, &c) + if err == io.EOF { + break + } + if err != nil { + panic(err) + } + fmt.Printf("%d: %s, %d, %f\n", n, a, b, c) + } + // Output: + // 3: dmr, 1771, 1.618034 + // 3: ken, 271828, 3.141590 +} + +func ExampleSscanf() { + var name string + var age int + n, err := fmt.Sscanf("Kim is 22 years old", "%s is %d years old", &name, &age) + if err != nil { + panic(err) + } + fmt.Printf("%d: %s, %d\n", n, name, age) + + // Output: + // 2: Kim, 22 +} + +func ExamplePrint() { + const name, age = "Kim", 22 + fmt.Print(name, " is ", age, " years old.\n") + + // It is conventional not to worry about any + // error returned by Print. + + // Output: + // Kim is 22 years old. +} + +func ExamplePrintln() { + const name, age = "Kim", 22 + fmt.Println(name, "is", age, "years old.") + + // It is conventional not to worry about any + // error returned by Println. + + // Output: + // Kim is 22 years old. +} + +func ExamplePrintf() { + const name, age = "Kim", 22 + fmt.Printf("%s is %d years old.\n", name, age) + + // It is conventional not to worry about any + // error returned by Printf. + + // Output: + // Kim is 22 years old. +} + +func ExampleSprint() { + const name, age = "Kim", 22 + s := fmt.Sprint(name, " is ", age, " years old.\n") + + io.WriteString(os.Stdout, s) // Ignoring error for simplicity. + + // Output: + // Kim is 22 years old. +} + +func ExampleSprintln() { + const name, age = "Kim", 22 + s := fmt.Sprintln(name, "is", age, "years old.") + + io.WriteString(os.Stdout, s) // Ignoring error for simplicity. + + // Output: + // Kim is 22 years old. +} + +func ExampleSprintf() { + const name, age = "Kim", 22 + s := fmt.Sprintf("%s is %d years old.\n", name, age) + + io.WriteString(os.Stdout, s) // Ignoring error for simplicity. + + // Output: + // Kim is 22 years old. +} + +func ExampleFprint() { + const name, age = "Kim", 22 + n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n") + + // The n and err return values from Fprint are + // those returned by the underlying io.Writer. + if err != nil { + fmt.Fprintf(os.Stderr, "Fprint: %v\n", err) + } + fmt.Print(n, " bytes written.\n") + + // Output: + // Kim is 22 years old. + // 21 bytes written. +} + +func ExampleFprintln() { + const name, age = "Kim", 22 + n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.") + + // The n and err return values from Fprintln are + // those returned by the underlying io.Writer. + if err != nil { + fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err) + } + fmt.Println(n, "bytes written.") + + // Output: + // Kim is 22 years old. + // 21 bytes written. +} + +func ExampleFprintf() { + const name, age = "Kim", 22 + n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age) + + // The n and err return values from Fprintf are + // those returned by the underlying io.Writer. + if err != nil { + fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err) + } + fmt.Printf("%d bytes written.\n", n) + + // Output: + // Kim is 22 years old. + // 21 bytes written. +} + +// Print, Println, and Printf lay out their arguments differently. In this example +// we can compare their behaviors. Println always adds blanks between the items it +// prints, while Print adds blanks only between non-string arguments and Printf +// does exactly what it is told. +// Sprint, Sprintln, Sprintf, Fprint, Fprintln, and Fprintf behave the same as +// their corresponding Print, Println, and Printf functions shown here. +func Example_printers() { + a, b := 3.0, 4.0 + h := math.Hypot(a, b) + + // Print inserts blanks between arguments when neither is a string. + // It does not add a newline to the output, so we add one explicitly. + fmt.Print("The vector (", a, b, ") has length ", h, ".\n") + + // Println always inserts spaces between its arguments, + // so it cannot be used to produce the same output as Print in this case; + // its output has extra spaces. + // Also, Println always adds a newline to the output. + fmt.Println("The vector (", a, b, ") has length", h, ".") + + // Printf provides complete control but is more complex to use. + // It does not add a newline to the output, so we add one explicitly + // at the end of the format specifier string. + fmt.Printf("The vector (%g %g) has length %g.\n", a, b, h) + + // Output: + // The vector (3 4) has length 5. + // The vector ( 3 4 ) has length 5 . + // The vector (3 4) has length 5. +} + +// These examples demonstrate the basics of printing using a format string. Printf, +// Sprintf, and Fprintf all take a format string that specifies how to format the +// subsequent arguments. For example, %d (we call that a 'verb') says to print the +// corresponding argument, which must be an integer (or something containing an +// integer, such as a slice of ints) in decimal. The verb %v ('v' for 'value') +// always formats the argument in its default form, just how Print or Println would +// show it. The special verb %T ('T' for 'Type') prints the type of the argument +// rather than its value. The examples are not exhaustive; see the package comment +// for all the details. +func Example_formats() { + // A basic set of examples showing that %v is the default format, in this + // case decimal for integers, which can be explicitly requested with %d; + // the output is just what Println generates. + integer := 23 + // Each of these prints "23" (without the quotes). + fmt.Println(integer) + fmt.Printf("%v\n", integer) + fmt.Printf("%d\n", integer) + + // The special verb %T shows the type of an item rather than its value. + fmt.Printf("%T %T\n", integer, &integer) + // Result: int *int + + // Println(x) is the same as Printf("%v\n", x) so we will use only Printf + // in the following examples. Each one demonstrates how to format values of + // a particular type, such as integers or strings. We start each format + // string with %v to show the default output and follow that with one or + // more custom formats. + + // Booleans print as "true" or "false" with %v or %t. + truth := true + fmt.Printf("%v %t\n", truth, truth) + // Result: true true + + // Integers print as decimals with %v and %d, + // or in hex with %x, octal with %o, or binary with %b. + answer := 42 + fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer) + // Result: 42 42 2a 52 101010 + + // Floats have multiple formats: %v and %g print a compact representation, + // while %f prints a decimal point and %e uses exponential notation. The + // format %6.2f used here shows how to set the width and precision to + // control the appearance of a floating-point value. In this instance, 6 is + // the total width of the printed text for the value (note the extra spaces + // in the output) and 2 is the number of decimal places to show. + pi := math.Pi + fmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi) + // Result: 3.141592653589793 3.141592653589793 3.14 ( 3.14) 3.141593e+00 + + // Complex numbers format as parenthesized pairs of floats, with an 'i' + // after the imaginary part. + point := 110.7 + 22.5i + fmt.Printf("%v %g %.2f %.2e\n", point, point, point, point) + // Result: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i) + + // Runes are integers but when printed with %c show the character with that + // Unicode value. The %q verb shows them as quoted characters, %U as a + // hex Unicode code point, and %#U as both a code point and a quoted + // printable form if the rune is printable. + smile := '😀' + fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile) + // Result: 128512 128512 😀 '😀' U+1F600 U+1F600 '😀' + + // Strings are formatted with %v and %s as-is, with %q as quoted strings, + // and %#q as backquoted strings. + placeholders := `foo "bar"` + fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders) + // Result: foo "bar" foo "bar" "foo \"bar\"" `foo "bar"` + + // Maps formatted with %v show keys and values in their default formats. + // The %#v form (the # is called a "flag" in this context) shows the map in + // the Go source format. Maps are printed in a consistent order, sorted + // by the values of the keys. + isLegume := map[string]bool{ + "peanut": true, + "dachshund": false, + } + fmt.Printf("%v %#v\n", isLegume, isLegume) + // Result: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true} + + // Structs formatted with %v show field values in their default formats. + // The %+v form shows the fields by name, while %#v formats the struct in + // Go source format. + person := struct { + Name string + Age int + }{"Kim", 22} + fmt.Printf("%v %+v %#v\n", person, person, person) + // Result: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22} + + // The default format for a pointer shows the underlying value preceded by + // an ampersand. The %p verb prints the pointer value in hex. We use a + // typed nil for the argument to %p here because the value of any non-nil + // pointer would change from run to run; run the commented-out Printf + // call yourself to see. + pointer := &person + fmt.Printf("%v %p\n", pointer, (*int)(nil)) + // Result: &{Kim 22} 0x0 + // fmt.Printf("%v %p\n", pointer, pointer) + // Result: &{Kim 22} 0x010203 // See comment above. + + // Arrays and slices are formatted by applying the format to each element. + greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"} + fmt.Printf("%v %q\n", greats, greats) + // Result: [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"] + + kGreats := greats[:3] + fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats) + // Result: [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"} + + // Byte slices are special. Integer verbs like %d print the elements in + // that format. The %s and %q forms treat the slice like a string. The %x + // verb has a special form with the space flag that puts a space between + // the bytes. + cmd := []byte("a⌘") + fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd) + // Result: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98 + + // Types that implement Stringer are printed the same as strings. Because + // Stringers return a string, we can print them using a string-specific + // verb such as %q. + now := time.Unix(123456789, 0).UTC() // time.Time implements fmt.Stringer. + fmt.Printf("%v %q\n", now, now) + // Result: 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC" + + // Output: + // 23 + // 23 + // 23 + // int *int + // true true + // 42 42 2a 52 101010 + // 3.141592653589793 3.141592653589793 3.14 ( 3.14) 3.141593e+00 + // (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i) + // 128512 128512 😀 '😀' U+1F600 U+1F600 '😀' + // foo "bar" foo "bar" "foo \"bar\"" `foo "bar"` + // map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true} + // {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22} + // &{Kim 22} 0x0 + // [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"] + // [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"} + // [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98 + // 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC" +} diff --git a/go/src/fmt/export_test.go b/go/src/fmt/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..14163a29afeb4e1615643220e8d554e1479c3064 --- /dev/null +++ b/go/src/fmt/export_test.go @@ -0,0 +1,8 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt + +var IsSpace = isSpace +var Parsenum = parsenum diff --git a/go/src/fmt/fmt_test.go b/go/src/fmt/fmt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c07da5683c24635d02f26ec31d61aca02b438efd --- /dev/null +++ b/go/src/fmt/fmt_test.go @@ -0,0 +1,2028 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + "bytes" + . "fmt" + "internal/race" + "io" + "math" + "reflect" + "strings" + "testing" + "time" + "unicode" +) + +type ( + renamedBool bool + renamedInt int + renamedInt8 int8 + renamedInt16 int16 + renamedInt32 int32 + renamedInt64 int64 + renamedUint uint + renamedUint8 uint8 + renamedUint16 uint16 + renamedUint32 uint32 + renamedUint64 uint64 + renamedUintptr uintptr + renamedString string + renamedBytes []byte + renamedFloat32 float32 + renamedFloat64 float64 + renamedComplex64 complex64 + renamedComplex128 complex128 +) + +func TestFmtInterface(t *testing.T) { + var i1 any + i1 = "abc" + s := Sprintf("%s", i1) + if s != "abc" { + t.Errorf(`Sprintf("%%s", empty("abc")) = %q want %q`, s, "abc") + } +} + +var ( + NaN = math.NaN() + posInf = math.Inf(1) + negInf = math.Inf(-1) + + intVar = 0 + + array = [5]int{1, 2, 3, 4, 5} + iarray = [4]any{1, "hello", 2.5, nil} + slice = array[:] + islice = iarray[:] +) + +type A struct { + i int + j uint + s string + x []int +} + +type I int + +func (i I) String() string { return Sprintf("<%d>", int(i)) } + +type B struct { + I I + j int +} + +type C struct { + i int + B +} + +type F int + +func (f F) Format(s State, c rune) { + Fprintf(s, "<%c=F(%d)>", c, int(f)) +} + +type G int + +func (g G) GoString() string { + return Sprintf("GoString(%d)", int(g)) +} + +type S struct { + F F // a struct field that Formats + G G // a struct field that GoStrings +} + +type SI struct { + I any +} + +// P is a type with a String method with pointer receiver for testing %p. +type P int + +var pValue P + +func (p *P) String() string { + return "String(p)" +} + +// Fn is a function type with a String method. +type Fn func() int + +func (fn Fn) String() string { return "String(fn)" } + +var fnValue Fn + +// U is a type with two unexported function fields. +type U struct { + u func() string + fn Fn +} + +var barray = [5]renamedUint8{1, 2, 3, 4, 5} +var bslice = barray[:] + +type byteStringer byte + +func (byteStringer) String() string { + return "X" +} + +var byteStringerSlice = []byteStringer{'h', 'e', 'l', 'l', 'o'} + +type byteFormatter byte + +func (byteFormatter) Format(f State, _ rune) { + Fprint(f, "X") +} + +var byteFormatterSlice = []byteFormatter{'h', 'e', 'l', 'l', 'o'} + +type writeStringFormatter string + +func (sf writeStringFormatter) Format(f State, c rune) { + if sw, ok := f.(io.StringWriter); ok { + sw.WriteString("***" + string(sf) + "***") + } +} + +var fmtTests = []struct { + fmt string + val any + out string +}{ + {"%d", 12345, "12345"}, + {"%v", 12345, "12345"}, + {"%t", true, "true"}, + + // basic string + {"%s", "abc", "abc"}, + {"%q", "abc", `"abc"`}, + {"%x", "abc", "616263"}, + {"%x", "\xff\xf0\x0f\xff", "fff00fff"}, + {"%X", "\xff\xf0\x0f\xff", "FFF00FFF"}, + {"%x", "", ""}, + {"% x", "", ""}, + {"%#x", "", ""}, + {"%# x", "", ""}, + {"%x", "xyz", "78797a"}, + {"%X", "xyz", "78797A"}, + {"% x", "xyz", "78 79 7a"}, + {"% X", "xyz", "78 79 7A"}, + {"%#x", "xyz", "0x78797a"}, + {"%#X", "xyz", "0X78797A"}, + {"%# x", "xyz", "0x78 0x79 0x7a"}, + {"%# X", "xyz", "0X78 0X79 0X7A"}, + + // basic bytes + {"%s", []byte("abc"), "abc"}, + {"%s", [3]byte{'a', 'b', 'c'}, "abc"}, + {"%s", &[3]byte{'a', 'b', 'c'}, "&abc"}, + {"%q", []byte("abc"), `"abc"`}, + {"%x", []byte("abc"), "616263"}, + {"%x", []byte("\xff\xf0\x0f\xff"), "fff00fff"}, + {"%X", []byte("\xff\xf0\x0f\xff"), "FFF00FFF"}, + {"%x", []byte(""), ""}, + {"% x", []byte(""), ""}, + {"%#x", []byte(""), ""}, + {"%# x", []byte(""), ""}, + {"%x", []byte("xyz"), "78797a"}, + {"%X", []byte("xyz"), "78797A"}, + {"% x", []byte("xyz"), "78 79 7a"}, + {"% X", []byte("xyz"), "78 79 7A"}, + {"%#x", []byte("xyz"), "0x78797a"}, + {"%#X", []byte("xyz"), "0X78797A"}, + {"%# x", []byte("xyz"), "0x78 0x79 0x7a"}, + {"%# X", []byte("xyz"), "0X78 0X79 0X7A"}, + + // escaped strings + {"%q", "", `""`}, + {"%#q", "", "``"}, + {"%q", "\"", `"\""`}, + {"%#q", "\"", "`\"`"}, + {"%q", "`", `"` + "`" + `"`}, + {"%#q", "`", `"` + "`" + `"`}, + {"%q", "\n", `"\n"`}, + {"%#q", "\n", `"\n"`}, + {"%q", `\n`, `"\\n"`}, + {"%#q", `\n`, "`\\n`"}, + {"%q", "abc", `"abc"`}, + {"%#q", "abc", "`abc`"}, + {"%q", "日本語", `"日本語"`}, + {"%+q", "日本語", `"\u65e5\u672c\u8a9e"`}, + {"%#q", "日本語", "`日本語`"}, + {"%#+q", "日本語", "`日本語`"}, + {"%q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`}, + {"%+q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`}, + {"%#q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`}, + {"%#+q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`}, + {"%q", "☺", `"☺"`}, + {"% q", "☺", `"☺"`}, // The space modifier should have no effect. + {"%+q", "☺", `"\u263a"`}, + {"%#q", "☺", "`☺`"}, + {"%#+q", "☺", "`☺`"}, + {"%10q", "⌘", ` "⌘"`}, + {"%+10q", "⌘", ` "\u2318"`}, + {"%-10q", "⌘", `"⌘" `}, + {"%+-10q", "⌘", `"\u2318" `}, + {"%010q", "⌘", `0000000"⌘"`}, + {"%+010q", "⌘", `00"\u2318"`}, + {"%-010q", "⌘", `"⌘" `}, // 0 has no effect when - is present. + {"%+-010q", "⌘", `"\u2318" `}, + {"%#8q", "\n", ` "\n"`}, + {"%#+8q", "\r", ` "\r"`}, + {"%#-8q", "\t", "` ` "}, + {"%#+-8q", "\b", `"\b" `}, + {"%q", "abc\xffdef", `"abc\xffdef"`}, + {"%+q", "abc\xffdef", `"abc\xffdef"`}, + {"%#q", "abc\xffdef", `"abc\xffdef"`}, + {"%#+q", "abc\xffdef", `"abc\xffdef"`}, + // Runes that are not printable. + {"%q", "\U0010ffff", `"\U0010ffff"`}, + {"%+q", "\U0010ffff", `"\U0010ffff"`}, + {"%#q", "\U0010ffff", "`􏿿`"}, + {"%#+q", "\U0010ffff", "`􏿿`"}, + // Runes that are not valid. + {"%q", string(rune(0x110000)), `"�"`}, + {"%+q", string(rune(0x110000)), `"\ufffd"`}, + {"%#q", string(rune(0x110000)), "`�`"}, + {"%#+q", string(rune(0x110000)), "`�`"}, + + // characters + {"%c", uint('x'), "x"}, + {"%c", 0xe4, "ä"}, + {"%c", 0x672c, "本"}, + {"%c", '日', "日"}, + {"%.0c", '⌘', "⌘"}, // Specifying precision should have no effect. + {"%3c", '⌘', " ⌘"}, + {"%-3c", '⌘', "⌘ "}, + {"%c", uint64(0x100000000), "\ufffd"}, + // Runes that are not printable. + {"%c", '\U00000e00', "\u0e00"}, + {"%c", '\U0010ffff', "\U0010ffff"}, + // Runes that are not valid. + {"%c", -1, "�"}, + {"%c", 0xDC80, "�"}, + {"%c", rune(0x110000), "�"}, + {"%c", int64(0xFFFFFFFFF), "�"}, + {"%c", uint64(0xFFFFFFFFF), "�"}, + + // escaped characters + {"%q", uint(0), `'\x00'`}, + {"%+q", uint(0), `'\x00'`}, + {"%q", '"', `'"'`}, + {"%+q", '"', `'"'`}, + {"%q", '\'', `'\''`}, + {"%+q", '\'', `'\''`}, + {"%q", '`', "'`'"}, + {"%+q", '`', "'`'"}, + {"%q", 'x', `'x'`}, + {"%+q", 'x', `'x'`}, + {"%q", 'ÿ', `'ÿ'`}, + {"%+q", 'ÿ', `'\u00ff'`}, + {"%q", '\n', `'\n'`}, + {"%+q", '\n', `'\n'`}, + {"%q", '☺', `'☺'`}, + {"%+q", '☺', `'\u263a'`}, + {"% q", '☺', `'☺'`}, // The space modifier should have no effect. + {"%.0q", '☺', `'☺'`}, // Specifying precision should have no effect. + {"%10q", '⌘', ` '⌘'`}, + {"%+10q", '⌘', ` '\u2318'`}, + {"%-10q", '⌘', `'⌘' `}, + {"%+-10q", '⌘', `'\u2318' `}, + {"%010q", '⌘', `0000000'⌘'`}, + {"%+010q", '⌘', `00'\u2318'`}, + {"%-010q", '⌘', `'⌘' `}, // 0 has no effect when - is present. + {"%+-010q", '⌘', `'\u2318' `}, + // Runes that are not printable. + {"%q", '\U00000e00', `'\u0e00'`}, + {"%q", '\U0010ffff', `'\U0010ffff'`}, + // Runes that are not valid. + {"%q", int32(-1), `'�'`}, + {"%q", 0xDC80, `'�'`}, + {"%q", rune(0x110000), `'�'`}, + {"%q", int64(0xFFFFFFFFF), `'�'`}, + {"%q", uint64(0xFFFFFFFFF), `'�'`}, + + // width + {"%5s", "abc", " abc"}, + {"%5s", []byte("abc"), " abc"}, + {"%2s", "\u263a", " ☺"}, + {"%2s", []byte("\u263a"), " ☺"}, + {"%-5s", "abc", "abc "}, + {"%-5s", []byte("abc"), "abc "}, + {"%05s", "abc", "00abc"}, + {"%05s", []byte("abc"), "00abc"}, + {"%5s", "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"}, + {"%5s", []byte("abcdefghijklmnopqrstuvwxyz"), "abcdefghijklmnopqrstuvwxyz"}, + {"%.5s", "abcdefghijklmnopqrstuvwxyz", "abcde"}, + {"%.5s", []byte("abcdefghijklmnopqrstuvwxyz"), "abcde"}, + {"%.0s", "日本語日本語", ""}, + {"%.0s", []byte("日本語日本語"), ""}, + {"%.5s", "日本語日本語", "日本語日本"}, + {"%.5s", []byte("日本語日本語"), "日本語日本"}, + {"%.10s", "日本語日本語", "日本語日本語"}, + {"%.10s", []byte("日本語日本語"), "日本語日本語"}, + {"%08q", "abc", `000"abc"`}, + {"%08q", []byte("abc"), `000"abc"`}, + {"%-8q", "abc", `"abc" `}, + {"%-8q", []byte("abc"), `"abc" `}, + {"%.5q", "abcdefghijklmnopqrstuvwxyz", `"abcde"`}, + {"%.5q", []byte("abcdefghijklmnopqrstuvwxyz"), `"abcde"`}, + {"%.5x", "abcdefghijklmnopqrstuvwxyz", "6162636465"}, + {"%.5x", []byte("abcdefghijklmnopqrstuvwxyz"), "6162636465"}, + {"%.3q", "日本語日本語", `"日本語"`}, + {"%.3q", []byte("日本語日本語"), `"日本語"`}, + {"%.1q", "日本語", `"日"`}, + {"%.1q", []byte("日本語"), `"日"`}, + {"%.1x", "日本語", "e6"}, + {"%.1X", []byte("日本語"), "E6"}, + {"%10.1q", "日本語日本語", ` "日"`}, + {"%10.1q", []byte("日本語日本語"), ` "日"`}, + {"%10v", nil, " "}, + {"%-10v", nil, " "}, + + // integers + {"%d", uint(12345), "12345"}, + {"%d", int(-12345), "-12345"}, + {"%d", ^uint8(0), "255"}, + {"%d", ^uint16(0), "65535"}, + {"%d", ^uint32(0), "4294967295"}, + {"%d", ^uint64(0), "18446744073709551615"}, + {"%d", int8(-1 << 7), "-128"}, + {"%d", int16(-1 << 15), "-32768"}, + {"%d", int32(-1 << 31), "-2147483648"}, + {"%d", int64(-1 << 63), "-9223372036854775808"}, + {"%.d", 0, ""}, + {"%.0d", 0, ""}, + {"%6.0d", 0, " "}, + {"%06.0d", 0, " "}, + {"% d", 12345, " 12345"}, + {"%+d", 12345, "+12345"}, + {"%+d", -12345, "-12345"}, + {"%b", 7, "111"}, + {"%b", -6, "-110"}, + {"%#b", 7, "0b111"}, + {"%#b", -6, "-0b110"}, + {"%b", ^uint32(0), "11111111111111111111111111111111"}, + {"%b", ^uint64(0), "1111111111111111111111111111111111111111111111111111111111111111"}, + {"%b", int64(-1 << 63), zeroFill("-1", 63, "")}, + {"%o", 01234, "1234"}, + {"%o", -01234, "-1234"}, + {"%#o", 01234, "01234"}, + {"%#o", -01234, "-01234"}, + {"%O", 01234, "0o1234"}, + {"%O", -01234, "-0o1234"}, + {"%o", ^uint32(0), "37777777777"}, + {"%o", ^uint64(0), "1777777777777777777777"}, + {"%#X", 0, "0X0"}, + {"%x", 0x12abcdef, "12abcdef"}, + {"%X", 0x12abcdef, "12ABCDEF"}, + {"%x", ^uint32(0), "ffffffff"}, + {"%X", ^uint64(0), "FFFFFFFFFFFFFFFF"}, + {"%.20b", 7, "00000000000000000111"}, + {"%10d", 12345, " 12345"}, + {"%10d", -12345, " -12345"}, + {"%+10d", 12345, " +12345"}, + {"%010d", 12345, "0000012345"}, + {"%010d", -12345, "-000012345"}, + {"%20.8d", 1234, " 00001234"}, + {"%20.8d", -1234, " -00001234"}, + {"%020.8d", 1234, " 00001234"}, + {"%020.8d", -1234, " -00001234"}, + {"%-20.8d", 1234, "00001234 "}, + {"%-20.8d", -1234, "-00001234 "}, + {"%-#20.8x", 0x1234abc, "0x01234abc "}, + {"%-#20.8X", 0x1234abc, "0X01234ABC "}, + {"%-#20.8o", 01234, "00001234 "}, + + // Test correct f.intbuf overflow checks. + {"%068d", 1, zeroFill("", 68, "1")}, + {"%068d", -1, zeroFill("-", 67, "1")}, + {"%#.68x", 42, zeroFill("0x", 68, "2a")}, + {"%.68d", -42, zeroFill("-", 68, "42")}, + {"%+.68d", 42, zeroFill("+", 68, "42")}, + {"% .68d", 42, zeroFill(" ", 68, "42")}, + {"% +.68d", 42, zeroFill("+", 68, "42")}, + + // unicode format + {"%U", 0, "U+0000"}, + {"%U", -1, "U+FFFFFFFFFFFFFFFF"}, + {"%U", '\n', `U+000A`}, + {"%#U", '\n', `U+000A`}, + {"%+U", 'x', `U+0078`}, // Plus flag should have no effect. + {"%# U", 'x', `U+0078 'x'`}, // Space flag should have no effect. + {"%#.2U", 'x', `U+0078 'x'`}, // Precisions below 4 should print 4 digits. + {"%U", '\u263a', `U+263A`}, + {"%#U", '\u263a', `U+263A '☺'`}, + {"%U", '\U0001D6C2', `U+1D6C2`}, + {"%#U", '\U0001D6C2', `U+1D6C2 '𝛂'`}, + {"%#14.6U", '⌘', " U+002318 '⌘'"}, + {"%#-14.6U", '⌘', "U+002318 '⌘' "}, + {"%#014.6U", '⌘', " U+002318 '⌘'"}, + {"%#-014.6U", '⌘', "U+002318 '⌘' "}, + {"%.68U", uint(42), zeroFill("U+", 68, "2A")}, + {"%#.68U", '日', zeroFill("U+", 68, "65E5") + " '日'"}, + + // floats + {"%+.3e", 0.0, "+0.000e+00"}, + {"%+.3e", 1.0, "+1.000e+00"}, + {"%+.3x", 0.0, "+0x0.000p+00"}, + {"%+.3x", 1.0, "+0x1.000p+00"}, + {"%+.3f", -1.0, "-1.000"}, + {"%+.3F", -1.0, "-1.000"}, + {"%+.3F", float32(-1.0), "-1.000"}, + {"%+07.2f", 1.0, "+001.00"}, + {"%+07.2f", -1.0, "-001.00"}, + {"%-07.2f", 1.0, "1.00 "}, + {"%-07.2f", -1.0, "-1.00 "}, + {"%+-07.2f", 1.0, "+1.00 "}, + {"%+-07.2f", -1.0, "-1.00 "}, + {"%-+07.2f", 1.0, "+1.00 "}, + {"%-+07.2f", -1.0, "-1.00 "}, + {"%+10.2f", +1.0, " +1.00"}, + {"%+10.2f", -1.0, " -1.00"}, + {"% .3E", -1.0, "-1.000E+00"}, + {"% .3e", 1.0, " 1.000e+00"}, + {"% .3X", -1.0, "-0X1.000P+00"}, + {"% .3x", 1.0, " 0x1.000p+00"}, + {"%+.3g", 0.0, "+0"}, + {"%+.3g", 1.0, "+1"}, + {"%+.3g", -1.0, "-1"}, + {"% .3g", -1.0, "-1"}, + {"% .3g", 1.0, " 1"}, + {"%b", float32(1.0), "8388608p-23"}, + {"%b", 1.0, "4503599627370496p-52"}, + // Test sharp flag used with floats. + {"%#g", 1e-323, "1.00000e-323"}, + {"%#g", -1.0, "-1.00000"}, + {"%#g", 1.1, "1.10000"}, + {"%#g", 123456.0, "123456."}, + {"%#g", 1234567.0, "1.234567e+06"}, + {"%#g", 1230000.0, "1.23000e+06"}, + {"%#g", 1000000.0, "1.00000e+06"}, + {"%#.0f", 1.0, "1."}, + {"%#.0e", 1.0, "1.e+00"}, + {"%#.0x", 1.0, "0x1.p+00"}, + {"%#.0g", 1.0, "1."}, + {"%#.0g", 1100000.0, "1.e+06"}, + {"%#.4f", 1.0, "1.0000"}, + {"%#.4e", 1.0, "1.0000e+00"}, + {"%#.4x", 1.0, "0x1.0000p+00"}, + {"%#.4g", 1.0, "1.000"}, + {"%#.4g", 100000.0, "1.000e+05"}, + {"%#.4g", 1.234, "1.234"}, + {"%#.4g", 0.1234, "0.1234"}, + {"%#.4g", 1.23, "1.230"}, + {"%#.4g", 0.123, "0.1230"}, + {"%#.4g", 1.2, "1.200"}, + {"%#.4g", 0.12, "0.1200"}, + {"%#.4g", 10.2, "10.20"}, + {"%#.4g", 0.0, "0.000"}, + {"%#.4g", 0.012, "0.01200"}, + {"%#.0f", 123.0, "123."}, + {"%#.0e", 123.0, "1.e+02"}, + {"%#.0x", 123.0, "0x1.p+07"}, + {"%#.0g", 123.0, "1.e+02"}, + {"%#.4f", 123.0, "123.0000"}, + {"%#.4e", 123.0, "1.2300e+02"}, + {"%#.4x", 123.0, "0x1.ec00p+06"}, + {"%#.4g", 123.0, "123.0"}, + {"%#.4g", 123000.0, "1.230e+05"}, + {"%#9.4g", 1.0, " 1.000"}, + // The sharp flag has no effect for binary float format. + {"%#b", 1.0, "4503599627370496p-52"}, + // Precision has no effect for binary float format. + {"%.4b", float32(1.0), "8388608p-23"}, + {"%.4b", -1.0, "-4503599627370496p-52"}, + // Test correct f.intbuf boundary checks. + {"%.68f", 1.0, zeroFill("1.", 68, "")}, + {"%.68f", -1.0, zeroFill("-1.", 68, "")}, + // float infinites and NaNs + {"%f", posInf, "+Inf"}, + {"%.1f", negInf, "-Inf"}, + {"% f", NaN, " NaN"}, + {"%20f", posInf, " +Inf"}, + {"% 20F", posInf, " Inf"}, + {"% 20e", negInf, " -Inf"}, + {"% 20x", negInf, " -Inf"}, + {"%+20E", negInf, " -Inf"}, + {"%+20X", negInf, " -Inf"}, + {"% +20g", negInf, " -Inf"}, + {"%+-20G", posInf, "+Inf "}, + {"%20e", NaN, " NaN"}, + {"%20x", NaN, " NaN"}, + {"% +20E", NaN, " +NaN"}, + {"% +20X", NaN, " +NaN"}, + {"% -20g", NaN, " NaN "}, + {"%+-20G", NaN, "+NaN "}, + // Zero padding does not apply to infinities and NaN. + {"%+020e", posInf, " +Inf"}, + {"%+020x", posInf, " +Inf"}, + {"%-020f", negInf, "-Inf "}, + {"%-020E", NaN, "NaN "}, + {"%-020X", NaN, "NaN "}, + + // complex values + {"%.f", 0i, "(0+0i)"}, + {"% .f", 0i, "( 0+0i)"}, + {"%+.f", 0i, "(+0+0i)"}, + {"% +.f", 0i, "(+0+0i)"}, + {"%+.3e", 0i, "(+0.000e+00+0.000e+00i)"}, + {"%+.3x", 0i, "(+0x0.000p+00+0x0.000p+00i)"}, + {"%+.3f", 0i, "(+0.000+0.000i)"}, + {"%+.3g", 0i, "(+0+0i)"}, + {"%+.3e", 1 + 2i, "(+1.000e+00+2.000e+00i)"}, + {"%+.3x", 1 + 2i, "(+0x1.000p+00+0x1.000p+01i)"}, + {"%+.3f", 1 + 2i, "(+1.000+2.000i)"}, + {"%+.3g", 1 + 2i, "(+1+2i)"}, + {"%.3e", 0i, "(0.000e+00+0.000e+00i)"}, + {"%.3x", 0i, "(0x0.000p+00+0x0.000p+00i)"}, + {"%.3f", 0i, "(0.000+0.000i)"}, + {"%.3F", 0i, "(0.000+0.000i)"}, + {"%.3F", complex64(0i), "(0.000+0.000i)"}, + {"%.3g", 0i, "(0+0i)"}, + {"%.3e", 1 + 2i, "(1.000e+00+2.000e+00i)"}, + {"%.3x", 1 + 2i, "(0x1.000p+00+0x1.000p+01i)"}, + {"%.3f", 1 + 2i, "(1.000+2.000i)"}, + {"%.3g", 1 + 2i, "(1+2i)"}, + {"%.3e", -1 - 2i, "(-1.000e+00-2.000e+00i)"}, + {"%.3x", -1 - 2i, "(-0x1.000p+00-0x1.000p+01i)"}, + {"%.3f", -1 - 2i, "(-1.000-2.000i)"}, + {"%.3g", -1 - 2i, "(-1-2i)"}, + {"% .3E", -1 - 2i, "(-1.000E+00-2.000E+00i)"}, + {"% .3X", -1 - 2i, "(-0X1.000P+00-0X1.000P+01i)"}, + {"%+.3g", 1 + 2i, "(+1+2i)"}, + {"%+.3g", complex64(1 + 2i), "(+1+2i)"}, + {"%#g", 1 + 2i, "(1.00000+2.00000i)"}, + {"%#g", 123456 + 789012i, "(123456.+789012.i)"}, + {"%#g", 1e-10i, "(0.00000+1.00000e-10i)"}, + {"%#g", -1e10 - 1.11e100i, "(-1.00000e+10-1.11000e+100i)"}, + {"%#.0f", 1.23 + 1.0i, "(1.+1.i)"}, + {"%#.0e", 1.23 + 1.0i, "(1.e+00+1.e+00i)"}, + {"%#.0x", 1.23 + 1.0i, "(0x1.p+00+0x1.p+00i)"}, + {"%#.0g", 1.23 + 1.0i, "(1.+1.i)"}, + {"%#.0g", 0 + 100000i, "(0.+1.e+05i)"}, + {"%#.0g", 1230000 + 0i, "(1.e+06+0.i)"}, + {"%#.4f", 1 + 1.23i, "(1.0000+1.2300i)"}, + {"%#.4e", 123 + 1i, "(1.2300e+02+1.0000e+00i)"}, + {"%#.4x", 123 + 1i, "(0x1.ec00p+06+0x1.0000p+00i)"}, + {"%#.4g", 123 + 1.23i, "(123.0+1.230i)"}, + {"%#12.5g", 0 + 100000i, "( 0.0000 +1.0000e+05i)"}, + {"%#12.5g", 1230000 - 0i, "( 1.2300e+06 +0.0000i)"}, + {"%b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"}, + {"%b", complex64(1 + 2i), "(8388608p-23+8388608p-22i)"}, + // The sharp flag has no effect for binary complex format. + {"%#b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"}, + // Precision has no effect for binary complex format. + {"%.4b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"}, + {"%.4b", complex64(1 + 2i), "(8388608p-23+8388608p-22i)"}, + // complex infinites and NaNs + {"%f", complex(posInf, posInf), "(+Inf+Infi)"}, + {"%f", complex(negInf, negInf), "(-Inf-Infi)"}, + {"%f", complex(NaN, NaN), "(NaN+NaNi)"}, + {"%.1f", complex(posInf, posInf), "(+Inf+Infi)"}, + {"% f", complex(posInf, posInf), "( Inf+Infi)"}, + {"% f", complex(negInf, negInf), "(-Inf-Infi)"}, + {"% f", complex(NaN, NaN), "( NaN+NaNi)"}, + {"%8e", complex(posInf, posInf), "( +Inf +Infi)"}, + {"%8x", complex(posInf, posInf), "( +Inf +Infi)"}, + {"% 8E", complex(posInf, posInf), "( Inf +Infi)"}, + {"% 8X", complex(posInf, posInf), "( Inf +Infi)"}, + {"%+8f", complex(negInf, negInf), "( -Inf -Infi)"}, + {"% +8g", complex(negInf, negInf), "( -Inf -Infi)"}, + {"% -8G", complex(NaN, NaN), "( NaN +NaN i)"}, + {"%+-8b", complex(NaN, NaN), "(+NaN +NaN i)"}, + // Zero padding does not apply to infinities and NaN. + {"%08f", complex(posInf, posInf), "( +Inf +Infi)"}, + {"%-08g", complex(negInf, negInf), "(-Inf -Inf i)"}, + {"%-08G", complex(NaN, NaN), "(NaN +NaN i)"}, + + // old test/fmt_test.go + {"%e", 1.0, "1.000000e+00"}, + {"%e", 1234.5678e3, "1.234568e+06"}, + {"%e", 1234.5678e-8, "1.234568e-05"}, + {"%e", -7.0, "-7.000000e+00"}, + {"%e", -1e-9, "-1.000000e-09"}, + {"%f", 1234.5678e3, "1234567.800000"}, + {"%f", 1234.5678e-8, "0.000012"}, + {"%f", -7.0, "-7.000000"}, + {"%f", -1e-9, "-0.000000"}, + {"%g", 1234.5678e3, "1.2345678e+06"}, + {"%g", float32(1234.5678e3), "1.2345678e+06"}, + {"%g", 1234.5678e-8, "1.2345678e-05"}, + {"%g", -7.0, "-7"}, + {"%g", -1e-9, "-1e-09"}, + {"%g", float32(-1e-9), "-1e-09"}, + {"%E", 1.0, "1.000000E+00"}, + {"%E", 1234.5678e3, "1.234568E+06"}, + {"%E", 1234.5678e-8, "1.234568E-05"}, + {"%E", -7.0, "-7.000000E+00"}, + {"%E", -1e-9, "-1.000000E-09"}, + {"%G", 1234.5678e3, "1.2345678E+06"}, + {"%G", float32(1234.5678e3), "1.2345678E+06"}, + {"%G", 1234.5678e-8, "1.2345678E-05"}, + {"%G", -7.0, "-7"}, + {"%G", -1e-9, "-1E-09"}, + {"%G", float32(-1e-9), "-1E-09"}, + {"%20.5s", "qwertyuiop", " qwert"}, + {"%.5s", "qwertyuiop", "qwert"}, + {"%-20.5s", "qwertyuiop", "qwert "}, + {"%20c", 'x', " x"}, + {"%-20c", 'x', "x "}, + {"%20.6e", 1.2345e3, " 1.234500e+03"}, + {"%20.6e", 1.2345e-3, " 1.234500e-03"}, + {"%20e", 1.2345e3, " 1.234500e+03"}, + {"%20e", 1.2345e-3, " 1.234500e-03"}, + {"%20.8e", 1.2345e3, " 1.23450000e+03"}, + {"%20f", 1.23456789e3, " 1234.567890"}, + {"%20f", 1.23456789e-3, " 0.001235"}, + {"%20f", 12345678901.23456789, " 12345678901.234568"}, + {"%-20f", 1.23456789e3, "1234.567890 "}, + {"%20.8f", 1.23456789e3, " 1234.56789000"}, + {"%20.8f", 1.23456789e-3, " 0.00123457"}, + {"%g", 1.23456789e3, "1234.56789"}, + {"%g", 1.23456789e-3, "0.00123456789"}, + {"%g", 1.23456789e20, "1.23456789e+20"}, + + // arrays + {"%v", array, "[1 2 3 4 5]"}, + {"%v", iarray, "[1 hello 2.5 ]"}, + {"%v", barray, "[1 2 3 4 5]"}, + {"%v", &array, "&[1 2 3 4 5]"}, + {"%v", &iarray, "&[1 hello 2.5 ]"}, + {"%v", &barray, "&[1 2 3 4 5]"}, + + // slices + {"%v", slice, "[1 2 3 4 5]"}, + {"%v", islice, "[1 hello 2.5 ]"}, + {"%v", bslice, "[1 2 3 4 5]"}, + {"%v", &slice, "&[1 2 3 4 5]"}, + {"%v", &islice, "&[1 hello 2.5 ]"}, + {"%v", &bslice, "&[1 2 3 4 5]"}, + + // byte arrays and slices with %b,%c,%d,%o,%U and %v + {"%b", [3]byte{65, 66, 67}, "[1000001 1000010 1000011]"}, + {"%c", [3]byte{65, 66, 67}, "[A B C]"}, + {"%d", [3]byte{65, 66, 67}, "[65 66 67]"}, + {"%o", [3]byte{65, 66, 67}, "[101 102 103]"}, + {"%U", [3]byte{65, 66, 67}, "[U+0041 U+0042 U+0043]"}, + {"%v", [3]byte{65, 66, 67}, "[65 66 67]"}, + {"%v", [1]byte{123}, "[123]"}, + {"%012v", []byte{}, "[]"}, + {"%#012v", []byte{}, "[]byte{}"}, + {"%6v", []byte{1, 11, 111}, "[ 1 11 111]"}, + {"%06v", []byte{1, 11, 111}, "[000001 000011 000111]"}, + {"%-6v", []byte{1, 11, 111}, "[1 11 111 ]"}, + {"%-06v", []byte{1, 11, 111}, "[1 11 111 ]"}, + {"%#v", []byte{1, 11, 111}, "[]byte{0x1, 0xb, 0x6f}"}, + {"%#6v", []byte{1, 11, 111}, "[]byte{ 0x1, 0xb, 0x6f}"}, + {"%#06v", []byte{1, 11, 111}, "[]byte{0x000001, 0x00000b, 0x00006f}"}, + {"%#-6v", []byte{1, 11, 111}, "[]byte{0x1 , 0xb , 0x6f }"}, + {"%#-06v", []byte{1, 11, 111}, "[]byte{0x1 , 0xb , 0x6f }"}, + // f.space should and f.plus should not have an effect with %v. + {"% v", []byte{1, 11, 111}, "[ 1 11 111]"}, + {"%+v", [3]byte{1, 11, 111}, "[1 11 111]"}, + {"%# -6v", []byte{1, 11, 111}, "[]byte{ 0x1 , 0xb , 0x6f }"}, + {"%#+-6v", [3]byte{1, 11, 111}, "[3]uint8{0x1 , 0xb , 0x6f }"}, + // f.space and f.plus should have an effect with %d. + {"% d", []byte{1, 11, 111}, "[ 1 11 111]"}, + {"%+d", [3]byte{1, 11, 111}, "[+1 +11 +111]"}, + {"%# -6d", []byte{1, 11, 111}, "[ 1 11 111 ]"}, + {"%#+-6d", [3]byte{1, 11, 111}, "[+1 +11 +111 ]"}, + + // floates with %v + {"%v", 1.2345678, "1.2345678"}, + {"%v", float32(1.2345678), "1.2345678"}, + + // complexes with %v + {"%v", 1 + 2i, "(1+2i)"}, + {"%v", complex64(1 + 2i), "(1+2i)"}, + + // structs + {"%v", A{1, 2, "a", []int{1, 2}}, `{1 2 a [1 2]}`}, + {"%+v", A{1, 2, "a", []int{1, 2}}, `{i:1 j:2 s:a x:[1 2]}`}, + + // +v on structs with Stringable items + {"%+v", B{1, 2}, `{I:<1> j:2}`}, + {"%+v", C{1, B{2, 3}}, `{i:1 B:{I:<2> j:3}}`}, + + // other formats on Stringable items + {"%s", I(23), `<23>`}, + {"%q", I(23), `"<23>"`}, + {"%x", I(23), `3c32333e`}, + {"%#x", I(23), `0x3c32333e`}, + {"%# x", I(23), `0x3c 0x32 0x33 0x3e`}, + // Stringer applies only to string formats. + {"%d", I(23), `23`}, + // Stringer applies to the extracted value. + {"%s", reflect.ValueOf(I(23)), `<23>`}, + + // go syntax + {"%#v", A{1, 2, "a", []int{1, 2}}, `fmt_test.A{i:1, j:0x2, s:"a", x:[]int{1, 2}}`}, + {"%#v", new(byte), "(*uint8)(0xPTR)"}, + {"%#v", make(chan int), "(chan int)(0xPTR)"}, + {"%#v", uint64(1<<64 - 1), "0xffffffffffffffff"}, + {"%#v", 1000000000, "1000000000"}, + {"%#v", map[string]int{"a": 1}, `map[string]int{"a":1}`}, + {"%#v", map[string]B{"a": {1, 2}}, `map[string]fmt_test.B{"a":fmt_test.B{I:1, j:2}}`}, + {"%#v", []string{"a", "b"}, `[]string{"a", "b"}`}, + {"%#v", SI{}, `fmt_test.SI{I:interface {}(nil)}`}, + {"%#v", []int(nil), `[]int(nil)`}, + {"%#v", []int{}, `[]int{}`}, + {"%#v", array, `[5]int{1, 2, 3, 4, 5}`}, + {"%#v", &array, `&[5]int{1, 2, 3, 4, 5}`}, + {"%#v", iarray, `[4]interface {}{1, "hello", 2.5, interface {}(nil)}`}, + {"%#v", &iarray, `&[4]interface {}{1, "hello", 2.5, interface {}(nil)}`}, + {"%#v", map[int]byte(nil), `map[int]uint8(nil)`}, + {"%#v", map[int]byte{}, `map[int]uint8{}`}, + {"%#v", "foo", `"foo"`}, + {"%#v", barray, `[5]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`}, + {"%#v", bslice, `[]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`}, + {"%#v", []int32(nil), "[]int32(nil)"}, + {"%#v", 1.2345678, "1.2345678"}, + {"%#v", float32(1.2345678), "1.2345678"}, + + // functions + {"%v", TestFmtInterface, "0xPTR"}, // simple function + {"%v", reflect.ValueOf(TestFmtInterface), "0xPTR"}, + {"%v", G.GoString, "0xPTR"}, // method expression + {"%v", reflect.ValueOf(G.GoString), "0xPTR"}, + {"%v", G(23).GoString, "0xPTR"}, // method value + {"%v", reflect.ValueOf(G(23).GoString), "0xPTR"}, + {"%v", reflect.ValueOf(G(23)).Method(0), "0xPTR"}, + {"%v", Fn.String, "0xPTR"}, // method of function type + {"%v", reflect.ValueOf(Fn.String), "0xPTR"}, + {"%v", fnValue, "String(fn)"}, // variable of function type with String method + {"%v", reflect.ValueOf(fnValue), "String(fn)"}, + {"%v", [1]Fn{fnValue}, "[String(fn)]"}, // array of function type with String method + {"%v", reflect.ValueOf([1]Fn{fnValue}), "[String(fn)]"}, + {"%v", fnValue.String, "0xPTR"}, // method value from function type + {"%v", reflect.ValueOf(fnValue.String), "0xPTR"}, + {"%v", reflect.ValueOf(fnValue).Method(0), "0xPTR"}, + {"%v", U{}.u, ""}, // unexported function field + {"%v", reflect.ValueOf(U{}.u), ""}, + {"%v", reflect.ValueOf(U{}).Field(0), ""}, + {"%v", U{fn: fnValue}.fn, "String(fn)"}, // unexported field of function type with String method + {"%v", reflect.ValueOf(U{fn: fnValue}.fn), "String(fn)"}, + {"%v", reflect.ValueOf(U{fn: fnValue}).Field(1), ""}, + + // functions with go syntax + {"%#v", TestFmtInterface, "(func(*testing.T))(0xPTR)"}, // simple function + {"%#v", reflect.ValueOf(TestFmtInterface), "(func(*testing.T))(0xPTR)"}, + {"%#v", G.GoString, "(func(fmt_test.G) string)(0xPTR)"}, // method expression + {"%#v", reflect.ValueOf(G.GoString), "(func(fmt_test.G) string)(0xPTR)"}, + {"%#v", G(23).GoString, "(func() string)(0xPTR)"}, // method value + {"%#v", reflect.ValueOf(G(23).GoString), "(func() string)(0xPTR)"}, + {"%#v", reflect.ValueOf(G(23)).Method(0), "(func() string)(0xPTR)"}, + {"%#v", Fn.String, "(func(fmt_test.Fn) string)(0xPTR)"}, // method of function type + {"%#v", reflect.ValueOf(Fn.String), "(func(fmt_test.Fn) string)(0xPTR)"}, + {"%#v", fnValue, "(fmt_test.Fn)(nil)"}, // variable of function type with String method + {"%#v", reflect.ValueOf(fnValue), "(fmt_test.Fn)(nil)"}, + {"%#v", [1]Fn{fnValue}, "[1]fmt_test.Fn{(fmt_test.Fn)(nil)}"}, // array of function type with String method + {"%#v", reflect.ValueOf([1]Fn{fnValue}), "[1]fmt_test.Fn{(fmt_test.Fn)(nil)}"}, + {"%#v", fnValue.String, "(func() string)(0xPTR)"}, // method value from function type + {"%#v", reflect.ValueOf(fnValue.String), "(func() string)(0xPTR)"}, + {"%#v", reflect.ValueOf(fnValue).Method(0), "(func() string)(0xPTR)"}, + {"%#v", U{}.u, "(func() string)(nil)"}, // unexported function field + {"%#v", reflect.ValueOf(U{}.u), "(func() string)(nil)"}, + {"%#v", reflect.ValueOf(U{}).Field(0), "(func() string)(nil)"}, + {"%#v", U{fn: fnValue}.fn, "(fmt_test.Fn)(nil)"}, // unexported field of function type with String method + {"%#v", reflect.ValueOf(U{fn: fnValue}.fn), "(fmt_test.Fn)(nil)"}, + {"%#v", reflect.ValueOf(U{fn: fnValue}).Field(1), "(fmt_test.Fn)(nil)"}, + + // Whole number floats are printed without decimals. See Issue 27634. + {"%#v", 1.0, "1"}, + {"%#v", 1000000.0, "1e+06"}, + {"%#v", float32(1.0), "1"}, + {"%#v", float32(1000000.0), "1e+06"}, + + // Only print []byte and []uint8 as type []byte if they appear at the top level. + {"%#v", []byte(nil), "[]byte(nil)"}, + {"%#v", []uint8(nil), "[]byte(nil)"}, + {"%#v", []byte{}, "[]byte{}"}, + {"%#v", []uint8{}, "[]byte{}"}, + {"%#v", reflect.ValueOf([]byte{}), "[]uint8{}"}, + {"%#v", reflect.ValueOf([]uint8{}), "[]uint8{}"}, + {"%#v", &[]byte{}, "&[]uint8{}"}, + {"%#v", &[]byte{}, "&[]uint8{}"}, + {"%#v", [3]byte{}, "[3]uint8{0x0, 0x0, 0x0}"}, + {"%#v", [3]uint8{}, "[3]uint8{0x0, 0x0, 0x0}"}, + + // slices with other formats + {"%#x", []int{1, 2, 15}, `[0x1 0x2 0xf]`}, + {"%x", []int{1, 2, 15}, `[1 2 f]`}, + {"%d", []int{1, 2, 15}, `[1 2 15]`}, + {"%d", []byte{1, 2, 15}, `[1 2 15]`}, + {"%q", []string{"a", "b"}, `["a" "b"]`}, + {"% 02x", []byte{1}, "01"}, + {"% 02x", []byte{1, 2, 3}, "01 02 03"}, + + // Padding with byte slices. + {"%2x", []byte{}, " "}, + {"%#2x", []byte{}, " "}, + {"% 02x", []byte{}, "00"}, + {"%# 02x", []byte{}, "00"}, + {"%-2x", []byte{}, " "}, + {"%-02x", []byte{}, " "}, + {"%8x", []byte{0xab}, " ab"}, + {"% 8x", []byte{0xab}, " ab"}, + {"%#8x", []byte{0xab}, " 0xab"}, + {"%# 8x", []byte{0xab}, " 0xab"}, + {"%08x", []byte{0xab}, "000000ab"}, + {"% 08x", []byte{0xab}, "000000ab"}, + {"%#08x", []byte{0xab}, "00000xab"}, + {"%# 08x", []byte{0xab}, "00000xab"}, + {"%10x", []byte{0xab, 0xcd}, " abcd"}, + {"% 10x", []byte{0xab, 0xcd}, " ab cd"}, + {"%#10x", []byte{0xab, 0xcd}, " 0xabcd"}, + {"%# 10x", []byte{0xab, 0xcd}, " 0xab 0xcd"}, + {"%010x", []byte{0xab, 0xcd}, "000000abcd"}, + {"% 010x", []byte{0xab, 0xcd}, "00000ab cd"}, + {"%#010x", []byte{0xab, 0xcd}, "00000xabcd"}, + {"%# 010x", []byte{0xab, 0xcd}, "00xab 0xcd"}, + {"%-10X", []byte{0xab}, "AB "}, + {"% -010X", []byte{0xab}, "AB "}, + {"%#-10X", []byte{0xab, 0xcd}, "0XABCD "}, + {"%# -010X", []byte{0xab, 0xcd}, "0XAB 0XCD "}, + // Same for strings + {"%2x", "", " "}, + {"%#2x", "", " "}, + {"% 02x", "", "00"}, + {"%# 02x", "", "00"}, + {"%-2x", "", " "}, + {"%-02x", "", " "}, + {"%8x", "\xab", " ab"}, + {"% 8x", "\xab", " ab"}, + {"%#8x", "\xab", " 0xab"}, + {"%# 8x", "\xab", " 0xab"}, + {"%08x", "\xab", "000000ab"}, + {"% 08x", "\xab", "000000ab"}, + {"%#08x", "\xab", "00000xab"}, + {"%# 08x", "\xab", "00000xab"}, + {"%10x", "\xab\xcd", " abcd"}, + {"% 10x", "\xab\xcd", " ab cd"}, + {"%#10x", "\xab\xcd", " 0xabcd"}, + {"%# 10x", "\xab\xcd", " 0xab 0xcd"}, + {"%010x", "\xab\xcd", "000000abcd"}, + {"% 010x", "\xab\xcd", "00000ab cd"}, + {"%#010x", "\xab\xcd", "00000xabcd"}, + {"%# 010x", "\xab\xcd", "00xab 0xcd"}, + {"%-10X", "\xab", "AB "}, + {"% -010X", "\xab", "AB "}, + {"%#-10X", "\xab\xcd", "0XABCD "}, + {"%# -010X", "\xab\xcd", "0XAB 0XCD "}, + + // renamings + {"%v", renamedBool(true), "true"}, + {"%d", renamedBool(true), "%!d(fmt_test.renamedBool=true)"}, + {"%o", renamedInt(8), "10"}, + {"%d", renamedInt8(-9), "-9"}, + {"%v", renamedInt16(10), "10"}, + {"%v", renamedInt32(-11), "-11"}, + {"%X", renamedInt64(255), "FF"}, + {"%v", renamedUint(13), "13"}, + {"%o", renamedUint8(14), "16"}, + {"%X", renamedUint16(15), "F"}, + {"%d", renamedUint32(16), "16"}, + {"%X", renamedUint64(17), "11"}, + {"%o", renamedUintptr(18), "22"}, + {"%x", renamedString("thing"), "7468696e67"}, + {"%d", renamedBytes([]byte{1, 2, 15}), `[1 2 15]`}, + {"%q", renamedBytes([]byte("hello")), `"hello"`}, + {"%x", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "68656c6c6f"}, + {"%X", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "68656C6C6F"}, + {"%s", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "hello"}, + {"%q", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, `"hello"`}, + {"%v", renamedFloat32(22), "22"}, + {"%v", renamedFloat64(33), "33"}, + {"%v", renamedComplex64(3 + 4i), "(3+4i)"}, + {"%v", renamedComplex128(4 - 3i), "(4-3i)"}, + + // Formatter + {"%x", F(1), ""}, + {"%x", G(2), "2"}, + {"%+v", S{F(4), G(5)}, "{F: G:5}"}, + + // GoStringer + {"%#v", G(6), "GoString(6)"}, + {"%#v", S{F(7), G(8)}, "fmt_test.S{F:, G:GoString(8)}"}, + + // %T + {"%T", byte(0), "uint8"}, + {"%T", reflect.ValueOf(nil), "reflect.Value"}, + {"%T", (4 - 3i), "complex128"}, + {"%T", renamedComplex128(4 - 3i), "fmt_test.renamedComplex128"}, + {"%T", intVar, "int"}, + {"%6T", &intVar, " *int"}, + {"%10T", nil, " "}, + {"%-10T", nil, " "}, + + // %p with pointers + {"%p", (*int)(nil), "0x0"}, + {"%#p", (*int)(nil), "0"}, + {"%p", &intVar, "0xPTR"}, + {"%#p", &intVar, "PTR"}, + {"%p", &array, "0xPTR"}, + {"%p", &slice, "0xPTR"}, + {"%8.2p", (*int)(nil), " 0x00"}, + {"%-20.16p", &intVar, "0xPTR "}, + // %p on non-pointers + {"%p", make(chan int), "0xPTR"}, + {"%p", make(map[int]int), "0xPTR"}, + {"%p", func() {}, "0xPTR"}, + {"%p", 27, "%!p(int=27)"}, // not a pointer at all + {"%p", nil, "%!p()"}, // nil on its own has no type ... + {"%#p", nil, "%!p()"}, // ... and hence is not a pointer type. + // pointers with specified base + {"%b", &intVar, "PTR_b"}, + {"%d", &intVar, "PTR_d"}, + {"%o", &intVar, "PTR_o"}, + {"%x", &intVar, "PTR_x"}, + {"%X", &intVar, "PTR_X"}, + // %v on pointers + {"%v", nil, ""}, + {"%#v", nil, ""}, + {"%v", (*int)(nil), ""}, + {"%#v", (*int)(nil), "(*int)(nil)"}, + {"%v", &intVar, "0xPTR"}, + {"%#v", &intVar, "(*int)(0xPTR)"}, + {"%8.2v", (*int)(nil), " "}, + {"%-20.16v", &intVar, "0xPTR "}, + // string method on pointer + {"%s", &pValue, "String(p)"}, // String method... + {"%p", &pValue, "0xPTR"}, // ... is not called with %p. + + // %d on Stringer should give integer if possible + {"%s", time.Time{}.Month(), "January"}, + {"%d", time.Time{}.Month(), "1"}, + + // erroneous things + {"", nil, "%!(EXTRA )"}, + {"", 2, "%!(EXTRA int=2)"}, + {"no args", "hello", "no args%!(EXTRA string=hello)"}, + {"%s %", "hello", "hello %!(NOVERB)"}, + {"%s %.2", "hello", "hello %!(NOVERB)"}, + {"%017091901790959340919092959340919017929593813360", 0, "%!(NOVERB)%!(EXTRA int=0)"}, + {"%184467440737095516170v", 0, "%!(NOVERB)%!(EXTRA int=0)"}, + // Extra argument errors should format without flags set. + {"%010.2", "12345", "%!(NOVERB)%!(EXTRA string=12345)"}, + + // Test that maps with non-reflexive keys print all keys and values. + {"%v", map[float64]int{NaN: 1, NaN: 1}, "map[NaN:1 NaN:1]"}, + + // Comparison of padding rules with C printf. + /* + C program: + #include + + char *format[] = { + "[%.2f]", + "[% .2f]", + "[%+.2f]", + "[%7.2f]", + "[% 7.2f]", + "[%+7.2f]", + "[% +7.2f]", + "[%07.2f]", + "[% 07.2f]", + "[%+07.2f]", + "[% +07.2f]" + }; + + int main(void) { + int i; + for(i = 0; i < 11; i++) { + printf("%s: ", format[i]); + printf(format[i], 1.0); + printf(" "); + printf(format[i], -1.0); + printf("\n"); + } + } + + Output: + [%.2f]: [1.00] [-1.00] + [% .2f]: [ 1.00] [-1.00] + [%+.2f]: [+1.00] [-1.00] + [%7.2f]: [ 1.00] [ -1.00] + [% 7.2f]: [ 1.00] [ -1.00] + [%+7.2f]: [ +1.00] [ -1.00] + [% +7.2f]: [ +1.00] [ -1.00] + [%07.2f]: [0001.00] [-001.00] + [% 07.2f]: [ 001.00] [-001.00] + [%+07.2f]: [+001.00] [-001.00] + [% +07.2f]: [+001.00] [-001.00] + + */ + {"%.2f", 1.0, "1.00"}, + {"%.2f", -1.0, "-1.00"}, + {"% .2f", 1.0, " 1.00"}, + {"% .2f", -1.0, "-1.00"}, + {"%+.2f", 1.0, "+1.00"}, + {"%+.2f", -1.0, "-1.00"}, + {"%7.2f", 1.0, " 1.00"}, + {"%7.2f", -1.0, " -1.00"}, + {"% 7.2f", 1.0, " 1.00"}, + {"% 7.2f", -1.0, " -1.00"}, + {"%+7.2f", 1.0, " +1.00"}, + {"%+7.2f", -1.0, " -1.00"}, + {"% +7.2f", 1.0, " +1.00"}, + {"% +7.2f", -1.0, " -1.00"}, + {"%07.2f", 1.0, "0001.00"}, + {"%07.2f", -1.0, "-001.00"}, + {"% 07.2f", 1.0, " 001.00"}, + {"% 07.2f", -1.0, "-001.00"}, + {"%+07.2f", 1.0, "+001.00"}, + {"%+07.2f", -1.0, "-001.00"}, + {"% +07.2f", 1.0, "+001.00"}, + {"% +07.2f", -1.0, "-001.00"}, + + // Complex numbers: exhaustively tested in TestComplexFormatting. + {"%7.2f", 1 + 2i, "( 1.00 +2.00i)"}, + {"%+07.2f", -1 - 2i, "(-001.00-002.00i)"}, + + // Use spaces instead of zero if padding to the right. + {"%0-5s", "abc", "abc "}, + {"%-05.1f", 1.0, "1.0 "}, + + // float and complex formatting should not change the padding width + // for other elements. See issue 14642. + {"%06v", []any{+10.0, 10}, "[000010 000010]"}, + {"%06v", []any{-10.0, 10}, "[-00010 000010]"}, + {"%06v", []any{+10.0 + 10i, 10}, "[(000010+00010i) 000010]"}, + {"%06v", []any{-10.0 + 10i, 10}, "[(-00010+00010i) 000010]"}, + + // integer formatting should not alter padding for other elements. + {"%03.6v", []any{1, 2.0, "x"}, "[000001 002 00x]"}, + {"%03.0v", []any{0, 2.0, "x"}, "[ 002 000]"}, + + // Complex fmt used to leave the plus flag set for future entries in the array + // causing +2+0i and +3+0i instead of 2+0i and 3+0i. + {"%v", []complex64{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"}, + {"%v", []complex128{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"}, + + // Incomplete format specification caused crash. + {"%.", 3, "%!.(int=3)"}, + + // Padding for complex numbers. Has been bad, then fixed, then bad again. + {"%+10.2f", +104.66 + 440.51i, "( +104.66 +440.51i)"}, + {"%+10.2f", -104.66 + 440.51i, "( -104.66 +440.51i)"}, + {"%+10.2f", +104.66 - 440.51i, "( +104.66 -440.51i)"}, + {"%+10.2f", -104.66 - 440.51i, "( -104.66 -440.51i)"}, + {"%+010.2f", +104.66 + 440.51i, "(+000104.66+000440.51i)"}, + {"%+010.2f", -104.66 + 440.51i, "(-000104.66+000440.51i)"}, + {"%+010.2f", +104.66 - 440.51i, "(+000104.66-000440.51i)"}, + {"%+010.2f", -104.66 - 440.51i, "(-000104.66-000440.51i)"}, + + // []T where type T is a byte with a Stringer method. + {"%v", byteStringerSlice, "[X X X X X]"}, + {"%s", byteStringerSlice, "hello"}, + {"%q", byteStringerSlice, "\"hello\""}, + {"%x", byteStringerSlice, "68656c6c6f"}, + {"%X", byteStringerSlice, "68656C6C6F"}, + {"%#v", byteStringerSlice, "[]fmt_test.byteStringer{0x68, 0x65, 0x6c, 0x6c, 0x6f}"}, + + // And the same for Formatter. + {"%v", byteFormatterSlice, "[X X X X X]"}, + {"%s", byteFormatterSlice, "hello"}, + {"%q", byteFormatterSlice, "\"hello\""}, + {"%x", byteFormatterSlice, "68656c6c6f"}, + {"%X", byteFormatterSlice, "68656C6C6F"}, + // This next case seems wrong, but the docs say the Formatter wins here. + {"%#v", byteFormatterSlice, "[]fmt_test.byteFormatter{X, X, X, X, X}"}, + + // pp.WriteString + {"%s", writeStringFormatter(""), "******"}, + {"%s", writeStringFormatter("xyz"), "***xyz***"}, + {"%s", writeStringFormatter("⌘/⌘"), "***⌘/⌘***"}, + + // reflect.Value handled specially in Go 1.5, making it possible to + // see inside non-exported fields (which cannot be accessed with Interface()). + // Issue 8965. + {"%v", reflect.ValueOf(A{}).Field(0).String(), ""}, // Equivalent to the old way. + {"%v", reflect.ValueOf(A{}).Field(0), "0"}, // Sees inside the field. + + // verbs apply to the extracted value too. + {"%s", reflect.ValueOf("hello"), "hello"}, + {"%q", reflect.ValueOf("hello"), `"hello"`}, + {"%#04x", reflect.ValueOf(256), "0x0100"}, + + // invalid reflect.Value doesn't crash. + {"%v", reflect.Value{}, ""}, + {"%v", &reflect.Value{}, ""}, + {"%v", SI{reflect.Value{}}, "{}"}, + + // Tests to check that not supported verbs generate an error string. + {"%☠", nil, "%!☠()"}, + {"%☠", any(nil), "%!☠()"}, + {"%☠", int(0), "%!☠(int=0)"}, + {"%☠", uint(0), "%!☠(uint=0)"}, + {"%☠", []byte{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"}, + {"%☠", []uint8{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"}, + {"%☠", [1]byte{0}, "[%!☠(uint8=0)]"}, + {"%☠", [1]uint8{0}, "[%!☠(uint8=0)]"}, + {"%☠", "hello", "%!☠(string=hello)"}, + {"%☠", 1.2345678, "%!☠(float64=1.2345678)"}, + {"%☠", float32(1.2345678), "%!☠(float32=1.2345678)"}, + {"%☠", 1.2345678 + 1.2345678i, "%!☠(complex128=(1.2345678+1.2345678i))"}, + {"%☠", complex64(1.2345678 + 1.2345678i), "%!☠(complex64=(1.2345678+1.2345678i))"}, + {"%☠", &intVar, "%!☠(*int=0xPTR)"}, + {"%☠", make(chan int), "%!☠(chan int=0xPTR)"}, + {"%☠", func() {}, "%!☠(func()=0xPTR)"}, + {"%☠", reflect.ValueOf(renamedInt(0)), "%!☠(fmt_test.renamedInt=0)"}, + {"%☠", SI{renamedInt(0)}, "{%!☠(fmt_test.renamedInt=0)}"}, + {"%☠", &[]any{I(1), G(2)}, "&[%!☠(fmt_test.I=1) %!☠(fmt_test.G=2)]"}, + {"%☠", SI{&[]any{I(1), G(2)}}, "{%!☠(*[]interface {}=&[1 2])}"}, + {"%☠", reflect.Value{}, ""}, + {"%☠", map[float64]int{NaN: 1}, "map[%!☠(float64=NaN):%!☠(int=1)]"}, +} + +// zeroFill generates zero-filled strings of the specified width. The length +// of the suffix (but not the prefix) is compensated for in the width calculation. +func zeroFill(prefix string, width int, suffix string) string { + return prefix + strings.Repeat("0", width-len(suffix)) + suffix +} + +func TestSprintf(t *testing.T) { + for _, tt := range fmtTests { + s := Sprintf(tt.fmt, tt.val) + i := strings.Index(tt.out, "PTR") + if i >= 0 && i < len(s) { + var pattern, chars string + switch { + case strings.HasPrefix(tt.out[i:], "PTR_b"): + pattern = "PTR_b" + chars = "01" + case strings.HasPrefix(tt.out[i:], "PTR_o"): + pattern = "PTR_o" + chars = "01234567" + case strings.HasPrefix(tt.out[i:], "PTR_d"): + pattern = "PTR_d" + chars = "0123456789" + case strings.HasPrefix(tt.out[i:], "PTR_x"): + pattern = "PTR_x" + chars = "0123456789abcdef" + case strings.HasPrefix(tt.out[i:], "PTR_X"): + pattern = "PTR_X" + chars = "0123456789ABCDEF" + default: + pattern = "PTR" + chars = "0123456789abcdefABCDEF" + } + p := s[:i] + pattern + for j := i; j < len(s); j++ { + if !strings.ContainsRune(chars, rune(s[j])) { + p += s[j:] + break + } + } + s = p + } + if s != tt.out { + if _, ok := tt.val.(string); ok { + // Don't requote the already-quoted strings. + // It's too confusing to read the errors. + t.Errorf("Sprintf(%q, %q) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out) + } else { + t.Errorf("Sprintf(%q, %v) = %q want %q", tt.fmt, tt.val, s, tt.out) + } + } + } +} + +// TestComplexFormatting checks that a complex always formats to the same +// thing as if done by hand with two singleton prints. +func TestComplexFormatting(t *testing.T) { + var yesNo = []bool{true, false} + var values = []float64{1, 0, -1, posInf, negInf, NaN} + for _, plus := range yesNo { + for _, zero := range yesNo { + for _, space := range yesNo { + for _, char := range "fFeEgG" { + realFmt := "%" + if zero { + realFmt += "0" + } + if space { + realFmt += " " + } + if plus { + realFmt += "+" + } + realFmt += "10.2" + realFmt += string(char) + // Imaginary part always has a sign, so force + and ignore space. + imagFmt := "%" + if zero { + imagFmt += "0" + } + imagFmt += "+" + imagFmt += "10.2" + imagFmt += string(char) + for _, realValue := range values { + for _, imagValue := range values { + one := Sprintf(realFmt, complex(realValue, imagValue)) + two := Sprintf("("+realFmt+imagFmt+"i)", realValue, imagValue) + if one != two { + t.Error(f, one, two) + } + } + } + } + } + } + } +} + +type SE []any // slice of empty; notational compactness. + +var reorderTests = []struct { + fmt string + val SE + out string +}{ + {"%[1]d", SE{1}, "1"}, + {"%[2]d", SE{2, 1}, "1"}, + {"%[2]d %[1]d", SE{1, 2}, "2 1"}, + {"%[2]*[1]d", SE{2, 5}, " 2"}, + {"%6.2f", SE{12.0}, " 12.00"}, // Explicit version of next line. + {"%[3]*.[2]*[1]f", SE{12.0, 2, 6}, " 12.00"}, + {"%[1]*.[2]*[3]f", SE{6, 2, 12.0}, " 12.00"}, + {"%10f", SE{12.0}, " 12.000000"}, + {"%[1]*[3]f", SE{10, 99, 12.0}, " 12.000000"}, + {"%.6f", SE{12.0}, "12.000000"}, // Explicit version of next line. + {"%.[1]*[3]f", SE{6, 99, 12.0}, "12.000000"}, + {"%6.f", SE{12.0}, " 12"}, // // Explicit version of next line; empty precision means zero. + {"%[1]*.[3]f", SE{6, 3, 12.0}, " 12"}, + // An actual use! Print the same arguments twice. + {"%d %d %d %#[1]o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015"}, + + // Erroneous cases. + {"%[d", SE{2, 1}, "%!d(BADINDEX)"}, + {"%]d", SE{2, 1}, "%!](int=2)d%!(EXTRA int=1)"}, + {"%[]d", SE{2, 1}, "%!d(BADINDEX)"}, + {"%[-3]d", SE{2, 1}, "%!d(BADINDEX)"}, + {"%[99]d", SE{2, 1}, "%!d(BADINDEX)"}, + {"%[3]", SE{2, 1}, "%!(NOVERB)"}, + {"%[1].2d", SE{5, 6}, "%!d(BADINDEX)"}, + {"%[1]2d", SE{2, 1}, "%!d(BADINDEX)"}, + {"%3.[2]d", SE{7}, "%!d(BADINDEX)"}, + {"%.[2]d", SE{7}, "%!d(BADINDEX)"}, + {"%d %d %d %#[1]o %#o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015 %!o(MISSING)"}, + {"%[5]d %[2]d %d", SE{1, 2, 3}, "%!d(BADINDEX) 2 3"}, + {"%d %[3]d %d", SE{1, 2}, "1 %!d(BADINDEX) 2"}, // Erroneous index does not affect sequence. + {"%.[]", SE{}, "%!](BADINDEX)"}, // Issue 10675 + {"%.-3d", SE{42}, "%!-(int=42)3d"}, // TODO: Should this set return better error messages? + {"%2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"}, + {"%-2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"}, + {"%.2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"}, +} + +func TestReorder(t *testing.T) { + for _, tt := range reorderTests { + s := Sprintf(tt.fmt, tt.val...) + if s != tt.out { + t.Errorf("Sprintf(%q, %v) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out) + } + } +} + +func BenchmarkSprintfPadding(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%16f", 1.0) + } + }) +} + +func BenchmarkSprintfEmpty(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("") + } + }) +} + +func BenchmarkSprintfString(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%s", "hello") + } + }) +} + +func BenchmarkSprintfTruncateString(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%.3s", "日本語日本語日本語日本語") + } + }) +} + +func BenchmarkSprintfTruncateBytes(b *testing.B) { + var bytes any = []byte("日本語日本語日本語日本語") + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%.3s", bytes) + } + }) +} + +func BenchmarkSprintfSlowParsingPath(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%.v", nil) + } + }) +} + +func BenchmarkSprintfQuoteString(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%q", "日本語日本語日本語") + } + }) +} + +func BenchmarkSprintfInt(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%d", 5) + } + }) +} + +func BenchmarkSprintfIntInt(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%d %d", 5, 6) + } + }) +} + +func BenchmarkSprintfPrefixedInt(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("This is some meaningless prefix text that needs to be scanned %d", 6) + } + }) +} + +func BenchmarkSprintfFloat(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%g", 5.23184) + } + }) +} + +func BenchmarkSprintfComplex(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%f", 5.23184+5.23184i) + } + }) +} + +func BenchmarkSprintfBoolean(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%t", true) + } + }) +} + +func BenchmarkSprintfHexString(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("% #x", "0123456789abcdef") + } + }) +} + +func BenchmarkSprintfHexBytes(b *testing.B) { + data := []byte("0123456789abcdef") + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("% #x", data) + } + }) +} + +func BenchmarkSprintfBytes(b *testing.B) { + data := []byte("0123456789abcdef") + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%v", data) + } + }) +} + +func BenchmarkSprintfStringer(b *testing.B) { + stringer := I(12345) + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%v", stringer) + } + }) +} + +func BenchmarkSprintfStructure(b *testing.B) { + s := &[]any{SI{12345}, map[int]string{0: "hello"}} + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = Sprintf("%#v", s) + } + }) +} + +func BenchmarkManyArgs(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + var buf bytes.Buffer + for pb.Next() { + buf.Reset() + Fprintf(&buf, "%2d/%2d/%2d %d:%d:%d %s %s\n", 3, 4, 5, 11, 12, 13, "hello", "world") + } + }) +} + +func BenchmarkFprintInt(b *testing.B) { + var buf bytes.Buffer + for i := 0; i < b.N; i++ { + buf.Reset() + Fprint(&buf, 123456) + } +} + +func BenchmarkFprintfBytes(b *testing.B) { + data := []byte(string("0123456789")) + var buf bytes.Buffer + for i := 0; i < b.N; i++ { + buf.Reset() + Fprintf(&buf, "%s", data) + } +} + +func BenchmarkFprintIntNoAlloc(b *testing.B) { + var x any = 123456 + var buf bytes.Buffer + for i := 0; i < b.N; i++ { + buf.Reset() + Fprint(&buf, x) + } +} + +var mallocBuf bytes.Buffer +var mallocPointer *int // A pointer so we know the interface value won't allocate. +var sink any + +var mallocTest = []struct { + count int + desc string + fn func() +}{ + {0, `Sprintf("")`, func() { _ = Sprintf("") }}, + {1, `Sprintf("xxx")`, func() { _ = Sprintf("xxx") }}, + {0, `Sprintf("%x")`, func() { _ = Sprintf("%x", 7) }}, + {1, `Sprintf("%x")`, func() { _ = Sprintf("%x", 1<<16) }}, + {3, `Sprintf("%80000s")`, func() { _ = Sprintf("%80000s", "hello") }}, // large buffer (>64KB) + {1, `Sprintf("%s")`, func() { _ = Sprintf("%s", "hello") }}, + {1, `Sprintf("%x %x")`, func() { _ = Sprintf("%x %x", 7, 112) }}, + {1, `Sprintf("%g")`, func() { _ = Sprintf("%g", float32(3.14159)) }}, + {0, `Fprintf(buf, "%s")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%s", "hello") }}, + {0, `Fprintf(buf, "%s")`, func() { mallocBuf.Reset(); s := "hello"; Fprintf(&mallocBuf, "%s", s) }}, + {1, `Fprintf(buf, "%s")`, func() { mallocBuf.Reset(); s := "hello"; Fprintf(&mallocBuf, "%s", noliteral(s)) }}, + {0, `Fprintf(buf, "%x")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%x", 7) }}, + {0, `Fprintf(buf, "%x")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%x", 1<<16) }}, + {0, `Fprintf(buf, "%x")`, func() { mallocBuf.Reset(); i := 1 << 16; Fprintf(&mallocBuf, "%x", i) }}, + {1, `Fprintf(buf, "%x")`, func() { mallocBuf.Reset(); i := 1 << 16; Fprintf(&mallocBuf, "%x", noliteral(i)) }}, + {4, `Fprintf(buf, "%v")`, func() { mallocBuf.Reset(); s := []int{1, 2}; Fprintf(&mallocBuf, "%v", s) }}, + {0, `Fprintf(buf, "%v")`, func() { mallocBuf.Reset(); type P struct{ x, y int }; Fprintf(&mallocBuf, "%v", P{1, 2}) }}, + {1, `Fprintf(buf, "%v")`, func() { mallocBuf.Reset(); type P struct{ x, y int }; Fprintf(&mallocBuf, "%v", noliteral(P{1, 2})) }}, + {2, `Fprintf(buf, "%80000s")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%80000s", "hello") }}, // large buffer (>64KB) + // If the interface value doesn't need to allocate, amortized allocation overhead should be zero. + {0, `Fprintf(buf, "%x %x %x")`, func() { + mallocBuf.Reset() + Fprintf(&mallocBuf, "%x %x %x", mallocPointer, mallocPointer, mallocPointer) + }}, + {0, `Errorf("hello")`, func() { _ = Errorf("hello") }}, + {2, `Errorf("hello: %x")`, func() { _ = Errorf("hello: %x", mallocPointer) }}, + {1, `sink = Errorf("hello")`, func() { sink = Errorf("hello") }}, + {2, `sink = Errorf("hello: %x")`, func() { sink = Errorf("hello: %x", mallocPointer) }}, +} + +var _ bytes.Buffer + +func TestCountMallocs(t *testing.T) { + switch { + case testing.Short(): + t.Skip("skipping malloc count in short mode") + case race.Enabled: + t.Skip("skipping malloc count under race detector") + } + for _, mt := range mallocTest { + mallocs := testing.AllocsPerRun(100, mt.fn) + if got, max := mallocs, float64(mt.count); got != max { + t.Errorf("%s: got %v allocs, want %v", mt.desc, got, max) + } + } +} + +type flagPrinter struct{} + +func (flagPrinter) Format(f State, c rune) { + s := "%" + for i := 0; i < 128; i++ { + if f.Flag(i) { + s += string(rune(i)) + } + } + if w, ok := f.Width(); ok { + s += Sprintf("%d", w) + } + if p, ok := f.Precision(); ok { + s += Sprintf(".%d", p) + } + s += string(c) + io.WriteString(f, "["+s+"]") +} + +var flagtests = []struct { + in string + out string +}{ + {"%a", "[%a]"}, + {"%-a", "[%-a]"}, + {"%+a", "[%+a]"}, + {"%#a", "[%#a]"}, + {"% a", "[% a]"}, + {"%0a", "[%0a]"}, + {"%1.2a", "[%1.2a]"}, + {"%-1.2a", "[%-1.2a]"}, + {"%+1.2a", "[%+1.2a]"}, + {"%-+1.2a", "[%+-1.2a]"}, + {"%-+1.2abc", "[%+-1.2a]bc"}, + {"%-1.2abc", "[%-1.2a]bc"}, + {"%-0abc", "[%-0a]bc"}, +} + +func TestFlagParser(t *testing.T) { + var flagprinter flagPrinter + for _, tt := range flagtests { + s := Sprintf(tt.in, &flagprinter) + if s != tt.out { + t.Errorf("Sprintf(%q, &flagprinter) => %q, want %q", tt.in, s, tt.out) + } + } +} + +func TestStructPrinter(t *testing.T) { + type T struct { + a string + b string + c int + } + var s T + s.a = "abc" + s.b = "def" + s.c = 123 + var tests = []struct { + fmt string + out string + }{ + {"%v", "{abc def 123}"}, + {"%+v", "{a:abc b:def c:123}"}, + {"%#v", `fmt_test.T{a:"abc", b:"def", c:123}`}, + } + for _, tt := range tests { + out := Sprintf(tt.fmt, s) + if out != tt.out { + t.Errorf("Sprintf(%q, s) = %#q, want %#q", tt.fmt, out, tt.out) + } + // The same but with a pointer. + out = Sprintf(tt.fmt, &s) + if out != "&"+tt.out { + t.Errorf("Sprintf(%q, &s) = %#q, want %#q", tt.fmt, out, "&"+tt.out) + } + } +} + +func TestSlicePrinter(t *testing.T) { + slice := []int{} + s := Sprint(slice) + if s != "[]" { + t.Errorf("empty slice printed as %q not %q", s, "[]") + } + slice = []int{1, 2, 3} + s = Sprint(slice) + if s != "[1 2 3]" { + t.Errorf("slice: got %q expected %q", s, "[1 2 3]") + } + s = Sprint(&slice) + if s != "&[1 2 3]" { + t.Errorf("&slice: got %q expected %q", s, "&[1 2 3]") + } +} + +// presentInMap checks map printing using substrings so we don't depend on the +// print order. +func presentInMap(s string, a []string, t *testing.T) { + for i := 0; i < len(a); i++ { + loc := strings.Index(s, a[i]) + if loc < 0 { + t.Errorf("map print: expected to find %q in %q", a[i], s) + } + // make sure the match ends here + loc += len(a[i]) + if loc >= len(s) || (s[loc] != ' ' && s[loc] != ']') { + t.Errorf("map print: %q not properly terminated in %q", a[i], s) + } + } +} + +func TestMapPrinter(t *testing.T) { + m0 := make(map[int]string) + s := Sprint(m0) + if s != "map[]" { + t.Errorf("empty map printed as %q not %q", s, "map[]") + } + m1 := map[int]string{1: "one", 2: "two", 3: "three"} + a := []string{"1:one", "2:two", "3:three"} + presentInMap(Sprintf("%v", m1), a, t) + presentInMap(Sprint(m1), a, t) + // Pointer to map prints the same but with initial &. + if !strings.HasPrefix(Sprint(&m1), "&") { + t.Errorf("no initial & for address of map") + } + presentInMap(Sprintf("%v", &m1), a, t) + presentInMap(Sprint(&m1), a, t) +} + +func TestEmptyMap(t *testing.T) { + const emptyMapStr = "map[]" + var m map[string]int + s := Sprint(m) + if s != emptyMapStr { + t.Errorf("nil map printed as %q not %q", s, emptyMapStr) + } + m = make(map[string]int) + s = Sprint(m) + if s != emptyMapStr { + t.Errorf("empty map printed as %q not %q", s, emptyMapStr) + } +} + +// TestBlank checks that Sprint (and hence Print, Fprint) puts spaces in the +// right places, that is, between arg pairs in which neither is a string. +func TestBlank(t *testing.T) { + got := Sprint("<", 1, ">:", 1, 2, 3, "!") + expect := "<1>:1 2 3!" + if got != expect { + t.Errorf("got %q expected %q", got, expect) + } +} + +// TestBlankln checks that Sprintln (and hence Println, Fprintln) puts spaces in +// the right places, that is, between all arg pairs. +func TestBlankln(t *testing.T) { + got := Sprintln("<", 1, ">:", 1, 2, 3, "!") + expect := "< 1 >: 1 2 3 !\n" + if got != expect { + t.Errorf("got %q expected %q", got, expect) + } +} + +// TestFormatterPrintln checks Formatter with Sprint, Sprintln, Sprintf. +func TestFormatterPrintln(t *testing.T) { + f := F(1) + expect := "\n" + s := Sprint(f, "\n") + if s != expect { + t.Errorf("Sprint wrong with Formatter: expected %q got %q", expect, s) + } + s = Sprintln(f) + if s != expect { + t.Errorf("Sprintln wrong with Formatter: expected %q got %q", expect, s) + } + s = Sprintf("%v\n", f) + if s != expect { + t.Errorf("Sprintf wrong with Formatter: expected %q got %q", expect, s) + } +} + +func args(a ...any) []any { return a } + +var startests = []struct { + fmt string + in []any + out string +}{ + {"%*d", args(4, 42), " 42"}, + {"%-*d", args(4, 42), "42 "}, + {"%*d", args(-4, 42), "42 "}, + {"%-*d", args(-4, 42), "42 "}, + {"%.*d", args(4, 42), "0042"}, + {"%*.*d", args(8, 4, 42), " 0042"}, + {"%0*d", args(4, 42), "0042"}, + // Some non-int types for width. (Issue 10732). + {"%0*d", args(uint(4), 42), "0042"}, + {"%0*d", args(uint64(4), 42), "0042"}, + {"%0*d", args('\x04', 42), "0042"}, + {"%0*d", args(uintptr(4), 42), "0042"}, + + // erroneous + {"%*d", args(nil, 42), "%!(BADWIDTH)42"}, + {"%*d", args(int(1e7), 42), "%!(BADWIDTH)42"}, + {"%*d", args(int(-1e7), 42), "%!(BADWIDTH)42"}, + {"%.*d", args(nil, 42), "%!(BADPREC)42"}, + {"%.*d", args(-1, 42), "%!(BADPREC)42"}, + {"%.*d", args(int(1e7), 42), "%!(BADPREC)42"}, + {"%.*d", args(uint(1e7), 42), "%!(BADPREC)42"}, + {"%.*d", args(uint64(1<<63), 42), "%!(BADPREC)42"}, // Huge negative (-inf). + {"%.*d", args(uint64(1<<64-1), 42), "%!(BADPREC)42"}, // Small negative (-1). + {"%*d", args(5, "foo"), "%!d(string= foo)"}, + {"%*% %d", args(20, 5), "% 5"}, + {"%*", args(4), "%!(NOVERB)"}, +} + +func TestWidthAndPrecision(t *testing.T) { + for i, tt := range startests { + s := Sprintf(tt.fmt, tt.in...) + if s != tt.out { + t.Errorf("#%d: %q: got %q expected %q", i, tt.fmt, s, tt.out) + } + } +} + +// PanicS is a type that panics in String. +type PanicS struct { + message any +} + +// Value receiver. +func (p PanicS) String() string { + panic(p.message) +} + +// PanicGo is a type that panics in GoString. +type PanicGo struct { + message any +} + +// Value receiver. +func (p PanicGo) GoString() string { + panic(p.message) +} + +// PanicF is a type that panics in Format. +type PanicF struct { + message any +} + +// Value receiver. +func (p PanicF) Format(f State, c rune) { + panic(p.message) +} + +var panictests = []struct { + fmt string + in any + out string +}{ + // String + {"%s", (*PanicS)(nil), ""}, // nil pointer special case + {"%s", PanicS{io.ErrUnexpectedEOF}, "%!s(PANIC=String method: unexpected EOF)"}, + {"%s", PanicS{3}, "%!s(PANIC=String method: 3)"}, + // GoString + {"%#v", (*PanicGo)(nil), ""}, // nil pointer special case + {"%#v", PanicGo{io.ErrUnexpectedEOF}, "%!v(PANIC=GoString method: unexpected EOF)"}, + {"%#v", PanicGo{3}, "%!v(PANIC=GoString method: 3)"}, + // Issue 18282. catchPanic should not clear fmtFlags permanently. + {"%#v", []any{PanicGo{3}, PanicGo{3}}, "[]interface {}{%!v(PANIC=GoString method: 3), %!v(PANIC=GoString method: 3)}"}, + // Format + {"%s", (*PanicF)(nil), ""}, // nil pointer special case + {"%s", PanicF{io.ErrUnexpectedEOF}, "%!s(PANIC=Format method: unexpected EOF)"}, + {"%s", PanicF{3}, "%!s(PANIC=Format method: 3)"}, +} + +func TestPanics(t *testing.T) { + for i, tt := range panictests { + s := Sprintf(tt.fmt, tt.in) + if s != tt.out { + t.Errorf("%d: %q: got %q expected %q", i, tt.fmt, s, tt.out) + } + } +} + +// recurCount tests that erroneous String routine doesn't cause fatal recursion. +var recurCount = 0 + +type Recur struct { + i int + failed *bool +} + +func (r *Recur) String() string { + if recurCount++; recurCount > 10 { + *r.failed = true + return "FAIL" + } + // This will call badVerb. Before the fix, that would cause us to recur into + // this routine to print %!p(value). Now we don't call the user's method + // during an error. + return Sprintf("recur@%p value: %d", r, r.i) +} + +func TestBadVerbRecursion(t *testing.T) { + failed := false + r := &Recur{3, &failed} + _ = Sprintf("recur@%p value: %d\n", &r, r.i) + if failed { + t.Error("fail with pointer") + } + failed = false + r = &Recur{4, &failed} + _ = Sprintf("recur@%p, value: %d\n", r, r.i) + if failed { + t.Error("fail with value") + } +} + +func TestIsSpace(t *testing.T) { + // This tests the internal isSpace function. + // IsSpace = isSpace is defined in export_test.go. + for i := rune(0); i <= unicode.MaxRune; i++ { + if IsSpace(i) != unicode.IsSpace(i) { + t.Errorf("isSpace(%U) = %v, want %v", i, IsSpace(i), unicode.IsSpace(i)) + } + } +} + +func hideFromVet(s string) string { return s } + +func TestNilDoesNotBecomeTyped(t *testing.T) { + type A struct{} + type B struct{} + var a *A = nil + var b B = B{} + got := Sprintf(hideFromVet("%s %s %s %s %s"), nil, a, nil, b, nil) + const expect = "%!s() %!s(*fmt_test.A=) %!s() {} %!s()" + if got != expect { + t.Errorf("expected:\n\t%q\ngot:\n\t%q", expect, got) + } +} + +var formatterFlagTests = []struct { + in string + val any + out string +}{ + // scalar values with the (unused by fmt) 'a' verb. + {"%a", flagPrinter{}, "[%a]"}, + {"%-a", flagPrinter{}, "[%-a]"}, + {"%+a", flagPrinter{}, "[%+a]"}, + {"%#a", flagPrinter{}, "[%#a]"}, + {"% a", flagPrinter{}, "[% a]"}, + {"%0a", flagPrinter{}, "[%0a]"}, + {"%1.2a", flagPrinter{}, "[%1.2a]"}, + {"%-1.2a", flagPrinter{}, "[%-1.2a]"}, + {"%+1.2a", flagPrinter{}, "[%+1.2a]"}, + {"%-+1.2a", flagPrinter{}, "[%+-1.2a]"}, + {"%-+1.2abc", flagPrinter{}, "[%+-1.2a]bc"}, + {"%-1.2abc", flagPrinter{}, "[%-1.2a]bc"}, + {"%-0abc", flagPrinter{}, "[%-0a]bc"}, + + // composite values with the 'a' verb + {"%a", [1]flagPrinter{}, "[[%a]]"}, + {"%-a", [1]flagPrinter{}, "[[%-a]]"}, + {"%+a", [1]flagPrinter{}, "[[%+a]]"}, + {"%#a", [1]flagPrinter{}, "[[%#a]]"}, + {"% a", [1]flagPrinter{}, "[[% a]]"}, + {"%0a", [1]flagPrinter{}, "[[%0a]]"}, + {"%1.2a", [1]flagPrinter{}, "[[%1.2a]]"}, + {"%-1.2a", [1]flagPrinter{}, "[[%-1.2a]]"}, + {"%+1.2a", [1]flagPrinter{}, "[[%+1.2a]]"}, + {"%-+1.2a", [1]flagPrinter{}, "[[%+-1.2a]]"}, + {"%-+1.2abc", [1]flagPrinter{}, "[[%+-1.2a]]bc"}, + {"%-1.2abc", [1]flagPrinter{}, "[[%-1.2a]]bc"}, + {"%-0abc", [1]flagPrinter{}, "[[%-0a]]bc"}, + + // simple values with the 'v' verb + {"%v", flagPrinter{}, "[%v]"}, + {"%-v", flagPrinter{}, "[%-v]"}, + {"%+v", flagPrinter{}, "[%+v]"}, + {"%#v", flagPrinter{}, "[%#v]"}, + {"% v", flagPrinter{}, "[% v]"}, + {"%0v", flagPrinter{}, "[%0v]"}, + {"%1.2v", flagPrinter{}, "[%1.2v]"}, + {"%-1.2v", flagPrinter{}, "[%-1.2v]"}, + {"%+1.2v", flagPrinter{}, "[%+1.2v]"}, + {"%-+1.2v", flagPrinter{}, "[%+-1.2v]"}, + {"%-+1.2vbc", flagPrinter{}, "[%+-1.2v]bc"}, + {"%-1.2vbc", flagPrinter{}, "[%-1.2v]bc"}, + {"%-0vbc", flagPrinter{}, "[%-0v]bc"}, + + // composite values with the 'v' verb. + {"%v", [1]flagPrinter{}, "[[%v]]"}, + {"%-v", [1]flagPrinter{}, "[[%-v]]"}, + {"%+v", [1]flagPrinter{}, "[[%+v]]"}, + {"%#v", [1]flagPrinter{}, "[1]fmt_test.flagPrinter{[%#v]}"}, + {"% v", [1]flagPrinter{}, "[[% v]]"}, + {"%0v", [1]flagPrinter{}, "[[%0v]]"}, + {"%1.2v", [1]flagPrinter{}, "[[%1.2v]]"}, + {"%-1.2v", [1]flagPrinter{}, "[[%-1.2v]]"}, + {"%+1.2v", [1]flagPrinter{}, "[[%+1.2v]]"}, + {"%-+1.2v", [1]flagPrinter{}, "[[%+-1.2v]]"}, + {"%-+1.2vbc", [1]flagPrinter{}, "[[%+-1.2v]]bc"}, + {"%-1.2vbc", [1]flagPrinter{}, "[[%-1.2v]]bc"}, + {"%-0vbc", [1]flagPrinter{}, "[[%-0v]]bc"}, +} + +func TestFormatterFlags(t *testing.T) { + for _, tt := range formatterFlagTests { + s := Sprintf(tt.in, tt.val) + if s != tt.out { + t.Errorf("Sprintf(%q, %T) = %q, want %q", tt.in, tt.val, s, tt.out) + } + } +} + +func TestParsenum(t *testing.T) { + testCases := []struct { + s string + start, end int + num int + isnum bool + newi int + }{ + {"a123", 0, 4, 0, false, 0}, + {"1234", 1, 1, 0, false, 1}, + {"123a", 0, 4, 123, true, 3}, + {"12a3", 0, 4, 12, true, 2}, + {"1234", 0, 4, 1234, true, 4}, + {"1a234", 1, 3, 0, false, 1}, + } + for _, tt := range testCases { + num, isnum, newi := Parsenum(tt.s, tt.start, tt.end) + if num != tt.num || isnum != tt.isnum || newi != tt.newi { + t.Errorf("parsenum(%q, %d, %d) = %d, %v, %d, want %d, %v, %d", tt.s, tt.start, tt.end, num, isnum, newi, tt.num, tt.isnum, tt.newi) + } + } +} + +// Test the various Append printers. The details are well tested above; +// here we just make sure the byte slice is updated. + +const ( + appendResult = "hello world, 23" + hello = "hello " +) + +func TestAppendf(t *testing.T) { + b := make([]byte, 100) + b = b[:copy(b, hello)] + got := Appendf(b, "world, %d", 23) + if string(got) != appendResult { + t.Fatalf("Appendf returns %q not %q", got, appendResult) + } + if &b[0] != &got[0] { + t.Fatalf("Appendf allocated a new slice") + } +} + +func TestAppend(t *testing.T) { + b := make([]byte, 100) + b = b[:copy(b, hello)] + got := Append(b, "world", ", ", 23) + if string(got) != appendResult { + t.Fatalf("Append returns %q not %q", got, appendResult) + } + if &b[0] != &got[0] { + t.Fatalf("Append allocated a new slice") + } +} + +func TestAppendln(t *testing.T) { + b := make([]byte, 100) + b = b[:copy(b, hello)] + got := Appendln(b, "world,", 23) + if string(got) != appendResult+"\n" { + t.Fatalf("Appendln returns %q not %q", got, appendResult+"\n") + } + if &b[0] != &got[0] { + t.Fatalf("Appendln allocated a new slice") + } +} + +// noliteral prevents escape analysis from recognizing a literal value. +// +//go:noinline +func noliteral[T any](t T) T { + return t +} diff --git a/go/src/fmt/format.go b/go/src/fmt/format.go new file mode 100644 index 0000000000000000000000000000000000000000..334a94e2983e634a0d010742e93dc39d30fa6b9d --- /dev/null +++ b/go/src/fmt/format.go @@ -0,0 +1,595 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt + +import ( + "strconv" + "unicode/utf8" +) + +const ( + ldigits = "0123456789abcdefx" + udigits = "0123456789ABCDEFX" +) + +const ( + signed = true + unsigned = false +) + +// flags placed in a separate struct for easy clearing. +type fmtFlags struct { + widPresent bool + precPresent bool + minus bool + plus bool + sharp bool + space bool + zero bool + + // For the formats %+v %#v, we set the plusV/sharpV flags + // and clear the plus/sharp flags since %+v and %#v are in effect + // different, flagless formats set at the top level. + plusV bool + sharpV bool +} + +// A fmt is the raw formatter used by Printf etc. +// It prints into a buffer that must be set up separately. +type fmt struct { + buf *buffer + + fmtFlags + + wid int // width + prec int // precision + + // intbuf is large enough to store %b of an int64 with a sign and + // avoids padding at the end of the struct on 32 bit architectures. + intbuf [68]byte +} + +func (f *fmt) clearflags() { + f.fmtFlags = fmtFlags{} + f.wid = 0 + f.prec = 0 +} + +func (f *fmt) init(buf *buffer) { + f.buf = buf + f.clearflags() +} + +// writePadding generates n bytes of padding. +func (f *fmt) writePadding(n int) { + if n <= 0 { // No padding bytes needed. + return + } + buf := *f.buf + oldLen := len(buf) + newLen := oldLen + n + // Make enough room for padding. + if newLen > cap(buf) { + buf = make(buffer, cap(buf)*2+n) + copy(buf, *f.buf) + } + // Decide which byte the padding should be filled with. + padByte := byte(' ') + // Zero padding is allowed only to the left. + if f.zero && !f.minus { + padByte = byte('0') + } + // Fill padding with padByte. + padding := buf[oldLen:newLen] + for i := range padding { + padding[i] = padByte + } + *f.buf = buf[:newLen] +} + +// pad appends b to f.buf, padded on left (!f.minus) or right (f.minus). +func (f *fmt) pad(b []byte) { + if !f.widPresent || f.wid == 0 { + f.buf.write(b) + return + } + width := f.wid - utf8.RuneCount(b) + if !f.minus { + // left padding + f.writePadding(width) + f.buf.write(b) + } else { + // right padding + f.buf.write(b) + f.writePadding(width) + } +} + +// padString appends s to f.buf, padded on left (!f.minus) or right (f.minus). +func (f *fmt) padString(s string) { + if !f.widPresent || f.wid == 0 { + f.buf.writeString(s) + return + } + width := f.wid - utf8.RuneCountInString(s) + if !f.minus { + // left padding + f.writePadding(width) + f.buf.writeString(s) + } else { + // right padding + f.buf.writeString(s) + f.writePadding(width) + } +} + +// fmtBoolean formats a boolean. +func (f *fmt) fmtBoolean(v bool) { + if v { + f.padString("true") + } else { + f.padString("false") + } +} + +// fmtUnicode formats a uint64 as "U+0078" or with f.sharp set as "U+0078 'x'". +func (f *fmt) fmtUnicode(u uint64) { + buf := f.intbuf[0:] + + // With default precision set the maximum needed buf length is 18 + // for formatting -1 with %#U ("U+FFFFFFFFFFFFFFFF") which fits + // into the already allocated intbuf with a capacity of 68 bytes. + prec := 4 + if f.precPresent && f.prec > 4 { + prec = f.prec + // Compute space needed for "U+" , number, " '", character, "'". + width := 2 + prec + 2 + utf8.UTFMax + 1 + if width > len(buf) { + buf = make([]byte, width) + } + } + + // Format into buf, ending at buf[i]. Formatting numbers is easier right-to-left. + i := len(buf) + + // For %#U we want to add a space and a quoted character at the end of the buffer. + if f.sharp && u <= utf8.MaxRune && strconv.IsPrint(rune(u)) { + i-- + buf[i] = '\'' + i -= utf8.RuneLen(rune(u)) + utf8.EncodeRune(buf[i:], rune(u)) + i-- + buf[i] = '\'' + i-- + buf[i] = ' ' + } + // Format the Unicode code point u as a hexadecimal number. + for u >= 16 { + i-- + buf[i] = udigits[u&0xF] + prec-- + u >>= 4 + } + i-- + buf[i] = udigits[u] + prec-- + // Add zeros in front of the number until requested precision is reached. + for prec > 0 { + i-- + buf[i] = '0' + prec-- + } + // Add a leading "U+". + i-- + buf[i] = '+' + i-- + buf[i] = 'U' + + oldZero := f.zero + f.zero = false + f.pad(buf[i:]) + f.zero = oldZero +} + +// fmtInteger formats signed and unsigned integers. +func (f *fmt) fmtInteger(u uint64, base int, isSigned bool, verb rune, digits string) { + negative := isSigned && int64(u) < 0 + if negative { + u = -u + } + + buf := f.intbuf[0:] + // The already allocated f.intbuf with a capacity of 68 bytes + // is large enough for integer formatting when no precision or width is set. + if f.widPresent || f.precPresent { + // Account 3 extra bytes for possible addition of a sign and "0x". + width := 3 + f.wid + f.prec // wid and prec are always positive. + if width > len(buf) { + // We're going to need a bigger boat. + buf = make([]byte, width) + } + } + + // Two ways to ask for extra leading zero digits: %.3d or %03d. + // If both are specified the f.zero flag is ignored and + // padding with spaces is used instead. + prec := 0 + if f.precPresent { + prec = f.prec + // Precision of 0 and value of 0 means "print nothing" but padding. + if prec == 0 && u == 0 { + oldZero := f.zero + f.zero = false + f.writePadding(f.wid) + f.zero = oldZero + return + } + } else if f.zero && !f.minus && f.widPresent { // Zero padding is allowed only to the left. + prec = f.wid + if negative || f.plus || f.space { + prec-- // leave room for sign + } + } + + // Because printing is easier right-to-left: format u into buf, ending at buf[i]. + // We could make things marginally faster by splitting the 32-bit case out + // into a separate block but it's not worth the duplication, so u has 64 bits. + i := len(buf) + // Use constants for the division and modulo for more efficient code. + // Switch cases ordered by popularity. + switch base { + case 10: + for u >= 10 { + i-- + next := u / 10 + buf[i] = byte('0' + u - next*10) + u = next + } + case 16: + for u >= 16 { + i-- + buf[i] = digits[u&0xF] + u >>= 4 + } + case 8: + for u >= 8 { + i-- + buf[i] = byte('0' + u&7) + u >>= 3 + } + case 2: + for u >= 2 { + i-- + buf[i] = byte('0' + u&1) + u >>= 1 + } + default: + panic("fmt: unknown base; can't happen") + } + i-- + buf[i] = digits[u] + for i > 0 && prec > len(buf)-i { + i-- + buf[i] = '0' + } + + // Various prefixes: 0x, -, etc. + if f.sharp { + switch base { + case 2: + // Add a leading 0b. + i-- + buf[i] = 'b' + i-- + buf[i] = '0' + case 8: + if buf[i] != '0' { + i-- + buf[i] = '0' + } + case 16: + // Add a leading 0x or 0X. + i-- + buf[i] = digits[16] + i-- + buf[i] = '0' + } + } + if verb == 'O' { + i-- + buf[i] = 'o' + i-- + buf[i] = '0' + } + + if negative { + i-- + buf[i] = '-' + } else if f.plus { + i-- + buf[i] = '+' + } else if f.space { + i-- + buf[i] = ' ' + } + + // Left padding with zeros has already been handled like precision earlier + // or the f.zero flag is ignored due to an explicitly set precision. + oldZero := f.zero + f.zero = false + f.pad(buf[i:]) + f.zero = oldZero +} + +// truncateString truncates the string s to the specified precision, if present. +func (f *fmt) truncateString(s string) string { + if f.precPresent { + n := f.prec + for i := range s { + n-- + if n < 0 { + return s[:i] + } + } + } + return s +} + +// truncate truncates the byte slice b as a string of the specified precision, if present. +func (f *fmt) truncate(b []byte) []byte { + if f.precPresent { + n := f.prec + for i := 0; i < len(b); { + n-- + if n < 0 { + return b[:i] + } + _, wid := utf8.DecodeRune(b[i:]) + i += wid + } + } + return b +} + +// fmtS formats a string. +func (f *fmt) fmtS(s string) { + s = f.truncateString(s) + f.padString(s) +} + +// fmtBs formats the byte slice b as if it was formatted as string with fmtS. +func (f *fmt) fmtBs(b []byte) { + b = f.truncate(b) + f.pad(b) +} + +// fmtSbx formats a string or byte slice as a hexadecimal encoding of its bytes. +func (f *fmt) fmtSbx(s string, b []byte, digits string) { + length := len(b) + if b == nil { + // No byte slice present. Assume string s should be encoded. + length = len(s) + } + // Set length to not process more bytes than the precision demands. + if f.precPresent && f.prec < length { + length = f.prec + } + // Compute width of the encoding taking into account the f.sharp and f.space flag. + width := 2 * length + if width > 0 { + if f.space { + // Each element encoded by two hexadecimals will get a leading 0x or 0X. + if f.sharp { + width *= 2 + } + // Elements will be separated by a space. + width += length - 1 + } else if f.sharp { + // Only a leading 0x or 0X will be added for the whole string. + width += 2 + } + } else { // The byte slice or string that should be encoded is empty. + if f.widPresent { + f.writePadding(f.wid) + } + return + } + // Handle padding to the left. + if f.widPresent && f.wid > width && !f.minus { + f.writePadding(f.wid - width) + } + // Write the encoding directly into the output buffer. + buf := *f.buf + if f.sharp { + // Add leading 0x or 0X. + buf = append(buf, '0', digits[16]) + } + var c byte + for i := 0; i < length; i++ { + if f.space && i > 0 { + // Separate elements with a space. + buf = append(buf, ' ') + if f.sharp { + // Add leading 0x or 0X for each element. + buf = append(buf, '0', digits[16]) + } + } + if b != nil { + c = b[i] // Take a byte from the input byte slice. + } else { + c = s[i] // Take a byte from the input string. + } + // Encode each byte as two hexadecimal digits. + buf = append(buf, digits[c>>4], digits[c&0xF]) + } + *f.buf = buf + // Handle padding to the right. + if f.widPresent && f.wid > width && f.minus { + f.writePadding(f.wid - width) + } +} + +// fmtSx formats a string as a hexadecimal encoding of its bytes. +func (f *fmt) fmtSx(s, digits string) { + f.fmtSbx(s, nil, digits) +} + +// fmtBx formats a byte slice as a hexadecimal encoding of its bytes. +func (f *fmt) fmtBx(b []byte, digits string) { + f.fmtSbx("", b, digits) +} + +// fmtQ formats a string as a double-quoted, escaped Go string constant. +// If f.sharp is set a raw (backquoted) string may be returned instead +// if the string does not contain any control characters other than tab. +func (f *fmt) fmtQ(s string) { + s = f.truncateString(s) + if f.sharp && strconv.CanBackquote(s) { + f.padString("`" + s + "`") + return + } + buf := f.intbuf[:0] + if f.plus { + f.pad(strconv.AppendQuoteToASCII(buf, s)) + } else { + f.pad(strconv.AppendQuote(buf, s)) + } +} + +// fmtC formats an integer as a Unicode character. +// If the character is not valid Unicode, it will print '\ufffd'. +func (f *fmt) fmtC(c uint64) { + // Explicitly check whether c exceeds utf8.MaxRune since the conversion + // of a uint64 to a rune may lose precision that indicates an overflow. + r := rune(c) + if c > utf8.MaxRune { + r = utf8.RuneError + } + buf := f.intbuf[:0] + f.pad(utf8.AppendRune(buf, r)) +} + +// fmtQc formats an integer as a single-quoted, escaped Go character constant. +// If the character is not valid Unicode, it will print '\ufffd'. +func (f *fmt) fmtQc(c uint64) { + r := rune(c) + if c > utf8.MaxRune { + r = utf8.RuneError + } + buf := f.intbuf[:0] + if f.plus { + f.pad(strconv.AppendQuoteRuneToASCII(buf, r)) + } else { + f.pad(strconv.AppendQuoteRune(buf, r)) + } +} + +// fmtFloat formats a float64. It assumes that verb is a valid format specifier +// for strconv.AppendFloat and therefore fits into a byte. +func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) { + // Explicit precision in format specifier overrules default precision. + if f.precPresent { + prec = f.prec + } + // Format number, reserving space for leading + sign if needed. + num := strconv.AppendFloat(f.intbuf[:1], v, byte(verb), prec, size) + if num[1] == '-' || num[1] == '+' { + num = num[1:] + } else { + num[0] = '+' + } + // f.space means to add a leading space instead of a "+" sign unless + // the sign is explicitly asked for by f.plus. + if f.space && num[0] == '+' && !f.plus { + num[0] = ' ' + } + // Special handling for infinities and NaN, + // which don't look like a number so shouldn't be padded with zeros. + if num[1] == 'I' || num[1] == 'N' { + oldZero := f.zero + f.zero = false + // Remove sign before NaN if not asked for. + if num[1] == 'N' && !f.space && !f.plus { + num = num[1:] + } + f.pad(num) + f.zero = oldZero + return + } + // The sharp flag forces printing a decimal point for non-binary formats + // and retains trailing zeros, which we may need to restore. + if f.sharp && verb != 'b' { + digits := 0 + switch verb { + case 'v', 'g', 'G', 'x': + digits = prec + // If no precision is set explicitly use a precision of 6. + if digits == -1 { + digits = 6 + } + } + + // Buffer pre-allocated with enough room for + // exponent notations of the form "e+123" or "p-1023". + var tailBuf [6]byte + tail := tailBuf[:0] + + hasDecimalPoint := false + sawNonzeroDigit := false + // Starting from i = 1 to skip sign at num[0]. + for i := 1; i < len(num); i++ { + switch num[i] { + case '.': + hasDecimalPoint = true + case 'p', 'P': + tail = append(tail, num[i:]...) + num = num[:i] + case 'e', 'E': + if verb != 'x' && verb != 'X' { + tail = append(tail, num[i:]...) + num = num[:i] + break + } + fallthrough + default: + if num[i] != '0' { + sawNonzeroDigit = true + } + // Count significant digits after the first non-zero digit. + if sawNonzeroDigit { + digits-- + } + } + } + if !hasDecimalPoint { + // Leading digit 0 should contribute once to digits. + if len(num) == 2 && num[1] == '0' { + digits-- + } + num = append(num, '.') + } + for digits > 0 { + num = append(num, '0') + digits-- + } + num = append(num, tail...) + } + // We want a sign if asked for and if the sign is not positive. + if f.plus || num[0] != '+' { + // If we're zero padding to the left we want the sign before the leading zeros. + // Achieve this by writing the sign out and then padding the unsigned number. + // Zero padding is allowed only to the left. + if f.zero && !f.minus && f.widPresent && f.wid > len(num) { + f.buf.writeByte(num[0]) + f.writePadding(f.wid - len(num)) + f.buf.write(num[1:]) + return + } + f.pad(num) + return + } + // No sign to show and the number is positive; just print the unsigned number. + f.pad(num[1:]) +} diff --git a/go/src/fmt/gostringer_example_test.go b/go/src/fmt/gostringer_example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ab19ee3b94d2e310c8962e85aed95cabd0203bd2 --- /dev/null +++ b/go/src/fmt/gostringer_example_test.go @@ -0,0 +1,59 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + "fmt" +) + +// Address has a City, State and a Country. +type Address struct { + City string + State string + Country string +} + +// Person has a Name, Age and Address. +type Person struct { + Name string + Age uint + Addr *Address +} + +// GoString makes Person satisfy the GoStringer interface. +// The return value is valid Go code that can be used to reproduce the Person struct. +func (p Person) GoString() string { + if p.Addr != nil { + return fmt.Sprintf("Person{Name: %q, Age: %d, Addr: &Address{City: %q, State: %q, Country: %q}}", p.Name, int(p.Age), p.Addr.City, p.Addr.State, p.Addr.Country) + } + return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age)) +} + +func ExampleGoStringer() { + p1 := Person{ + Name: "Warren", + Age: 31, + Addr: &Address{ + City: "Denver", + State: "CO", + Country: "U.S.A.", + }, + } + // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to + // Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)} + fmt.Printf("%#v\n", p1) + + p2 := Person{ + Name: "Theia", + Age: 4, + } + // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to + // Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)} + fmt.Printf("%#v\n", p2) + + // Output: + // Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}} + // Person{Name: "Theia", Age: 4} +} diff --git a/go/src/fmt/print.go b/go/src/fmt/print.go new file mode 100644 index 0000000000000000000000000000000000000000..2340ceed8f294488d73d28e1ffd26a3fa67a2eb1 --- /dev/null +++ b/go/src/fmt/print.go @@ -0,0 +1,1221 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt + +import ( + "internal/fmtsort" + "io" + "os" + "reflect" + "strconv" + "sync" + "unicode/utf8" +) + +// Strings for use with buffer.WriteString. +// This is less overhead than using buffer.Write with byte arrays. +const ( + commaSpaceString = ", " + nilAngleString = "" + nilParenString = "(nil)" + nilString = "nil" + mapString = "map[" + percentBangString = "%!" + missingString = "(MISSING)" + badIndexString = "(BADINDEX)" + panicString = "(PANIC=" + extraString = "%!(EXTRA " + badWidthString = "%!(BADWIDTH)" + badPrecString = "%!(BADPREC)" + noVerbString = "%!(NOVERB)" + invReflectString = "" +) + +// State represents the printer state passed to custom formatters. +// It provides access to the [io.Writer] interface plus information about +// the flags and options for the operand's format specifier. +type State interface { + // Write is the function to call to emit formatted output to be printed. + Write(b []byte) (n int, err error) + // Width returns the value of the width option and whether it has been set. + Width() (wid int, ok bool) + // Precision returns the value of the precision option and whether it has been set. + Precision() (prec int, ok bool) + + // Flag reports whether the flag c, a character, has been set. + Flag(c int) bool +} + +// Formatter is implemented by any value that has a Format method. +// The implementation controls how [State] and rune are interpreted, +// and may call [Sprint] or [Fprint](f) etc. to generate its output. +type Formatter interface { + Format(f State, verb rune) +} + +// Stringer is implemented by any value that has a String method, +// which defines the “native” format for that value. +// The String method is used to print values passed as an operand +// to any format that accepts a string or to an unformatted printer +// such as [Print]. +type Stringer interface { + String() string +} + +// GoStringer is implemented by any value that has a GoString method, +// which defines the Go syntax for that value. +// The GoString method is used to print values passed as an operand +// to a %#v format. +type GoStringer interface { + GoString() string +} + +// FormatString returns a string representing the fully qualified formatting +// directive captured by the [State], followed by the argument verb. ([State] does not +// itself contain the verb.) The result has a leading percent sign followed by any +// flags, the width, and the precision. Missing flags, width, and precision are +// omitted. This function allows a [Formatter] to reconstruct the original +// directive triggering the call to Format. +func FormatString(state State, verb rune) string { + var tmp [16]byte // Use a local buffer. + b := append(tmp[:0], '%') + for _, c := range " +-#0" { // All known flags + if state.Flag(int(c)) { // The argument is an int for historical reasons. + b = append(b, byte(c)) + } + } + if w, ok := state.Width(); ok { + b = strconv.AppendInt(b, int64(w), 10) + } + if p, ok := state.Precision(); ok { + b = append(b, '.') + b = strconv.AppendInt(b, int64(p), 10) + } + b = utf8.AppendRune(b, verb) + return string(b) +} + +// Use simple []byte instead of bytes.Buffer to avoid large dependency. +type buffer []byte + +func (b *buffer) write(p []byte) { + *b = append(*b, p...) +} + +func (b *buffer) writeString(s string) { + *b = append(*b, s...) +} + +func (b *buffer) writeByte(c byte) { + *b = append(*b, c) +} + +func (b *buffer) writeRune(r rune) { + *b = utf8.AppendRune(*b, r) +} + +// pp is used to store a printer's state and is reused with sync.Pool to avoid allocations. +type pp struct { + buf buffer + + // arg holds the current item, as an interface{}. + arg any + + // value is used instead of arg for reflect values. + value reflect.Value + + // fmt is used to format basic items such as integers or strings. + fmt fmt + + // reordered records whether the format string used argument reordering. + reordered bool + // goodArgNum records whether the most recent reordering directive was valid. + goodArgNum bool + // panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion. + panicking bool + // erroring is set when printing an error string to guard against calling handleMethods. + erroring bool + // wrapErrs is set when the format string may contain a %w verb. + wrapErrs bool + // wrappedErrs records the targets of the %w verb. + wrappedErrs []int +} + +var ppFree = sync.Pool{ + New: func() any { return new(pp) }, +} + +// newPrinter allocates a new pp struct or grabs a cached one. +func newPrinter() *pp { + p := ppFree.Get().(*pp) + p.panicking = false + p.erroring = false + p.wrapErrs = false + p.fmt.init(&p.buf) + return p +} + +// free saves used pp structs in ppFree; avoids an allocation per invocation. +func (p *pp) free() { + // Proper usage of a sync.Pool requires each entry to have approximately + // the same memory cost. To obtain this property when the stored type + // contains a variably-sized buffer, we add a hard limit on the maximum + // buffer to place back in the pool. If the buffer is larger than the + // limit, we drop the buffer and recycle just the printer. + // + // See https://golang.org/issue/23199. + if cap(p.buf) > 64*1024 { + p.buf = nil + } else { + p.buf = p.buf[:0] + } + if cap(p.wrappedErrs) > 8 { + p.wrappedErrs = nil + } + + p.arg = nil + p.value = reflect.Value{} + p.wrappedErrs = p.wrappedErrs[:0] + ppFree.Put(p) +} + +func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent } + +func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent } + +func (p *pp) Flag(b int) bool { + switch b { + case '-': + return p.fmt.minus + case '+': + return p.fmt.plus || p.fmt.plusV + case '#': + return p.fmt.sharp || p.fmt.sharpV + case ' ': + return p.fmt.space + case '0': + return p.fmt.zero + } + return false +} + +// Write implements [io.Writer] so we can call [Fprintf] on a pp (through [State]), for +// recursive use in custom verbs. +func (p *pp) Write(b []byte) (ret int, err error) { + p.buf.write(b) + return len(b), nil +} + +// WriteString implements [io.StringWriter] so that we can call [io.WriteString] +// on a pp (through state), for efficiency. +func (p *pp) WriteString(s string) (ret int, err error) { + p.buf.writeString(s) + return len(s), nil +} + +// These routines end in 'f' and take a format string. + +// Fprintf formats according to a format specifier and writes to w. +// It returns the number of bytes written and any write error encountered. +func Fprintf(w io.Writer, format string, a ...any) (n int, err error) { + p := newPrinter() + p.doPrintf(format, a) + n, err = w.Write(p.buf) + p.free() + return +} + +// Printf formats according to a format specifier and writes to standard output. +// It returns the number of bytes written and any write error encountered. +func Printf(format string, a ...any) (n int, err error) { + return Fprintf(os.Stdout, format, a...) +} + +// Sprintf formats according to a format specifier and returns the resulting string. +func Sprintf(format string, a ...any) string { + p := newPrinter() + p.doPrintf(format, a) + s := string(p.buf) + p.free() + return s +} + +// Appendf formats according to a format specifier, appends the result to the byte +// slice, and returns the updated slice. +func Appendf(b []byte, format string, a ...any) []byte { + p := newPrinter() + p.doPrintf(format, a) + b = append(b, p.buf...) + p.free() + return b +} + +// These routines do not take a format string + +// Fprint formats using the default formats for its operands and writes to w. +// Spaces are added between operands when neither is a string. +// It returns the number of bytes written and any write error encountered. +func Fprint(w io.Writer, a ...any) (n int, err error) { + p := newPrinter() + p.doPrint(a) + n, err = w.Write(p.buf) + p.free() + return +} + +// Print formats using the default formats for its operands and writes to standard output. +// Spaces are added between operands when neither is a string. +// It returns the number of bytes written and any write error encountered. +func Print(a ...any) (n int, err error) { + return Fprint(os.Stdout, a...) +} + +// Sprint formats using the default formats for its operands and returns the resulting string. +// Spaces are added between operands when neither is a string. +func Sprint(a ...any) string { + p := newPrinter() + p.doPrint(a) + s := string(p.buf) + p.free() + return s +} + +// Append formats using the default formats for its operands, appends the result to +// the byte slice, and returns the updated slice. +// Spaces are added between operands when neither is a string. +func Append(b []byte, a ...any) []byte { + p := newPrinter() + p.doPrint(a) + b = append(b, p.buf...) + p.free() + return b +} + +// These routines end in 'ln', do not take a format string, +// always add spaces between operands, and add a newline +// after the last operand. + +// Fprintln formats using the default formats for its operands and writes to w. +// Spaces are always added between operands and a newline is appended. +// It returns the number of bytes written and any write error encountered. +func Fprintln(w io.Writer, a ...any) (n int, err error) { + p := newPrinter() + p.doPrintln(a) + n, err = w.Write(p.buf) + p.free() + return +} + +// Println formats using the default formats for its operands and writes to standard output. +// Spaces are always added between operands and a newline is appended. +// It returns the number of bytes written and any write error encountered. +func Println(a ...any) (n int, err error) { + return Fprintln(os.Stdout, a...) +} + +// Sprintln formats using the default formats for its operands and returns the resulting string. +// Spaces are always added between operands and a newline is appended. +func Sprintln(a ...any) string { + p := newPrinter() + p.doPrintln(a) + s := string(p.buf) + p.free() + return s +} + +// Appendln formats using the default formats for its operands, appends the result +// to the byte slice, and returns the updated slice. Spaces are always added +// between operands and a newline is appended. +func Appendln(b []byte, a ...any) []byte { + p := newPrinter() + p.doPrintln(a) + b = append(b, p.buf...) + p.free() + return b +} + +// getField gets the i'th field of the struct value. +// If the field itself is a non-nil interface, return a value for +// the thing inside the interface, not the interface itself. +func getField(v reflect.Value, i int) reflect.Value { + val := v.Field(i) + if val.Kind() == reflect.Interface && !val.IsNil() { + val = val.Elem() + } + return val +} + +// tooLarge reports whether the magnitude of the integer is +// too large to be used as a formatting width or precision. +func tooLarge(x int) bool { + const max int = 1e6 + return x > max || x < -max +} + +// parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present. +func parsenum(s string, start, end int) (num int, isnum bool, newi int) { + if start >= end { + return 0, false, end + } + for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ { + if tooLarge(num) { + return 0, false, end // Overflow; crazy long number most likely. + } + num = num*10 + int(s[newi]-'0') + isnum = true + } + return +} + +func (p *pp) unknownType(v reflect.Value) { + if !v.IsValid() { + p.buf.writeString(nilAngleString) + return + } + p.buf.writeByte('?') + p.buf.writeString(v.Type().String()) + p.buf.writeByte('?') +} + +func (p *pp) badVerb(verb rune) { + p.erroring = true + p.buf.writeString(percentBangString) + p.buf.writeRune(verb) + p.buf.writeByte('(') + switch { + case p.arg != nil: + p.buf.writeString(reflect.TypeOf(p.arg).String()) + p.buf.writeByte('=') + p.printArg(p.arg, 'v') + case p.value.IsValid(): + p.buf.writeString(p.value.Type().String()) + p.buf.writeByte('=') + p.printValue(p.value, 'v', 0) + default: + p.buf.writeString(nilAngleString) + } + p.buf.writeByte(')') + p.erroring = false +} + +func (p *pp) fmtBool(v bool, verb rune) { + switch verb { + case 't', 'v': + p.fmt.fmtBoolean(v) + default: + p.badVerb(verb) + } +} + +// fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or +// not, as requested, by temporarily setting the sharp flag. +func (p *pp) fmt0x64(v uint64, leading0x bool) { + sharp := p.fmt.sharp + p.fmt.sharp = leading0x + p.fmt.fmtInteger(v, 16, unsigned, 'v', ldigits) + p.fmt.sharp = sharp +} + +// fmtInteger formats a signed or unsigned integer. +func (p *pp) fmtInteger(v uint64, isSigned bool, verb rune) { + switch verb { + case 'v': + if p.fmt.sharpV && !isSigned { + p.fmt0x64(v, true) + } else { + p.fmt.fmtInteger(v, 10, isSigned, verb, ldigits) + } + case 'd': + p.fmt.fmtInteger(v, 10, isSigned, verb, ldigits) + case 'b': + p.fmt.fmtInteger(v, 2, isSigned, verb, ldigits) + case 'o', 'O': + p.fmt.fmtInteger(v, 8, isSigned, verb, ldigits) + case 'x': + p.fmt.fmtInteger(v, 16, isSigned, verb, ldigits) + case 'X': + p.fmt.fmtInteger(v, 16, isSigned, verb, udigits) + case 'c': + p.fmt.fmtC(v) + case 'q': + p.fmt.fmtQc(v) + case 'U': + p.fmt.fmtUnicode(v) + default: + p.badVerb(verb) + } +} + +// fmtFloat formats a float. The default precision for each verb +// is specified as last argument in the call to fmt_float. +func (p *pp) fmtFloat(v float64, size int, verb rune) { + switch verb { + case 'v': + p.fmt.fmtFloat(v, size, 'g', -1) + case 'b', 'g', 'G', 'x', 'X': + p.fmt.fmtFloat(v, size, verb, -1) + case 'f', 'e', 'E': + p.fmt.fmtFloat(v, size, verb, 6) + case 'F': + p.fmt.fmtFloat(v, size, 'f', 6) + default: + p.badVerb(verb) + } +} + +// fmtComplex formats a complex number v with +// r = real(v) and j = imag(v) as (r+ji) using +// fmtFloat for r and j formatting. +func (p *pp) fmtComplex(v complex128, size int, verb rune) { + // Make sure any unsupported verbs are found before the + // calls to fmtFloat to not generate an incorrect error string. + switch verb { + case 'v', 'b', 'g', 'G', 'x', 'X', 'f', 'F', 'e', 'E': + oldPlus := p.fmt.plus + p.buf.writeByte('(') + p.fmtFloat(real(v), size/2, verb) + // Imaginary part always has a sign. + p.fmt.plus = true + p.fmtFloat(imag(v), size/2, verb) + p.buf.writeString("i)") + p.fmt.plus = oldPlus + default: + p.badVerb(verb) + } +} + +func (p *pp) fmtString(v string, verb rune) { + switch verb { + case 'v': + if p.fmt.sharpV { + p.fmt.fmtQ(v) + } else { + p.fmt.fmtS(v) + } + case 's': + p.fmt.fmtS(v) + case 'x': + p.fmt.fmtSx(v, ldigits) + case 'X': + p.fmt.fmtSx(v, udigits) + case 'q': + p.fmt.fmtQ(v) + default: + p.badVerb(verb) + } +} + +func (p *pp) fmtBytes(v []byte, verb rune, typeString string) { + switch verb { + case 'v', 'd': + if p.fmt.sharpV { + p.buf.writeString(typeString) + if v == nil { + p.buf.writeString(nilParenString) + return + } + p.buf.writeByte('{') + for i, c := range v { + if i > 0 { + p.buf.writeString(commaSpaceString) + } + p.fmt0x64(uint64(c), true) + } + p.buf.writeByte('}') + } else { + p.buf.writeByte('[') + for i, c := range v { + if i > 0 { + p.buf.writeByte(' ') + } + p.fmt.fmtInteger(uint64(c), 10, unsigned, verb, ldigits) + } + p.buf.writeByte(']') + } + case 's': + p.fmt.fmtBs(v) + case 'x': + p.fmt.fmtBx(v, ldigits) + case 'X': + p.fmt.fmtBx(v, udigits) + case 'q': + p.fmt.fmtQ(string(v)) + default: + p.printValue(reflect.ValueOf(v), verb, 0) + } +} + +func (p *pp) fmtPointer(value reflect.Value, verb rune) { + var u uintptr + switch value.Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Slice, reflect.UnsafePointer: + u = uintptr(value.UnsafePointer()) + default: + p.badVerb(verb) + return + } + + switch verb { + case 'v': + if p.fmt.sharpV { + p.buf.writeByte('(') + p.buf.writeString(value.Type().String()) + p.buf.writeString(")(") + if u == 0 { + p.buf.writeString(nilString) + } else { + p.fmt0x64(uint64(u), true) + } + p.buf.writeByte(')') + } else { + if u == 0 { + p.fmt.padString(nilAngleString) + } else { + p.fmt0x64(uint64(u), !p.fmt.sharp) + } + } + case 'p': + p.fmt0x64(uint64(u), !p.fmt.sharp) + case 'b', 'o', 'd', 'x', 'X': + p.fmtInteger(uint64(u), unsigned, verb) + default: + p.badVerb(verb) + } +} + +func (p *pp) catchPanic(arg any, verb rune, method string) { + if err := recover(); err != nil { + // If it's a nil pointer, just say "". The likeliest causes are a + // Stringer that fails to guard against nil or a nil pointer for a + // value receiver, and in either case, "" is a nice result. + if v := reflect.ValueOf(arg); v.Kind() == reflect.Pointer && v.IsNil() { + p.buf.writeString(nilAngleString) + return + } + // Otherwise print a concise panic message. Most of the time the panic + // value will print itself nicely. + if p.panicking { + // Nested panics; the recursion in printArg cannot succeed. + panic(err) + } + + oldFlags := p.fmt.fmtFlags + // For this output we want default behavior. + p.fmt.clearflags() + + p.buf.writeString(percentBangString) + p.buf.writeRune(verb) + p.buf.writeString(panicString) + p.buf.writeString(method) + p.buf.writeString(" method: ") + p.panicking = true + p.printArg(err, 'v') + p.panicking = false + p.buf.writeByte(')') + + p.fmt.fmtFlags = oldFlags + } +} + +func (p *pp) handleMethods(verb rune) (handled bool) { + if p.erroring { + return + } + if verb == 'w' { + // It is invalid to use %w other than with Errorf or with a non-error arg. + _, ok := p.arg.(error) + if !ok || !p.wrapErrs { + p.badVerb(verb) + return true + } + // If the arg is a Formatter, pass 'v' as the verb to it. + verb = 'v' + } + + // Is it a Formatter? + if formatter, ok := p.arg.(Formatter); ok { + handled = true + defer p.catchPanic(p.arg, verb, "Format") + formatter.Format(p, verb) + return + } + + // If we're doing Go syntax and the argument knows how to supply it, take care of it now. + if p.fmt.sharpV { + if stringer, ok := p.arg.(GoStringer); ok { + handled = true + defer p.catchPanic(p.arg, verb, "GoString") + // Print the result of GoString unadorned. + p.fmt.fmtS(stringer.GoString()) + return + } + } else { + // If a string is acceptable according to the format, see if + // the value satisfies one of the string-valued interfaces. + // Println etc. set verb to %v, which is "stringable". + switch verb { + case 'v', 's', 'x', 'X', 'q': + // Is it an error or Stringer? + // The duplication in the bodies is necessary: + // setting handled and deferring catchPanic + // must happen before calling the method. + switch v := p.arg.(type) { + case error: + handled = true + defer p.catchPanic(p.arg, verb, "Error") + p.fmtString(v.Error(), verb) + return + + case Stringer: + handled = true + defer p.catchPanic(p.arg, verb, "String") + p.fmtString(v.String(), verb) + return + } + } + } + return false +} + +func (p *pp) printArg(arg any, verb rune) { + p.arg = arg + p.value = reflect.Value{} + + if arg == nil { + switch verb { + case 'T', 'v': + p.fmt.padString(nilAngleString) + default: + p.badVerb(verb) + } + return + } + + // Special processing considerations. + // %T (the value's type) and %p (its address) are special; we always do them first. + switch verb { + case 'T': + p.fmt.fmtS(reflect.TypeOf(arg).String()) + return + case 'p': + p.fmtPointer(reflect.ValueOf(arg), 'p') + return + } + + // Some types can be done without reflection. + switch f := arg.(type) { + case bool: + p.fmtBool(f, verb) + case float32: + p.fmtFloat(float64(f), 32, verb) + case float64: + p.fmtFloat(f, 64, verb) + case complex64: + p.fmtComplex(complex128(f), 64, verb) + case complex128: + p.fmtComplex(f, 128, verb) + case int: + p.fmtInteger(uint64(f), signed, verb) + case int8: + p.fmtInteger(uint64(f), signed, verb) + case int16: + p.fmtInteger(uint64(f), signed, verb) + case int32: + p.fmtInteger(uint64(f), signed, verb) + case int64: + p.fmtInteger(uint64(f), signed, verb) + case uint: + p.fmtInteger(uint64(f), unsigned, verb) + case uint8: + p.fmtInteger(uint64(f), unsigned, verb) + case uint16: + p.fmtInteger(uint64(f), unsigned, verb) + case uint32: + p.fmtInteger(uint64(f), unsigned, verb) + case uint64: + p.fmtInteger(f, unsigned, verb) + case uintptr: + p.fmtInteger(uint64(f), unsigned, verb) + case string: + p.fmtString(f, verb) + case []byte: + p.fmtBytes(f, verb, "[]byte") + case reflect.Value: + // Handle extractable values with special methods + // since printValue does not handle them at depth 0. + if f.IsValid() && f.CanInterface() { + p.arg = f.Interface() + if p.handleMethods(verb) { + return + } + } + p.printValue(f, verb, 0) + default: + // If the type is not simple, it might have methods. + if !p.handleMethods(verb) { + // Need to use reflection, since the type had no + // interface methods that could be used for formatting. + p.printValue(reflect.ValueOf(f), verb, 0) + } + } +} + +// printValue is similar to printArg but starts with a reflect value, not an interface{} value. +// It does not handle 'p' and 'T' verbs because these should have been already handled by printArg. +func (p *pp) printValue(value reflect.Value, verb rune, depth int) { + // Handle values with special methods if not already handled by printArg (depth == 0). + if depth > 0 && value.IsValid() && value.CanInterface() { + p.arg = value.Interface() + if p.handleMethods(verb) { + return + } + } + p.arg = nil + p.value = value + + switch f := value; value.Kind() { + case reflect.Invalid: + if depth == 0 { + p.buf.writeString(invReflectString) + } else { + switch verb { + case 'v': + p.buf.writeString(nilAngleString) + default: + p.badVerb(verb) + } + } + case reflect.Bool: + p.fmtBool(f.Bool(), verb) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p.fmtInteger(uint64(f.Int()), signed, verb) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p.fmtInteger(f.Uint(), unsigned, verb) + case reflect.Float32: + p.fmtFloat(f.Float(), 32, verb) + case reflect.Float64: + p.fmtFloat(f.Float(), 64, verb) + case reflect.Complex64: + p.fmtComplex(f.Complex(), 64, verb) + case reflect.Complex128: + p.fmtComplex(f.Complex(), 128, verb) + case reflect.String: + p.fmtString(f.String(), verb) + case reflect.Map: + if p.fmt.sharpV { + p.buf.writeString(f.Type().String()) + if f.IsNil() { + p.buf.writeString(nilParenString) + return + } + p.buf.writeByte('{') + } else { + p.buf.writeString(mapString) + } + sorted := fmtsort.Sort(f) + for i, m := range sorted { + if i > 0 { + if p.fmt.sharpV { + p.buf.writeString(commaSpaceString) + } else { + p.buf.writeByte(' ') + } + } + p.printValue(m.Key, verb, depth+1) + p.buf.writeByte(':') + p.printValue(m.Value, verb, depth+1) + } + if p.fmt.sharpV { + p.buf.writeByte('}') + } else { + p.buf.writeByte(']') + } + case reflect.Struct: + if p.fmt.sharpV { + p.buf.writeString(f.Type().String()) + } + p.buf.writeByte('{') + for i := 0; i < f.NumField(); i++ { + if i > 0 { + if p.fmt.sharpV { + p.buf.writeString(commaSpaceString) + } else { + p.buf.writeByte(' ') + } + } + if p.fmt.plusV || p.fmt.sharpV { + if name := f.Type().Field(i).Name; name != "" { + p.buf.writeString(name) + p.buf.writeByte(':') + } + } + p.printValue(getField(f, i), verb, depth+1) + } + p.buf.writeByte('}') + case reflect.Interface: + value := f.Elem() + if !value.IsValid() { + if p.fmt.sharpV { + p.buf.writeString(f.Type().String()) + p.buf.writeString(nilParenString) + } else { + p.buf.writeString(nilAngleString) + } + } else { + p.printValue(value, verb, depth+1) + } + case reflect.Array, reflect.Slice: + switch verb { + case 's', 'q', 'x', 'X': + // Handle byte and uint8 slices and arrays special for the above verbs. + t := f.Type() + if t.Elem().Kind() == reflect.Uint8 { + var bytes []byte + if f.Kind() == reflect.Slice || f.CanAddr() { + bytes = f.Bytes() + } else { + // We have an array, but we cannot Bytes() a non-addressable array, + // so we build a slice by hand. This is a rare case but it would be nice + // if reflection could help a little more. + bytes = make([]byte, f.Len()) + for i := range bytes { + bytes[i] = byte(f.Index(i).Uint()) + } + } + p.fmtBytes(bytes, verb, t.String()) + return + } + } + if p.fmt.sharpV { + p.buf.writeString(f.Type().String()) + if f.Kind() == reflect.Slice && f.IsNil() { + p.buf.writeString(nilParenString) + return + } + p.buf.writeByte('{') + for i := 0; i < f.Len(); i++ { + if i > 0 { + p.buf.writeString(commaSpaceString) + } + p.printValue(f.Index(i), verb, depth+1) + } + p.buf.writeByte('}') + } else { + p.buf.writeByte('[') + for i := 0; i < f.Len(); i++ { + if i > 0 { + p.buf.writeByte(' ') + } + p.printValue(f.Index(i), verb, depth+1) + } + p.buf.writeByte(']') + } + case reflect.Pointer: + // pointer to array or slice or struct? ok at top level + // but not embedded (avoid loops) + if depth == 0 && f.UnsafePointer() != nil { + switch a := f.Elem(); a.Kind() { + case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map: + p.buf.writeByte('&') + p.printValue(a, verb, depth+1) + return + } + } + fallthrough + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + p.fmtPointer(f, verb) + default: + p.unknownType(f) + } +} + +// intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has integer type. +func intFromArg(a []any, argNum int) (num int, isInt bool, newArgNum int) { + newArgNum = argNum + if argNum < len(a) { + num, isInt = a[argNum].(int) // Almost always OK. + if !isInt { + // Work harder. + switch v := reflect.ValueOf(a[argNum]); v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + n := v.Int() + if int64(int(n)) == n { + num = int(n) + isInt = true + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + n := v.Uint() + if int64(n) >= 0 && uint64(int(n)) == n { + num = int(n) + isInt = true + } + default: + // Already 0, false. + } + } + newArgNum = argNum + 1 + if tooLarge(num) { + num = 0 + isInt = false + } + } + return +} + +// parseArgNumber returns the value of the bracketed number, minus 1 +// (explicit argument numbers are one-indexed but we want zero-indexed). +// The opening bracket is known to be present at format[0]. +// The returned values are the index, the number of bytes to consume +// up to the closing paren, if present, and whether the number parsed +// ok. The bytes to consume will be 1 if no closing paren is present. +func parseArgNumber(format string) (index int, wid int, ok bool) { + // There must be at least 3 bytes: [n]. + if len(format) < 3 { + return 0, 1, false + } + + // Find closing bracket. + for i := 1; i < len(format); i++ { + if format[i] == ']' { + width, ok, newi := parsenum(format, 1, i) + if !ok || newi != i { + return 0, i + 1, false + } + return width - 1, i + 1, true // arg numbers are one-indexed and skip paren. + } + } + return 0, 1, false +} + +// argNumber returns the next argument to evaluate, which is either the value of the passed-in +// argNum or the value of the bracketed integer that begins format[i:]. It also returns +// the new value of i, that is, the index of the next byte of the format to process. +func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) { + if len(format) <= i || format[i] != '[' { + return argNum, i, false + } + p.reordered = true + index, wid, ok := parseArgNumber(format[i:]) + if ok && 0 <= index && index < numArgs { + return index, i + wid, true + } + p.goodArgNum = false + return argNum, i + wid, ok +} + +func (p *pp) badArgNum(verb rune) { + p.buf.writeString(percentBangString) + p.buf.writeRune(verb) + p.buf.writeString(badIndexString) +} + +func (p *pp) missingArg(verb rune) { + p.buf.writeString(percentBangString) + p.buf.writeRune(verb) + p.buf.writeString(missingString) +} + +func (p *pp) doPrintf(format string, a []any) { + end := len(format) + argNum := 0 // we process one argument per non-trivial format + afterIndex := false // previous item in format was an index like [3]. + p.reordered = false +formatLoop: + for i := 0; i < end; { + p.goodArgNum = true + lasti := i + for i < end && format[i] != '%' { + i++ + } + if i > lasti { + p.buf.writeString(format[lasti:i]) + } + if i >= end { + // done processing format string + break + } + + // Process one verb + i++ + + // Do we have flags? + p.fmt.clearflags() + simpleFormat: + for ; i < end; i++ { + c := format[i] + switch c { + case '#': + p.fmt.sharp = true + case '0': + p.fmt.zero = true + case '+': + p.fmt.plus = true + case '-': + p.fmt.minus = true + case ' ': + p.fmt.space = true + default: + // Fast path for common case of ascii lower case simple verbs + // without precision or width or argument indices. + if 'a' <= c && c <= 'z' && argNum < len(a) { + switch c { + case 'w': + p.wrappedErrs = append(p.wrappedErrs, argNum) + fallthrough + case 'v': + // Go syntax + p.fmt.sharpV = p.fmt.sharp + p.fmt.sharp = false + // Struct-field syntax + p.fmt.plusV = p.fmt.plus + p.fmt.plus = false + } + p.printArg(a[argNum], rune(c)) + argNum++ + i++ + continue formatLoop + } + // Format is more complex than simple flags and a verb or is malformed. + break simpleFormat + } + } + + // Do we have an explicit argument index? + argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) + + // Do we have width? + if i < end && format[i] == '*' { + i++ + p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum) + + if !p.fmt.widPresent { + p.buf.writeString(badWidthString) + } + + // We have a negative width, so take its value and ensure + // that the minus flag is set + if p.fmt.wid < 0 { + p.fmt.wid = -p.fmt.wid + p.fmt.minus = true + p.fmt.zero = false // Do not pad with zeros to the right. + } + afterIndex = false + } else { + p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end) + if afterIndex && p.fmt.widPresent { // "%[3]2d" + p.goodArgNum = false + } + } + + // Do we have precision? + if i+1 < end && format[i] == '.' { + i++ + if afterIndex { // "%[3].2d" + p.goodArgNum = false + } + argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) + if i < end && format[i] == '*' { + i++ + p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum) + // Negative precision arguments don't make sense + if p.fmt.prec < 0 { + p.fmt.prec = 0 + p.fmt.precPresent = false + } + if !p.fmt.precPresent { + p.buf.writeString(badPrecString) + } + afterIndex = false + } else { + p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end) + if !p.fmt.precPresent { + p.fmt.prec = 0 + p.fmt.precPresent = true + } + } + } + + if !afterIndex { + argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) + } + + if i >= end { + p.buf.writeString(noVerbString) + break + } + + verb, size := utf8.DecodeRuneInString(format[i:]) + i += size + + switch { + case verb == '%': // Percent does not absorb operands and ignores f.wid and f.prec. + p.buf.writeByte('%') + case !p.goodArgNum: + p.badArgNum(verb) + case argNum >= len(a): // No argument left over to print for the current verb. + p.missingArg(verb) + case verb == 'w': + p.wrappedErrs = append(p.wrappedErrs, argNum) + fallthrough + case verb == 'v': + // Go syntax + p.fmt.sharpV = p.fmt.sharp + p.fmt.sharp = false + // Struct-field syntax + p.fmt.plusV = p.fmt.plus + p.fmt.plus = false + fallthrough + default: + p.printArg(a[argNum], verb) + argNum++ + } + } + + // Check for extra arguments unless the call accessed the arguments + // out of order, in which case it's too expensive to detect if they've all + // been used and arguably OK if they're not. + if !p.reordered && argNum < len(a) { + p.fmt.clearflags() + p.buf.writeString(extraString) + for i, arg := range a[argNum:] { + if i > 0 { + p.buf.writeString(commaSpaceString) + } + if arg == nil { + p.buf.writeString(nilAngleString) + } else { + p.buf.writeString(reflect.TypeOf(arg).String()) + p.buf.writeByte('=') + p.printArg(arg, 'v') + } + } + p.buf.writeByte(')') + } +} + +func (p *pp) doPrint(a []any) { + prevString := false + for argNum, arg := range a { + isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String + // Add a space between two non-string arguments. + if argNum > 0 && !isString && !prevString { + p.buf.writeByte(' ') + } + p.printArg(arg, 'v') + prevString = isString + } +} + +// doPrintln is like doPrint but always adds a space between arguments +// and a newline after the last argument. +func (p *pp) doPrintln(a []any) { + for argNum, arg := range a { + if argNum > 0 { + p.buf.writeByte(' ') + } + p.printArg(arg, 'v') + } + p.buf.writeByte('\n') +} diff --git a/go/src/fmt/scan.go b/go/src/fmt/scan.go new file mode 100644 index 0000000000000000000000000000000000000000..d8c7d263e059271bc591e5c29260601e4325145f --- /dev/null +++ b/go/src/fmt/scan.go @@ -0,0 +1,1238 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt + +import ( + "errors" + "io" + "math" + "os" + "reflect" + "strconv" + "sync" + "unicode/utf8" +) + +// ScanState represents the scanner state passed to custom scanners. +// Scanners may do rune-at-a-time scanning or ask the ScanState +// to discover the next space-delimited token. +type ScanState interface { + // ReadRune reads the next rune (Unicode code point) from the input. + // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will + // return EOF after returning the first '\n' or when reading beyond + // the specified width. + ReadRune() (r rune, size int, err error) + // UnreadRune causes the next call to ReadRune to return the same rune. + UnreadRune() error + // SkipSpace skips space in the input. Newlines are treated appropriately + // for the operation being performed; see the package documentation + // for more information. + SkipSpace() + // Token skips space in the input if skipSpace is true, then returns the + // run of Unicode code points c satisfying f(c). If f is nil, + // !unicode.IsSpace(c) is used; that is, the token will hold non-space + // characters. Newlines are treated appropriately for the operation being + // performed; see the package documentation for more information. + // The returned slice points to shared data that may be overwritten + // by the next call to Token, a call to a Scan function using the ScanState + // as input, or when the calling Scan method returns. + Token(skipSpace bool, f func(rune) bool) (token []byte, err error) + // Width returns the value of the width option and whether it has been set. + // The unit is Unicode code points. + Width() (wid int, ok bool) + // Because ReadRune is implemented by the interface, Read should never be + // called by the scanning routines and a valid implementation of + // ScanState may choose always to return an error from Read. + Read(buf []byte) (n int, err error) +} + +// Scanner is implemented by any value that has a Scan method, which scans +// the input for the representation of a value and stores the result in the +// receiver, which must be a pointer to be useful. The Scan method is called +// for any argument to [Scan], [Scanf], or [Scanln] that implements it. +type Scanner interface { + Scan(state ScanState, verb rune) error +} + +// Scan scans text read from standard input, storing successive +// space-separated values into successive arguments. Newlines count +// as space. It returns the number of items successfully scanned. +// If that is less than the number of arguments, err will report why. +func Scan(a ...any) (n int, err error) { + return Fscan(os.Stdin, a...) +} + +// Scanln is similar to [Scan], but stops scanning at a newline and +// after the final item there must be a newline or EOF. +func Scanln(a ...any) (n int, err error) { + return Fscanln(os.Stdin, a...) +} + +// Scanf scans text read from standard input, storing successive +// space-separated values into successive arguments as determined by +// the format. It returns the number of items successfully scanned. +// If that is less than the number of arguments, err will report why. +// Newlines in the input must match newlines in the format. +// The one exception: the verb %c always scans the next rune in the +// input, even if it is a space (or tab etc.) or newline. +func Scanf(format string, a ...any) (n int, err error) { + return Fscanf(os.Stdin, format, a...) +} + +type stringReader string + +func (r *stringReader) Read(b []byte) (n int, err error) { + n = copy(b, *r) + *r = (*r)[n:] + if n == 0 { + err = io.EOF + } + return +} + +// Sscan scans the argument string, storing successive space-separated +// values into successive arguments. Newlines count as space. It +// returns the number of items successfully scanned. If that is less +// than the number of arguments, err will report why. +func Sscan(str string, a ...any) (n int, err error) { + return Fscan((*stringReader)(&str), a...) +} + +// Sscanln is similar to [Sscan], but stops scanning at a newline and +// after the final item there must be a newline or EOF. +func Sscanln(str string, a ...any) (n int, err error) { + return Fscanln((*stringReader)(&str), a...) +} + +// Sscanf scans the argument string, storing successive space-separated +// values into successive arguments as determined by the format. It +// returns the number of items successfully parsed. +// Newlines in the input must match newlines in the format. +func Sscanf(str string, format string, a ...any) (n int, err error) { + return Fscanf((*stringReader)(&str), format, a...) +} + +// Fscan scans text read from r, storing successive space-separated +// values into successive arguments. Newlines count as space. It +// returns the number of items successfully scanned. If that is less +// than the number of arguments, err will report why. +func Fscan(r io.Reader, a ...any) (n int, err error) { + s, old := newScanState(r, true, false) + n, err = s.doScan(a) + s.free(old) + return +} + +// Fscanln is similar to [Fscan], but stops scanning at a newline and +// after the final item there must be a newline or EOF. +func Fscanln(r io.Reader, a ...any) (n int, err error) { + s, old := newScanState(r, false, true) + n, err = s.doScan(a) + s.free(old) + return +} + +// Fscanf scans text read from r, storing successive space-separated +// values into successive arguments as determined by the format. It +// returns the number of items successfully parsed. +// Newlines in the input must match newlines in the format. +func Fscanf(r io.Reader, format string, a ...any) (n int, err error) { + s, old := newScanState(r, false, false) + n, err = s.doScanf(format, a) + s.free(old) + return +} + +// scanError represents an error generated by the scanning software. +// It's used as a unique signature to identify such errors when recovering. +type scanError struct { + err error +} + +const eof = -1 + +// ss is the internal implementation of ScanState. +type ss struct { + rs io.RuneScanner // where to read input + buf buffer // token accumulator + count int // runes consumed so far. + atEOF bool // already read EOF + ssave +} + +// ssave holds the parts of ss that need to be +// saved and restored on recursive scans. +type ssave struct { + validSave bool // is or was a part of an actual ss. + nlIsEnd bool // whether newline terminates scan + nlIsSpace bool // whether newline counts as white space + argLimit int // max value of ss.count for this arg; argLimit <= limit + limit int // max value of ss.count. + maxWid int // width of this arg. +} + +// The Read method is only in ScanState so that ScanState +// satisfies io.Reader. It will never be called when used as +// intended, so there is no need to make it actually work. +func (s *ss) Read(buf []byte) (n int, err error) { + return 0, errors.New("ScanState's Read should not be called. Use ReadRune") +} + +func (s *ss) ReadRune() (r rune, size int, err error) { + if s.atEOF || s.count >= s.argLimit { + err = io.EOF + return + } + + r, size, err = s.rs.ReadRune() + if err == nil { + s.count++ + if s.nlIsEnd && r == '\n' { + s.atEOF = true + } + } else if err == io.EOF { + s.atEOF = true + } + return +} + +func (s *ss) Width() (wid int, ok bool) { + if s.maxWid == hugeWid { + return 0, false + } + return s.maxWid, true +} + +// The public method returns an error; this private one panics. +// If getRune reaches EOF, the return value is EOF (-1). +func (s *ss) getRune() (r rune) { + r, _, err := s.ReadRune() + if err != nil { + if err == io.EOF { + return eof + } + s.error(err) + } + return +} + +// mustReadRune turns io.EOF into a panic(io.ErrUnexpectedEOF). +// It is called in cases such as string scanning where an EOF is a +// syntax error. +func (s *ss) mustReadRune() (r rune) { + r = s.getRune() + if r == eof { + s.error(io.ErrUnexpectedEOF) + } + return +} + +func (s *ss) UnreadRune() error { + s.rs.UnreadRune() + s.atEOF = false + s.count-- + return nil +} + +func (s *ss) error(err error) { + panic(scanError{err}) +} + +func (s *ss) errorString(err string) { + panic(scanError{errors.New(err)}) +} + +func (s *ss) Token(skipSpace bool, f func(rune) bool) (tok []byte, err error) { + defer func() { + if e := recover(); e != nil { + if se, ok := e.(scanError); ok { + err = se.err + } else { + panic(e) + } + } + }() + if f == nil { + f = notSpace + } + s.buf = s.buf[:0] + tok = s.token(skipSpace, f) + return +} + +// space is a copy of the unicode.White_Space ranges, +// to avoid depending on package unicode. +var space = [][2]uint16{ + {0x0009, 0x000d}, + {0x0020, 0x0020}, + {0x0085, 0x0085}, + {0x00a0, 0x00a0}, + {0x1680, 0x1680}, + {0x2000, 0x200a}, + {0x2028, 0x2029}, + {0x202f, 0x202f}, + {0x205f, 0x205f}, + {0x3000, 0x3000}, +} + +func isSpace(r rune) bool { + if r >= 1<<16 { + return false + } + rx := uint16(r) + for _, rng := range space { + if rx < rng[0] { + return false + } + if rx <= rng[1] { + return true + } + } + return false +} + +// notSpace is the default scanning function used in Token. +func notSpace(r rune) bool { + return !isSpace(r) +} + +// readRune is a structure to enable reading UTF-8 encoded code points +// from an io.Reader. It is used if the Reader given to the scanner does +// not already implement io.RuneScanner. +type readRune struct { + reader io.Reader + buf [utf8.UTFMax]byte // used only inside ReadRune + pending int // number of bytes in pendBuf; only >0 for bad UTF-8 + pendBuf [utf8.UTFMax]byte // bytes left over + peekRune rune // if >=0 next rune; when <0 is ^(previous Rune) +} + +// readByte returns the next byte from the input, which may be +// left over from a previous read if the UTF-8 was ill-formed. +func (r *readRune) readByte() (b byte, err error) { + if r.pending > 0 { + b = r.pendBuf[0] + copy(r.pendBuf[0:], r.pendBuf[1:]) + r.pending-- + return + } + n, err := io.ReadFull(r.reader, r.pendBuf[:1]) + if n != 1 { + return 0, err + } + return r.pendBuf[0], err +} + +// ReadRune returns the next UTF-8 encoded code point from the +// io.Reader inside r. +func (r *readRune) ReadRune() (rr rune, size int, err error) { + if r.peekRune >= 0 { + rr = r.peekRune + r.peekRune = ^r.peekRune + size = utf8.RuneLen(rr) + return + } + r.buf[0], err = r.readByte() + if err != nil { + return + } + if r.buf[0] < utf8.RuneSelf { // fast check for common ASCII case + rr = rune(r.buf[0]) + size = 1 // Known to be 1. + // Flip the bits of the rune so it's available to UnreadRune. + r.peekRune = ^rr + return + } + var n int + for n = 1; !utf8.FullRune(r.buf[:n]); n++ { + r.buf[n], err = r.readByte() + if err != nil { + if err == io.EOF { + err = nil + break + } + return + } + } + rr, size = utf8.DecodeRune(r.buf[:n]) + if size < n { // an error, save the bytes for the next read + copy(r.pendBuf[r.pending:], r.buf[size:n]) + r.pending += n - size + } + // Flip the bits of the rune so it's available to UnreadRune. + r.peekRune = ^rr + return +} + +func (r *readRune) UnreadRune() error { + if r.peekRune >= 0 { + return errors.New("fmt: scanning called UnreadRune with no rune available") + } + // Reverse bit flip of previously read rune to obtain valid >=0 state. + r.peekRune = ^r.peekRune + return nil +} + +var ssFree = sync.Pool{ + New: func() any { return new(ss) }, +} + +// newScanState allocates a new ss struct or grab a cached one. +func newScanState(r io.Reader, nlIsSpace, nlIsEnd bool) (s *ss, old ssave) { + s = ssFree.Get().(*ss) + if rs, ok := r.(io.RuneScanner); ok { + s.rs = rs + } else { + s.rs = &readRune{reader: r, peekRune: -1} + } + s.nlIsSpace = nlIsSpace + s.nlIsEnd = nlIsEnd + s.atEOF = false + s.limit = hugeWid + s.argLimit = hugeWid + s.maxWid = hugeWid + s.validSave = true + s.count = 0 + return +} + +// free saves used ss structs in ssFree; avoid an allocation per invocation. +func (s *ss) free(old ssave) { + // If it was used recursively, just restore the old state. + if old.validSave { + s.ssave = old + return + } + // Don't hold on to ss structs with large buffers. + if cap(s.buf) > 1024 { + return + } + s.buf = s.buf[:0] + s.rs = nil + ssFree.Put(s) +} + +// SkipSpace provides Scan methods the ability to skip space and newline +// characters in keeping with the current scanning mode set by format strings +// and [Scan]/[Scanln]. +func (s *ss) SkipSpace() { + for { + r := s.getRune() + if r == eof { + return + } + if r == '\r' && s.peek("\n") { + continue + } + if r == '\n' { + if s.nlIsSpace { + continue + } + s.errorString("unexpected newline") + return + } + if !isSpace(r) { + s.UnreadRune() + break + } + } +} + +// token returns the next space-delimited string from the input. It +// skips white space. For Scanln, it stops at newlines. For Scan, +// newlines are treated as spaces. +func (s *ss) token(skipSpace bool, f func(rune) bool) []byte { + if skipSpace { + s.SkipSpace() + } + // read until white space or newline + for { + r := s.getRune() + if r == eof { + break + } + if !f(r) { + s.UnreadRune() + break + } + s.buf.writeRune(r) + } + return s.buf +} + +var errComplex = errors.New("syntax error scanning complex number") +var errBool = errors.New("syntax error scanning boolean") + +func indexRune(s string, r rune) int { + for i, c := range s { + if c == r { + return i + } + } + return -1 +} + +// consume reads the next rune in the input and reports whether it is in the ok string. +// If accept is true, it puts the character into the input token. +func (s *ss) consume(ok string, accept bool) bool { + r := s.getRune() + if r == eof { + return false + } + if indexRune(ok, r) >= 0 { + if accept { + s.buf.writeRune(r) + } + return true + } + if r != eof && accept { + s.UnreadRune() + } + return false +} + +// peek reports whether the next character is in the ok string, without consuming it. +func (s *ss) peek(ok string) bool { + r := s.getRune() + if r != eof { + s.UnreadRune() + } + return indexRune(ok, r) >= 0 +} + +func (s *ss) notEOF() { + // Guarantee there is data to be read. + if r := s.getRune(); r == eof { + panic(io.EOF) + } + s.UnreadRune() +} + +// accept checks the next rune in the input. If it's a byte (sic) in the string, it puts it in the +// buffer and returns true. Otherwise it return false. +func (s *ss) accept(ok string) bool { + return s.consume(ok, true) +} + +// okVerb verifies that the verb is present in the list, setting s.err appropriately if not. +func (s *ss) okVerb(verb rune, okVerbs, typ string) bool { + for _, v := range okVerbs { + if v == verb { + return true + } + } + s.errorString("bad verb '%" + string(verb) + "' for " + typ) + return false +} + +// scanBool returns the value of the boolean represented by the next token. +func (s *ss) scanBool(verb rune) bool { + s.SkipSpace() + s.notEOF() + if !s.okVerb(verb, "tv", "boolean") { + return false + } + // Syntax-checking a boolean is annoying. We're not fastidious about case. + switch s.getRune() { + case '0': + return false + case '1': + return true + case 't', 'T': + if s.accept("rR") && (!s.accept("uU") || !s.accept("eE")) { + s.error(errBool) + } + return true + case 'f', 'F': + if s.accept("aA") && (!s.accept("lL") || !s.accept("sS") || !s.accept("eE")) { + s.error(errBool) + } + return false + } + return false +} + +// Numerical elements +const ( + binaryDigits = "01" + octalDigits = "01234567" + decimalDigits = "0123456789" + hexadecimalDigits = "0123456789aAbBcCdDeEfF" + sign = "+-" + period = "." + exponent = "eEpP" +) + +// getBase returns the numeric base represented by the verb and its digit string. +func (s *ss) getBase(verb rune) (base int, digits string) { + s.okVerb(verb, "bdoUxXv", "integer") // sets s.err + base = 10 + digits = decimalDigits + switch verb { + case 'b': + base = 2 + digits = binaryDigits + case 'o': + base = 8 + digits = octalDigits + case 'x', 'X', 'U': + base = 16 + digits = hexadecimalDigits + } + return +} + +// scanNumber returns the numerical string with specified digits starting here. +func (s *ss) scanNumber(digits string, haveDigits bool) string { + if !haveDigits { + s.notEOF() + if !s.accept(digits) { + s.errorString("expected integer") + } + } + for s.accept(digits) { + } + return string(s.buf) +} + +// scanRune returns the next rune value in the input. +func (s *ss) scanRune(bitSize int) int64 { + s.notEOF() + r := s.getRune() + n := uint(bitSize) + x := (int64(r) << (64 - n)) >> (64 - n) + if x != int64(r) { + s.errorString("overflow on character value " + string(r)) + } + return int64(r) +} + +// scanBasePrefix reports whether the integer begins with a base prefix +// and returns the base, digit string, and whether a zero was found. +// It is called only if the verb is %v. +func (s *ss) scanBasePrefix() (base int, digits string, zeroFound bool) { + if !s.peek("0") { + return 0, decimalDigits + "_", false + } + s.accept("0") + // Special cases for 0, 0b, 0o, 0x. + switch { + case s.peek("bB"): + s.consume("bB", true) + return 0, binaryDigits + "_", true + case s.peek("oO"): + s.consume("oO", true) + return 0, octalDigits + "_", true + case s.peek("xX"): + s.consume("xX", true) + return 0, hexadecimalDigits + "_", true + default: + return 0, octalDigits + "_", true + } +} + +// scanInt returns the value of the integer represented by the next +// token, checking for overflow. Any error is stored in s.err. +func (s *ss) scanInt(verb rune, bitSize int) int64 { + if verb == 'c' { + return s.scanRune(bitSize) + } + s.SkipSpace() + s.notEOF() + base, digits := s.getBase(verb) + haveDigits := false + if verb == 'U' { + if !s.consume("U", false) || !s.consume("+", false) { + s.errorString("bad unicode format ") + } + } else { + s.accept(sign) // If there's a sign, it will be left in the token buffer. + if verb == 'v' { + base, digits, haveDigits = s.scanBasePrefix() + } + } + tok := s.scanNumber(digits, haveDigits) + i, err := strconv.ParseInt(tok, base, 64) + if err != nil { + s.error(err) + } + n := uint(bitSize) + x := (i << (64 - n)) >> (64 - n) + if x != i { + s.errorString("integer overflow on token " + tok) + } + return i +} + +// scanUint returns the value of the unsigned integer represented +// by the next token, checking for overflow. Any error is stored in s.err. +func (s *ss) scanUint(verb rune, bitSize int) uint64 { + if verb == 'c' { + return uint64(s.scanRune(bitSize)) + } + s.SkipSpace() + s.notEOF() + base, digits := s.getBase(verb) + haveDigits := false + if verb == 'U' { + if !s.consume("U", false) || !s.consume("+", false) { + s.errorString("bad unicode format ") + } + } else if verb == 'v' { + base, digits, haveDigits = s.scanBasePrefix() + } + tok := s.scanNumber(digits, haveDigits) + i, err := strconv.ParseUint(tok, base, 64) + if err != nil { + s.error(err) + } + n := uint(bitSize) + x := (i << (64 - n)) >> (64 - n) + if x != i { + s.errorString("unsigned integer overflow on token " + tok) + } + return i +} + +// floatToken returns the floating-point number starting here, no longer than swid +// if the width is specified. It's not rigorous about syntax because it doesn't check that +// we have at least some digits, but Atof will do that. +func (s *ss) floatToken() string { + s.buf = s.buf[:0] + // NaN? + if s.accept("nN") && s.accept("aA") && s.accept("nN") { + return string(s.buf) + } + // leading sign? + s.accept(sign) + // Inf? + if s.accept("iI") && s.accept("nN") && s.accept("fF") { + return string(s.buf) + } + digits := decimalDigits + "_" + exp := exponent + if s.accept("0") && s.accept("xX") { + digits = hexadecimalDigits + "_" + exp = "pP" + } + // digits? + for s.accept(digits) { + } + // decimal point? + if s.accept(period) { + // fraction? + for s.accept(digits) { + } + } + // exponent? + if s.accept(exp) { + // leading sign? + s.accept(sign) + // digits? + for s.accept(decimalDigits + "_") { + } + } + return string(s.buf) +} + +// complexTokens returns the real and imaginary parts of the complex number starting here. +// The number might be parenthesized and has the format (N+Ni) where N is a floating-point +// number and there are no spaces within. +func (s *ss) complexTokens() (real, imag string) { + // TODO: accept N and Ni independently? + parens := s.accept("(") + real = s.floatToken() + s.buf = s.buf[:0] + // Must now have a sign. + if !s.accept("+-") { + s.error(errComplex) + } + // Sign is now in buffer + imagSign := string(s.buf) + imag = s.floatToken() + if !s.accept("i") { + s.error(errComplex) + } + if parens && !s.accept(")") { + s.error(errComplex) + } + return real, imagSign + imag +} + +func hasX(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] == 'x' || s[i] == 'X' { + return true + } + } + return false +} + +// convertFloat converts the string to a float64value. +func (s *ss) convertFloat(str string, n int) float64 { + // strconv.ParseFloat will handle "+0x1.fp+2", + // but we have to implement our non-standard + // decimal+binary exponent mix (1.2p4) ourselves. + if p := indexRune(str, 'p'); p >= 0 && !hasX(str) { + // Atof doesn't handle power-of-2 exponents, + // but they're easy to evaluate. + f, err := strconv.ParseFloat(str[:p], n) + if err != nil { + // Put full string into error. + if e, ok := err.(*strconv.NumError); ok { + e.Num = str + } + s.error(err) + } + m, err := strconv.Atoi(str[p+1:]) + if err != nil { + // Put full string into error. + if e, ok := err.(*strconv.NumError); ok { + e.Num = str + } + s.error(err) + } + return math.Ldexp(f, m) + } + f, err := strconv.ParseFloat(str, n) + if err != nil { + s.error(err) + } + return f +} + +// scanComplex converts the next token to a complex128 value. +// The atof argument is a type-specific reader for the underlying type. +// If we're reading complex64, atof will parse float32s and convert them +// to float64's to avoid reproducing this code for each complex type. +func (s *ss) scanComplex(verb rune, n int) complex128 { + if !s.okVerb(verb, floatVerbs, "complex") { + return 0 + } + s.SkipSpace() + s.notEOF() + sreal, simag := s.complexTokens() + real := s.convertFloat(sreal, n/2) + imag := s.convertFloat(simag, n/2) + return complex(real, imag) +} + +// convertString returns the string represented by the next input characters. +// The format of the input is determined by the verb. +func (s *ss) convertString(verb rune) (str string) { + if !s.okVerb(verb, "svqxX", "string") { + return "" + } + s.SkipSpace() + s.notEOF() + switch verb { + case 'q': + str = s.quotedString() + case 'x', 'X': + str = s.hexString() + default: + str = string(s.token(true, notSpace)) // %s and %v just return the next word + } + return +} + +// quotedString returns the double- or back-quoted string represented by the next input characters. +func (s *ss) quotedString() string { + s.notEOF() + quote := s.getRune() + switch quote { + case '`': + // Back-quoted: Anything goes until EOF or back quote. + for { + r := s.mustReadRune() + if r == quote { + break + } + s.buf.writeRune(r) + } + return string(s.buf) + case '"': + // Double-quoted: Include the quotes and let strconv.Unquote do the backslash escapes. + s.buf.writeByte('"') + for { + r := s.mustReadRune() + s.buf.writeRune(r) + if r == '\\' { + // In a legal backslash escape, no matter how long, only the character + // immediately after the escape can itself be a backslash or quote. + // Thus we only need to protect the first character after the backslash. + s.buf.writeRune(s.mustReadRune()) + } else if r == '"' { + break + } + } + result, err := strconv.Unquote(string(s.buf)) + if err != nil { + s.error(err) + } + return result + default: + s.errorString("expected quoted string") + } + return "" +} + +// hexDigit returns the value of the hexadecimal digit. +func hexDigit(d rune) (int, bool) { + digit := int(d) + switch digit { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return digit - '0', true + case 'a', 'b', 'c', 'd', 'e', 'f': + return 10 + digit - 'a', true + case 'A', 'B', 'C', 'D', 'E', 'F': + return 10 + digit - 'A', true + } + return -1, false +} + +// hexByte returns the next hex-encoded (two-character) byte from the input. +// It returns ok==false if the next bytes in the input do not encode a hex byte. +// If the first byte is hex and the second is not, processing stops. +func (s *ss) hexByte() (b byte, ok bool) { + rune1 := s.getRune() + if rune1 == eof { + return + } + value1, ok := hexDigit(rune1) + if !ok { + s.UnreadRune() + return + } + value2, ok := hexDigit(s.mustReadRune()) + if !ok { + s.errorString("illegal hex digit") + return + } + return byte(value1<<4 | value2), true +} + +// hexString returns the space-delimited hexpair-encoded string. +func (s *ss) hexString() string { + s.notEOF() + for { + b, ok := s.hexByte() + if !ok { + break + } + s.buf.writeByte(b) + } + if len(s.buf) == 0 { + s.errorString("no hex data for %x string") + return "" + } + return string(s.buf) +} + +const ( + floatVerbs = "beEfFgGv" + + hugeWid = 1 << 30 + + intBits = 32 << (^uint(0) >> 63) + uintptrBits = 32 << (^uintptr(0) >> 63) +) + +// scanPercent scans a literal percent character. +func (s *ss) scanPercent() { + s.SkipSpace() + s.notEOF() + if !s.accept("%") { + s.errorString("missing literal %") + } +} + +// scanOne scans a single value, deriving the scanner from the type of the argument. +func (s *ss) scanOne(verb rune, arg any) { + s.buf = s.buf[:0] + var err error + // If the parameter has its own Scan method, use that. + if v, ok := arg.(Scanner); ok { + err = v.Scan(s, verb) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + s.error(err) + } + return + } + + switch v := arg.(type) { + case *bool: + *v = s.scanBool(verb) + case *complex64: + *v = complex64(s.scanComplex(verb, 64)) + case *complex128: + *v = s.scanComplex(verb, 128) + case *int: + *v = int(s.scanInt(verb, intBits)) + case *int8: + *v = int8(s.scanInt(verb, 8)) + case *int16: + *v = int16(s.scanInt(verb, 16)) + case *int32: + *v = int32(s.scanInt(verb, 32)) + case *int64: + *v = s.scanInt(verb, 64) + case *uint: + *v = uint(s.scanUint(verb, intBits)) + case *uint8: + *v = uint8(s.scanUint(verb, 8)) + case *uint16: + *v = uint16(s.scanUint(verb, 16)) + case *uint32: + *v = uint32(s.scanUint(verb, 32)) + case *uint64: + *v = s.scanUint(verb, 64) + case *uintptr: + *v = uintptr(s.scanUint(verb, uintptrBits)) + // Floats are tricky because you want to scan in the precision of the result, not + // scan in high precision and convert, in order to preserve the correct error condition. + case *float32: + if s.okVerb(verb, floatVerbs, "float32") { + s.SkipSpace() + s.notEOF() + *v = float32(s.convertFloat(s.floatToken(), 32)) + } + case *float64: + if s.okVerb(verb, floatVerbs, "float64") { + s.SkipSpace() + s.notEOF() + *v = s.convertFloat(s.floatToken(), 64) + } + case *string: + *v = s.convertString(verb) + case *[]byte: + // We scan to string and convert so we get a copy of the data. + // If we scanned to bytes, the slice would point at the buffer. + *v = []byte(s.convertString(verb)) + default: + val := reflect.ValueOf(v) + ptr := val + if ptr.Kind() != reflect.Pointer { + s.errorString("type not a pointer: " + val.Type().String()) + return + } + switch v := ptr.Elem(); v.Kind() { + case reflect.Bool: + v.SetBool(s.scanBool(verb)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v.SetInt(s.scanInt(verb, v.Type().Bits())) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + v.SetUint(s.scanUint(verb, v.Type().Bits())) + case reflect.String: + v.SetString(s.convertString(verb)) + case reflect.Slice: + // For now, can only handle (renamed) []byte. + typ := v.Type() + if typ.Elem().Kind() != reflect.Uint8 { + s.errorString("can't scan type: " + val.Type().String()) + } + str := s.convertString(verb) + v.Set(reflect.MakeSlice(typ, len(str), len(str))) + for i := 0; i < len(str); i++ { + v.Index(i).SetUint(uint64(str[i])) + } + case reflect.Float32, reflect.Float64: + s.SkipSpace() + s.notEOF() + v.SetFloat(s.convertFloat(s.floatToken(), v.Type().Bits())) + case reflect.Complex64, reflect.Complex128: + v.SetComplex(s.scanComplex(verb, v.Type().Bits())) + default: + s.errorString("can't scan type: " + val.Type().String()) + } + } +} + +// errorHandler turns local panics into error returns. +func errorHandler(errp *error) { + if e := recover(); e != nil { + if se, ok := e.(scanError); ok { // catch local error + *errp = se.err + } else if eof, ok := e.(error); ok && eof == io.EOF { // out of input + *errp = eof + } else { + panic(e) + } + } +} + +// doScan does the real work for scanning without a format string. +func (s *ss) doScan(a []any) (numProcessed int, err error) { + defer errorHandler(&err) + for _, arg := range a { + s.scanOne('v', arg) + numProcessed++ + } + // Check for newline (or EOF) if required (Scanln etc.). + if s.nlIsEnd { + for { + r := s.getRune() + if r == '\n' || r == eof { + break + } + if !isSpace(r) { + s.errorString("expected newline") + break + } + } + } + return +} + +// advance determines whether the next characters in the input match +// those of the format. It returns the number of bytes (sic) consumed +// in the format. All runs of space characters in either input or +// format behave as a single space. Newlines are special, though: +// newlines in the format must match those in the input and vice versa. +// This routine also handles the %% case. If the return value is zero, +// either format starts with a % (with no following %) or the input +// is empty. If it is negative, the input did not match the string. +func (s *ss) advance(format string) (i int) { + for i < len(format) { + fmtc, w := utf8.DecodeRuneInString(format[i:]) + + // Space processing. + // In the rest of this comment "space" means spaces other than newline. + // Newline in the format matches input of zero or more spaces and then newline or end-of-input. + // Spaces in the format before the newline are collapsed into the newline. + // Spaces in the format after the newline match zero or more spaces after the corresponding input newline. + // Other spaces in the format match input of one or more spaces or end-of-input. + if isSpace(fmtc) { + newlines := 0 + trailingSpace := false + for isSpace(fmtc) && i < len(format) { + if fmtc == '\n' { + newlines++ + trailingSpace = false + } else { + trailingSpace = true + } + i += w + fmtc, w = utf8.DecodeRuneInString(format[i:]) + } + for j := 0; j < newlines; j++ { + inputc := s.getRune() + for isSpace(inputc) && inputc != '\n' { + inputc = s.getRune() + } + if inputc != '\n' && inputc != eof { + s.errorString("newline in format does not match input") + } + } + if trailingSpace { + inputc := s.getRune() + if newlines == 0 { + // If the trailing space stood alone (did not follow a newline), + // it must find at least one space to consume. + if !isSpace(inputc) && inputc != eof { + s.errorString("expected space in input to match format") + } + if inputc == '\n' { + s.errorString("newline in input does not match format") + } + } + for isSpace(inputc) && inputc != '\n' { + inputc = s.getRune() + } + if inputc != eof { + s.UnreadRune() + } + } + continue + } + + // Verbs. + if fmtc == '%' { + // % at end of string is an error. + if i+w == len(format) { + s.errorString("missing verb: % at end of format string") + } + // %% acts like a real percent + nextc, _ := utf8.DecodeRuneInString(format[i+w:]) // will not match % if string is empty + if nextc != '%' { + return + } + i += w // skip the first % + } + + // Literals. + inputc := s.mustReadRune() + if fmtc != inputc { + s.UnreadRune() + return -1 + } + i += w + } + return +} + +// doScanf does the real work when scanning with a format string. +// At the moment, it handles only pointers to basic types. +func (s *ss) doScanf(format string, a []any) (numProcessed int, err error) { + defer errorHandler(&err) + end := len(format) - 1 + // We process one item per non-trivial format + for i := 0; i <= end; { + w := s.advance(format[i:]) + if w > 0 { + i += w + continue + } + // Either we failed to advance, we have a percent character, or we ran out of input. + if format[i] != '%' { + // Can't advance format. Why not? + if w < 0 { + s.errorString("input does not match format") + } + // Otherwise at EOF; "too many operands" error handled below + break + } + i++ // % is one byte + + // do we have 20 (width)? + var widPresent bool + s.maxWid, widPresent, i = parsenum(format, i, end) + if !widPresent { + s.maxWid = hugeWid + } + + c, w := utf8.DecodeRuneInString(format[i:]) + i += w + + if c != 'c' { + s.SkipSpace() + } + if c == '%' { + s.scanPercent() + continue // Do not consume an argument. + } + s.argLimit = s.limit + if f := s.count + s.maxWid; f < s.argLimit { + s.argLimit = f + } + + if numProcessed >= len(a) { // out of operands + s.errorString("too few operands for format '%" + format[i-w:] + "'") + break + } + arg := a[numProcessed] + + s.scanOne(c, arg) + numProcessed++ + s.argLimit = s.limit + } + if numProcessed < len(a) { + s.errorString("too many operands") + } + return +} diff --git a/go/src/fmt/scan_test.go b/go/src/fmt/scan_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ff9e4f30ca8c873f89457c4f8fa2fcf62453a9a6 --- /dev/null +++ b/go/src/fmt/scan_test.go @@ -0,0 +1,1334 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + "bufio" + "bytes" + "errors" + . "fmt" + "io" + "math" + "reflect" + "regexp" + "strings" + "testing" + "testing/iotest" + "unicode/utf8" +) + +type ScanTest struct { + text string + in any + out any +} + +type ScanfTest struct { + format string + text string + in any + out any +} + +type ScanfMultiTest struct { + format string + text string + in []any + out []any + err string +} + +var ( + boolVal bool + intVal int + int8Val int8 + int16Val int16 + int32Val int32 + int64Val int64 + uintVal uint + uint8Val uint8 + uint16Val uint16 + uint32Val uint32 + uint64Val uint64 + uintptrVal uintptr + float32Val float32 + float64Val float64 + stringVal string + bytesVal []byte + runeVal rune + complex64Val complex64 + complex128Val complex128 + renamedBoolVal renamedBool + renamedIntVal renamedInt + renamedInt8Val renamedInt8 + renamedInt16Val renamedInt16 + renamedInt32Val renamedInt32 + renamedInt64Val renamedInt64 + renamedUintVal renamedUint + renamedUint8Val renamedUint8 + renamedUint16Val renamedUint16 + renamedUint32Val renamedUint32 + renamedUint64Val renamedUint64 + renamedUintptrVal renamedUintptr + renamedStringVal renamedString + renamedBytesVal renamedBytes + renamedFloat32Val renamedFloat32 + renamedFloat64Val renamedFloat64 + renamedComplex64Val renamedComplex64 + renamedComplex128Val renamedComplex128 +) + +// Xs accepts any non-empty run of the verb character +type Xs string + +func (x *Xs) Scan(state ScanState, verb rune) error { + tok, err := state.Token(true, func(r rune) bool { return r == verb }) + if err != nil { + return err + } + s := string(tok) + if !regexp.MustCompile("^" + string(verb) + "+$").MatchString(s) { + return errors.New("syntax error for xs") + } + *x = Xs(s) + return nil +} + +var xVal Xs + +// IntString accepts an integer followed immediately by a string. +// It tests the embedding of a scan within a scan. +type IntString struct { + i int + s string +} + +func (s *IntString) Scan(state ScanState, verb rune) error { + if _, err := Fscan(state, &s.i); err != nil { + return err + } + + tok, err := state.Token(true, nil) + if err != nil { + return err + } + s.s = string(tok) + return nil +} + +var intStringVal IntString + +var scanTests = []ScanTest{ + // Basic types + {"T\n", &boolVal, true}, // boolean test vals toggle to be sure they are written + {"F\n", &boolVal, false}, // restored to zero value + {"21\n", &intVal, 21}, + {"2_1\n", &intVal, 21}, + {"0\n", &intVal, 0}, + {"000\n", &intVal, 0}, + {"0x10\n", &intVal, 0x10}, + {"0x_1_0\n", &intVal, 0x10}, + {"-0x10\n", &intVal, -0x10}, + {"0377\n", &intVal, 0377}, + {"0_3_7_7\n", &intVal, 0377}, + {"0o377\n", &intVal, 0377}, + {"0o_3_7_7\n", &intVal, 0377}, + {"-0377\n", &intVal, -0377}, + {"-0o377\n", &intVal, -0377}, + {"0\n", &uintVal, uint(0)}, + {"000\n", &uintVal, uint(0)}, + {"0x10\n", &uintVal, uint(0x10)}, + {"0377\n", &uintVal, uint(0377)}, + {"22\n", &int8Val, int8(22)}, + {"23\n", &int16Val, int16(23)}, + {"24\n", &int32Val, int32(24)}, + {"25\n", &int64Val, int64(25)}, + {"127\n", &int8Val, int8(127)}, + {"-21\n", &intVal, -21}, + {"-22\n", &int8Val, int8(-22)}, + {"-23\n", &int16Val, int16(-23)}, + {"-24\n", &int32Val, int32(-24)}, + {"-25\n", &int64Val, int64(-25)}, + {"-128\n", &int8Val, int8(-128)}, + {"+21\n", &intVal, +21}, + {"+22\n", &int8Val, int8(+22)}, + {"+23\n", &int16Val, int16(+23)}, + {"+24\n", &int32Val, int32(+24)}, + {"+25\n", &int64Val, int64(+25)}, + {"+127\n", &int8Val, int8(+127)}, + {"26\n", &uintVal, uint(26)}, + {"27\n", &uint8Val, uint8(27)}, + {"28\n", &uint16Val, uint16(28)}, + {"29\n", &uint32Val, uint32(29)}, + {"30\n", &uint64Val, uint64(30)}, + {"31\n", &uintptrVal, uintptr(31)}, + {"255\n", &uint8Val, uint8(255)}, + {"32767\n", &int16Val, int16(32767)}, + {"2.3\n", &float64Val, 2.3}, + {"2.3e1\n", &float32Val, float32(2.3e1)}, + {"2.3e2\n", &float64Val, 2.3e2}, + {"2.3p2\n", &float64Val, 2.3 * 4}, + {"2.3p+2\n", &float64Val, 2.3 * 4}, + {"2.3p+66\n", &float64Val, 2.3 * (1 << 66)}, + {"2.3p-66\n", &float64Val, 2.3 / (1 << 66)}, + {"0x2.3p-66\n", &float64Val, float64(0x23) / (1 << 70)}, + {"2_3.4_5\n", &float64Val, 23.45}, + {"2.35\n", &stringVal, "2.35"}, + {"2345678\n", &bytesVal, []byte("2345678")}, + {"(3.4e1-2i)\n", &complex128Val, 3.4e1 - 2i}, + {"-3.45e1-3i\n", &complex64Val, complex64(-3.45e1 - 3i)}, + {"-.45e1-1e2i\n", &complex128Val, complex128(-.45e1 - 100i)}, + {"-.4_5e1-1E2i\n", &complex128Val, complex128(-.45e1 - 100i)}, + {"0x1.0p1+0x1.0P2i\n", &complex128Val, complex128(2 + 4i)}, + {"-0x1p1-0x1p2i\n", &complex128Val, complex128(-2 - 4i)}, + {"-0x1ep-1-0x1p2i\n", &complex128Val, complex128(-15 - 4i)}, + {"-0x1_Ep-1-0x1p0_2i\n", &complex128Val, complex128(-15 - 4i)}, + {"hello\n", &stringVal, "hello"}, + + // Carriage-return followed by newline. (We treat \r\n as \n always.) + {"hello\r\n", &stringVal, "hello"}, + {"27\r\n", &uint8Val, uint8(27)}, + + // Renamed types + {"true\n", &renamedBoolVal, renamedBool(true)}, + {"F\n", &renamedBoolVal, renamedBool(false)}, + {"101\n", &renamedIntVal, renamedInt(101)}, + {"102\n", &renamedIntVal, renamedInt(102)}, + {"103\n", &renamedUintVal, renamedUint(103)}, + {"104\n", &renamedUintVal, renamedUint(104)}, + {"105\n", &renamedInt8Val, renamedInt8(105)}, + {"106\n", &renamedInt16Val, renamedInt16(106)}, + {"107\n", &renamedInt32Val, renamedInt32(107)}, + {"108\n", &renamedInt64Val, renamedInt64(108)}, + {"109\n", &renamedUint8Val, renamedUint8(109)}, + {"110\n", &renamedUint16Val, renamedUint16(110)}, + {"111\n", &renamedUint32Val, renamedUint32(111)}, + {"112\n", &renamedUint64Val, renamedUint64(112)}, + {"113\n", &renamedUintptrVal, renamedUintptr(113)}, + {"114\n", &renamedStringVal, renamedString("114")}, + {"115\n", &renamedBytesVal, renamedBytes([]byte("115"))}, + + // Custom scanners. + {" vvv ", &xVal, Xs("vvv")}, + {" 1234hello", &intStringVal, IntString{1234, "hello"}}, + + // Fixed bugs + {"2147483648\n", &int64Val, int64(2147483648)}, // was: integer overflow +} + +var scanfTests = []ScanfTest{ + {"%v", "TRUE\n", &boolVal, true}, + {"%t", "false\n", &boolVal, false}, + {"%v", "-71\n", &intVal, -71}, + {"%v", "-7_1\n", &intVal, -71}, + {"%v", "0b111\n", &intVal, 7}, + {"%v", "0b_1_1_1\n", &intVal, 7}, + {"%v", "0377\n", &intVal, 0377}, + {"%v", "0_3_7_7\n", &intVal, 0377}, + {"%v", "0o377\n", &intVal, 0377}, + {"%v", "0o_3_7_7\n", &intVal, 0377}, + {"%v", "0x44\n", &intVal, 0x44}, + {"%v", "0x_4_4\n", &intVal, 0x44}, + {"%d", "72\n", &intVal, 72}, + {"%c", "a\n", &runeVal, 'a'}, + {"%c", "\u5072\n", &runeVal, '\u5072'}, + {"%c", "\u1234\n", &runeVal, '\u1234'}, + {"%d", "73\n", &int8Val, int8(73)}, + {"%d", "+74\n", &int16Val, int16(74)}, + {"%d", "75\n", &int32Val, int32(75)}, + {"%d", "76\n", &int64Val, int64(76)}, + {"%b", "1001001\n", &intVal, 73}, + {"%o", "075\n", &intVal, 075}, + {"%x", "a75\n", &intVal, 0xa75}, + {"%v", "71\n", &uintVal, uint(71)}, + {"%d", "72\n", &uintVal, uint(72)}, + {"%d", "7_2\n", &uintVal, uint(7)}, // only %v takes underscores + {"%d", "73\n", &uint8Val, uint8(73)}, + {"%d", "74\n", &uint16Val, uint16(74)}, + {"%d", "75\n", &uint32Val, uint32(75)}, + {"%d", "76\n", &uint64Val, uint64(76)}, + {"%d", "77\n", &uintptrVal, uintptr(77)}, + {"%b", "1001001\n", &uintVal, uint(73)}, + {"%b", "100_1001\n", &uintVal, uint(4)}, + {"%o", "075\n", &uintVal, uint(075)}, + {"%o", "07_5\n", &uintVal, uint(07)}, // only %v takes underscores + {"%x", "a75\n", &uintVal, uint(0xa75)}, + {"%x", "A75\n", &uintVal, uint(0xa75)}, + {"%x", "A7_5\n", &uintVal, uint(0xa7)}, // only %v takes underscores + {"%U", "U+1234\n", &intVal, int(0x1234)}, + {"%U", "U+4567\n", &uintVal, uint(0x4567)}, + + {"%e", "2.3\n", &float64Val, 2.3}, + {"%E", "2.3e1\n", &float32Val, float32(2.3e1)}, + {"%f", "2.3e2\n", &float64Val, 2.3e2}, + {"%g", "2.3p2\n", &float64Val, 2.3 * 4}, + {"%G", "2.3p+2\n", &float64Val, 2.3 * 4}, + {"%v", "2.3p+66\n", &float64Val, 2.3 * (1 << 66)}, + {"%f", "2.3p-66\n", &float64Val, 2.3 / (1 << 66)}, + {"%G", "0x2.3p-66\n", &float64Val, float64(0x23) / (1 << 70)}, + {"%E", "2_3.4_5\n", &float64Val, 23.45}, + + // Strings + {"%s", "using-%s\n", &stringVal, "using-%s"}, + {"%x", "7573696e672d2578\n", &stringVal, "using-%x"}, + {"%X", "7573696E672D2558\n", &stringVal, "using-%X"}, + {"%q", `"quoted\twith\\do\u0075bl\x65s"` + "\n", &stringVal, "quoted\twith\\doubles"}, + {"%q", "`quoted with backs`\n", &stringVal, "quoted with backs"}, + + // Byte slices + {"%s", "bytes-%s\n", &bytesVal, []byte("bytes-%s")}, + {"%x", "62797465732d2578\n", &bytesVal, []byte("bytes-%x")}, + {"%X", "62797465732D2558\n", &bytesVal, []byte("bytes-%X")}, + {"%q", `"bytes\rwith\vdo\u0075bl\x65s"` + "\n", &bytesVal, []byte("bytes\rwith\vdoubles")}, + {"%q", "`bytes with backs`\n", &bytesVal, []byte("bytes with backs")}, + + // Renamed types + {"%v\n", "true\n", &renamedBoolVal, renamedBool(true)}, + {"%t\n", "F\n", &renamedBoolVal, renamedBool(false)}, + {"%v", "101\n", &renamedIntVal, renamedInt(101)}, + {"%c", "\u0101\n", &renamedIntVal, renamedInt('\u0101')}, + {"%o", "0146\n", &renamedIntVal, renamedInt(102)}, + {"%v", "103\n", &renamedUintVal, renamedUint(103)}, + {"%d", "104\n", &renamedUintVal, renamedUint(104)}, + {"%d", "105\n", &renamedInt8Val, renamedInt8(105)}, + {"%d", "106\n", &renamedInt16Val, renamedInt16(106)}, + {"%d", "107\n", &renamedInt32Val, renamedInt32(107)}, + {"%d", "108\n", &renamedInt64Val, renamedInt64(108)}, + {"%x", "6D\n", &renamedUint8Val, renamedUint8(109)}, + {"%o", "0156\n", &renamedUint16Val, renamedUint16(110)}, + {"%d", "111\n", &renamedUint32Val, renamedUint32(111)}, + {"%d", "112\n", &renamedUint64Val, renamedUint64(112)}, + {"%d", "113\n", &renamedUintptrVal, renamedUintptr(113)}, + {"%s", "114\n", &renamedStringVal, renamedString("114")}, + {"%q", "\"1155\"\n", &renamedBytesVal, renamedBytes([]byte("1155"))}, + {"%g", "116e1\n", &renamedFloat32Val, renamedFloat32(116e1)}, + {"%g", "-11.7e+1", &renamedFloat64Val, renamedFloat64(-11.7e+1)}, + {"%g", "11+6e1i\n", &renamedComplex64Val, renamedComplex64(11 + 6e1i)}, + {"%g", "-11.+7e+1i", &renamedComplex128Val, renamedComplex128(-11. + 7e+1i)}, + + // Interesting formats + {"here is\tthe value:%d", "here is the\tvalue:118\n", &intVal, 118}, + {"%% %%:%d", "% %:119\n", &intVal, 119}, + {"%d%%", "42%", &intVal, 42}, // %% at end of string. + + // Corner cases + {"%x", "FFFFFFFF\n", &uint32Val, uint32(0xFFFFFFFF)}, + + // Custom scanner. + {"%s", " sss ", &xVal, Xs("sss")}, + {"%2s", "sssss", &xVal, Xs("ss")}, + + // Fixed bugs + {"%d\n", "27\n", &intVal, 27}, // ok + {"%d\n", "28 \n", &intVal, 28}, // was: "unexpected newline" + {"%v", "0", &intVal, 0}, // was: "EOF"; 0 was taken as base prefix and not counted. + {"%v", "0", &uintVal, uint(0)}, // was: "EOF"; 0 was taken as base prefix and not counted. + {"%c", " ", &uintVal, uint(' ')}, // %c must accept a blank. + {"%c", "\t", &uintVal, uint('\t')}, // %c must accept any space. + {"%c", "\n", &uintVal, uint('\n')}, // %c must accept any space. + {"%d%%", "23%\n", &uintVal, uint(23)}, // %% matches literal %. + {"%%%d", "%23\n", &uintVal, uint(23)}, // %% matches literal %. + + // space handling + {"%d", "27", &intVal, 27}, + {"%d", "27 ", &intVal, 27}, + {"%d", " 27", &intVal, 27}, + {"%d", " 27 ", &intVal, 27}, + + {"X%d", "X27", &intVal, 27}, + {"X%d", "X27 ", &intVal, 27}, + {"X%d", "X 27", &intVal, 27}, + {"X%d", "X 27 ", &intVal, 27}, + + {"X %d", "X27", &intVal, nil}, // expected space in input to match format + {"X %d", "X27 ", &intVal, nil}, // expected space in input to match format + {"X %d", "X 27", &intVal, 27}, + {"X %d", "X 27 ", &intVal, 27}, + + {"%dX", "27X", &intVal, 27}, + {"%dX", "27 X", &intVal, nil}, // input does not match format + {"%dX", " 27X", &intVal, 27}, + {"%dX", " 27 X", &intVal, nil}, // input does not match format + + {"%d X", "27X", &intVal, nil}, // expected space in input to match format + {"%d X", "27 X", &intVal, 27}, + {"%d X", " 27X", &intVal, nil}, // expected space in input to match format + {"%d X", " 27 X", &intVal, 27}, + + {"X %d X", "X27X", &intVal, nil}, // expected space in input to match format + {"X %d X", "X27 X", &intVal, nil}, // expected space in input to match format + {"X %d X", "X 27X", &intVal, nil}, // expected space in input to match format + {"X %d X", "X 27 X", &intVal, 27}, + + {"X %s X", "X27X", &stringVal, nil}, // expected space in input to match format + {"X %s X", "X27 X", &stringVal, nil}, // expected space in input to match format + {"X %s X", "X 27X", &stringVal, nil}, // unexpected EOF + {"X %s X", "X 27 X", &stringVal, "27"}, + + {"X%sX", "X27X", &stringVal, nil}, // unexpected EOF + {"X%sX", "X27 X", &stringVal, nil}, // input does not match format + {"X%sX", "X 27X", &stringVal, nil}, // unexpected EOF + {"X%sX", "X 27 X", &stringVal, nil}, // input does not match format + + {"X%s", "X27", &stringVal, "27"}, + {"X%s", "X27 ", &stringVal, "27"}, + {"X%s", "X 27", &stringVal, "27"}, + {"X%s", "X 27 ", &stringVal, "27"}, + + {"X%dX", "X27X", &intVal, 27}, + {"X%dX", "X27 X", &intVal, nil}, // input does not match format + {"X%dX", "X 27X", &intVal, 27}, + {"X%dX", "X 27 X", &intVal, nil}, // input does not match format + + {"X%dX", "X27X", &intVal, 27}, + {"X%dX", "X27X ", &intVal, 27}, + {"X%dX", " X27X", &intVal, nil}, // input does not match format + {"X%dX", " X27X ", &intVal, nil}, // input does not match format + + {"X%dX\n", "X27X", &intVal, 27}, + {"X%dX \n", "X27X ", &intVal, 27}, + {"X%dX\n", "X27X\n", &intVal, 27}, + {"X%dX\n", "X27X \n", &intVal, 27}, + + {"X%dX \n", "X27X", &intVal, 27}, + {"X%dX \n", "X27X ", &intVal, 27}, + {"X%dX \n", "X27X\n", &intVal, 27}, + {"X%dX \n", "X27X \n", &intVal, 27}, + + {"X%c", "X\n", &runeVal, '\n'}, + {"X%c", "X \n", &runeVal, ' '}, + {"X %c", "X!", &runeVal, nil}, // expected space in input to match format + {"X %c", "X\n", &runeVal, nil}, // newline in input does not match format + {"X %c", "X !", &runeVal, '!'}, + {"X %c", "X \n", &runeVal, '\n'}, + + {" X%dX", "X27X", &intVal, nil}, // expected space in input to match format + {" X%dX", "X27X ", &intVal, nil}, // expected space in input to match format + {" X%dX", " X27X", &intVal, 27}, + {" X%dX", " X27X ", &intVal, 27}, + + {"X%dX ", "X27X", &intVal, 27}, + {"X%dX ", "X27X ", &intVal, 27}, + {"X%dX ", " X27X", &intVal, nil}, // input does not match format + {"X%dX ", " X27X ", &intVal, nil}, // input does not match format + + {" X%dX ", "X27X", &intVal, nil}, // expected space in input to match format + {" X%dX ", "X27X ", &intVal, nil}, // expected space in input to match format + {" X%dX ", " X27X", &intVal, 27}, + {" X%dX ", " X27X ", &intVal, 27}, + + {"%d\nX", "27\nX", &intVal, 27}, + {"%dX\n X", "27X\n X", &intVal, 27}, +} + +var overflowTests = []ScanTest{ + {"128", &int8Val, 0}, + {"32768", &int16Val, 0}, + {"-129", &int8Val, 0}, + {"-32769", &int16Val, 0}, + {"256", &uint8Val, 0}, + {"65536", &uint16Val, 0}, + {"1e100", &float32Val, 0}, + {"1e500", &float64Val, 0}, + {"(1e100+0i)", &complex64Val, 0}, + {"(1+1e100i)", &complex64Val, 0}, + {"(1-1e500i)", &complex128Val, 0}, +} + +var truth bool +var i, j, k int +var f float64 +var s, t string +var c complex128 +var x, y Xs +var z IntString +var r1, r2, r3 rune + +var multiTests = []ScanfMultiTest{ + {"", "", []any{}, []any{}, ""}, + {"%d", "23", args(&i), args(23), ""}, + {"%2s%3s", "22333", args(&s, &t), args("22", "333"), ""}, + {"%2d%3d", "44555", args(&i, &j), args(44, 555), ""}, + {"%2d.%3d", "66.777", args(&i, &j), args(66, 777), ""}, + {"%d, %d", "23, 18", args(&i, &j), args(23, 18), ""}, + {"%3d22%3d", "33322333", args(&i, &j), args(333, 333), ""}, + {"%6vX=%3fY", "3+2iX=2.5Y", args(&c, &f), args((3 + 2i), 2.5), ""}, + {"%d%s", "123abc", args(&i, &s), args(123, "abc"), ""}, + {"%c%c%c", "2\u50c2X", args(&r1, &r2, &r3), args('2', '\u50c2', 'X'), ""}, + {"%5s%d", " 1234567 ", args(&s, &i), args("12345", 67), ""}, + {"%5s%d", " 12 34 567 ", args(&s, &i), args("12", 34), ""}, + + // Custom scanners. + {"%e%f", "eefffff", args(&x, &y), args(Xs("ee"), Xs("fffff")), ""}, + {"%4v%s", "12abcd", args(&z, &s), args(IntString{12, "ab"}, "cd"), ""}, + + // Errors + {"%t", "23 18", args(&i), nil, "bad verb"}, + {"%d %d %d", "23 18", args(&i, &j), args(23, 18), "too few operands"}, + {"%d %d", "23 18 27", args(&i, &j, &k), args(23, 18), "too many operands"}, + {"%c", "\u0100", args(&int8Val), nil, "overflow"}, + {"X%d", "10X", args(&intVal), nil, "input does not match format"}, + {"%d%", "42%", args(&intVal), args(42), "missing verb: % at end of format string"}, + {"%d% ", "42%", args(&intVal), args(42), "too few operands for format '% '"}, // Slightly odd error, but correct. + {"%%%d", "xxx 42", args(&intVal), args(42), "missing literal %"}, + {"%%%d", "x42", args(&intVal), args(42), "missing literal %"}, + {"%%%d", "42", args(&intVal), args(42), "missing literal %"}, + + // Bad UTF-8: should see every byte. + {"%c%c%c", "\xc2X\xc2", args(&r1, &r2, &r3), args(utf8.RuneError, 'X', utf8.RuneError), ""}, + + // Fixed bugs + {"%v%v", "FALSE23", args(&truth, &i), args(false, 23), ""}, +} + +var readers = []struct { + name string + f func(string) io.Reader +}{ + {"StringReader", func(s string) io.Reader { + return strings.NewReader(s) + }}, + {"ReaderOnly", func(s string) io.Reader { + return struct{ io.Reader }{strings.NewReader(s)} + }}, + {"OneByteReader", func(s string) io.Reader { + return iotest.OneByteReader(strings.NewReader(s)) + }}, + {"DataErrReader", func(s string) io.Reader { + return iotest.DataErrReader(strings.NewReader(s)) + }}, +} + +func testScan(t *testing.T, f func(string) io.Reader, scan func(r io.Reader, a ...any) (int, error)) { + for _, test := range scanTests { + r := f(test.text) + n, err := scan(r, test.in) + if err != nil { + m := "" + if n > 0 { + m = Sprintf(" (%d fields ok)", n) + } + t.Errorf("got error scanning %q: %s%s", test.text, err, m) + continue + } + if n != 1 { + t.Errorf("count error on entry %q: got %d", test.text, n) + continue + } + // The incoming value may be a pointer + v := reflect.ValueOf(test.in) + if p := v; p.Kind() == reflect.Pointer { + v = p.Elem() + } + val := v.Interface() + if !reflect.DeepEqual(val, test.out) { + t.Errorf("scanning %q: expected %#v got %#v, type %T", test.text, test.out, val, val) + } + } +} + +func TestScan(t *testing.T) { + for _, r := range readers { + t.Run(r.name, func(t *testing.T) { + testScan(t, r.f, Fscan) + }) + } +} + +func TestScanln(t *testing.T) { + for _, r := range readers { + t.Run(r.name, func(t *testing.T) { + testScan(t, r.f, Fscanln) + }) + } +} + +func TestScanf(t *testing.T) { + for _, test := range scanfTests { + n, err := Sscanf(test.text, test.format, test.in) + if err != nil { + if test.out != nil { + t.Errorf("Sscanf(%q, %q): unexpected error: %v", test.text, test.format, err) + } + continue + } + if test.out == nil { + t.Errorf("Sscanf(%q, %q): unexpected success", test.text, test.format) + continue + } + if n != 1 { + t.Errorf("Sscanf(%q, %q): parsed %d field, want 1", test.text, test.format, n) + continue + } + // The incoming value may be a pointer + v := reflect.ValueOf(test.in) + if p := v; p.Kind() == reflect.Pointer { + v = p.Elem() + } + val := v.Interface() + if !reflect.DeepEqual(val, test.out) { + t.Errorf("Sscanf(%q, %q): parsed value %T(%#v), want %T(%#v)", test.text, test.format, val, val, test.out, test.out) + } + } +} + +func TestScanOverflow(t *testing.T) { + // different machines and different types report errors with different strings. + re := regexp.MustCompile("overflow|too large|out of range|not representable") + for _, test := range overflowTests { + _, err := Sscan(test.text, test.in) + if err == nil { + t.Errorf("expected overflow scanning %q", test.text) + continue + } + if !re.MatchString(err.Error()) { + t.Errorf("expected overflow error scanning %q: %s", test.text, err) + } + } +} + +func verifyNaN(str string, t *testing.T) { + var f float64 + var f32 float32 + var f64 float64 + text := str + " " + str + " " + str + n, err := Fscan(strings.NewReader(text), &f, &f32, &f64) + if err != nil { + t.Errorf("got error scanning %q: %s", text, err) + } + if n != 3 { + t.Errorf("count error scanning %q: got %d", text, n) + } + if !math.IsNaN(float64(f)) || !math.IsNaN(float64(f32)) || !math.IsNaN(f64) { + t.Errorf("didn't get NaNs scanning %q: got %g %g %g", text, f, f32, f64) + } +} + +func TestNaN(t *testing.T) { + for _, s := range []string{"nan", "NAN", "NaN"} { + verifyNaN(s, t) + } +} + +func verifyInf(str string, t *testing.T) { + var f float64 + var f32 float32 + var f64 float64 + text := str + " " + str + " " + str + n, err := Fscan(strings.NewReader(text), &f, &f32, &f64) + if err != nil { + t.Errorf("got error scanning %q: %s", text, err) + } + if n != 3 { + t.Errorf("count error scanning %q: got %d", text, n) + } + sign := 1 + if str[0] == '-' { + sign = -1 + } + if !math.IsInf(float64(f), sign) || !math.IsInf(float64(f32), sign) || !math.IsInf(f64, sign) { + t.Errorf("didn't get right Infs scanning %q: got %g %g %g", text, f, f32, f64) + } +} + +func TestInf(t *testing.T) { + for _, s := range []string{"inf", "+inf", "-inf", "INF", "-INF", "+INF", "Inf", "-Inf", "+Inf"} { + verifyInf(s, t) + } +} + +func testScanfMulti(t *testing.T, f func(string) io.Reader) { + sliceType := reflect.TypeOf(make([]any, 1)) + for _, test := range multiTests { + r := f(test.text) + n, err := Fscanf(r, test.format, test.in...) + if err != nil { + if test.err == "" { + t.Errorf("got error scanning (%q, %q): %q", test.format, test.text, err) + } else if !strings.Contains(err.Error(), test.err) { + t.Errorf("got wrong error scanning (%q, %q): %q; expected %q", test.format, test.text, err, test.err) + } + continue + } + if test.err != "" { + t.Errorf("expected error %q error scanning (%q, %q)", test.err, test.format, test.text) + } + if n != len(test.out) { + t.Errorf("count error on entry (%q, %q): expected %d got %d", test.format, test.text, len(test.out), n) + continue + } + // Convert the slice of pointers into a slice of values + resultVal := reflect.MakeSlice(sliceType, n, n) + for i := 0; i < n; i++ { + v := reflect.ValueOf(test.in[i]).Elem() + resultVal.Index(i).Set(v) + } + result := resultVal.Interface() + if !reflect.DeepEqual(result, test.out) { + t.Errorf("scanning (%q, %q): expected %#v got %#v", test.format, test.text, test.out, result) + } + } +} + +func TestScanfMulti(t *testing.T) { + for _, r := range readers { + t.Run(r.name, func(t *testing.T) { + testScanfMulti(t, r.f) + }) + } +} + +func TestScanMultiple(t *testing.T) { + var a int + var s string + n, err := Sscan("123abc", &a, &s) + if n != 2 { + t.Errorf("Sscan count error: expected 2: got %d", n) + } + if err != nil { + t.Errorf("Sscan expected no error; got %s", err) + } + if a != 123 || s != "abc" { + t.Errorf("Sscan wrong values: got (%d %q) expected (123 \"abc\")", a, s) + } + n, err = Sscan("asdf", &s, &a) + if n != 1 { + t.Errorf("Sscan count error: expected 1: got %d", n) + } + if err == nil { + t.Errorf("Sscan expected error; got none: %s", err) + } + if s != "asdf" { + t.Errorf("Sscan wrong values: got %q expected \"asdf\"", s) + } +} + +// Empty strings are not valid input when scanning a string. +func TestScanEmpty(t *testing.T) { + var s1, s2 string + n, err := Sscan("abc", &s1, &s2) + if n != 1 { + t.Errorf("Sscan count error: expected 1: got %d", n) + } + if err == nil { + t.Error("Sscan expected error; got none") + } + if s1 != "abc" { + t.Errorf("Sscan wrong values: got %q expected \"abc\"", s1) + } + n, err = Sscan("", &s1, &s2) + if n != 0 { + t.Errorf("Sscan count error: expected 0: got %d", n) + } + if err == nil { + t.Error("Sscan expected error; got none") + } + // Quoted empty string is OK. + n, err = Sscanf(`""`, "%q", &s1) + if n != 1 { + t.Errorf("Sscanf count error: expected 1: got %d", n) + } + if err != nil { + t.Errorf("Sscanf expected no error with quoted string; got %s", err) + } +} + +func TestScanNotPointer(t *testing.T) { + r := strings.NewReader("1") + var a int + _, err := Fscan(r, a) + if err == nil { + t.Error("expected error scanning non-pointer") + } else if !strings.Contains(err.Error(), "pointer") { + t.Errorf("expected pointer error scanning non-pointer, got: %s", err) + } +} + +func TestScanlnNoNewline(t *testing.T) { + var a int + _, err := Sscanln("1 x\n", &a) + if err == nil { + t.Error("expected error scanning string missing newline") + } else if !strings.Contains(err.Error(), "newline") { + t.Errorf("expected newline error scanning string missing newline, got: %s", err) + } +} + +func TestScanlnWithMiddleNewline(t *testing.T) { + r := strings.NewReader("123\n456\n") + var a, b int + _, err := Fscanln(r, &a, &b) + if err == nil { + t.Error("expected error scanning string with extra newline") + } else if !strings.Contains(err.Error(), "newline") { + t.Errorf("expected newline error scanning string with extra newline, got: %s", err) + } +} + +// eofCounter is a special Reader that counts reads at end of file. +type eofCounter struct { + reader *strings.Reader + eofCount int +} + +func (ec *eofCounter) Read(b []byte) (n int, err error) { + n, err = ec.reader.Read(b) + if n == 0 { + ec.eofCount++ + } + return +} + +// TestEOF verifies that when we scan, we see at most EOF once per call to a +// Scan function, and then only when it's really an EOF. +func TestEOF(t *testing.T) { + ec := &eofCounter{strings.NewReader("123\n"), 0} + var a int + n, err := Fscanln(ec, &a) + if err != nil { + t.Error("unexpected error", err) + } + if n != 1 { + t.Error("expected to scan one item, got", n) + } + if ec.eofCount != 0 { + t.Error("expected zero EOFs", ec.eofCount) + ec.eofCount = 0 // reset for next test + } + n, err = Fscanln(ec, &a) + if err == nil { + t.Error("expected error scanning empty string") + } + if n != 0 { + t.Error("expected to scan zero items, got", n) + } + if ec.eofCount != 1 { + t.Error("expected one EOF, got", ec.eofCount) + } +} + +// TestEOFAtEndOfInput verifies that we see an EOF error if we run out of input. +// This was a buglet: we used to get "expected integer". +func TestEOFAtEndOfInput(t *testing.T) { + var i, j int + n, err := Sscanf("23", "%d %d", &i, &j) + if n != 1 || i != 23 { + t.Errorf("Sscanf expected one value of 23; got %d %d", n, i) + } + if err != io.EOF { + t.Errorf("Sscanf expected EOF; got %q", err) + } + n, err = Sscan("234", &i, &j) + if n != 1 || i != 234 { + t.Errorf("Sscan expected one value of 234; got %d %d", n, i) + } + if err != io.EOF { + t.Errorf("Sscan expected EOF; got %q", err) + } + // Trailing space is tougher. + n, err = Sscan("234 ", &i, &j) + if n != 1 || i != 234 { + t.Errorf("Sscan expected one value of 234; got %d %d", n, i) + } + if err != io.EOF { + t.Errorf("Sscan expected EOF; got %q", err) + } +} + +var eofTests = []struct { + format string + v any +}{ + {"%s", &stringVal}, + {"%q", &stringVal}, + {"%x", &stringVal}, + {"%v", &stringVal}, + {"%v", &bytesVal}, + {"%v", &intVal}, + {"%v", &uintVal}, + {"%v", &boolVal}, + {"%v", &float32Val}, + {"%v", &complex64Val}, + {"%v", &renamedStringVal}, + {"%v", &renamedBytesVal}, + {"%v", &renamedIntVal}, + {"%v", &renamedUintVal}, + {"%v", &renamedBoolVal}, + {"%v", &renamedFloat32Val}, + {"%v", &renamedComplex64Val}, +} + +func TestEOFAllTypes(t *testing.T) { + for i, test := range eofTests { + if _, err := Sscanf("", test.format, test.v); err != io.EOF { + t.Errorf("#%d: %s %T not eof on empty string: %s", i, test.format, test.v, err) + } + if _, err := Sscanf(" ", test.format, test.v); err != io.EOF { + t.Errorf("#%d: %s %T not eof on trailing blanks: %s", i, test.format, test.v, err) + } + } +} + +// TestUnreadRuneWithBufio verifies that, at least when using bufio, successive +// calls to Fscan do not lose runes. +func TestUnreadRuneWithBufio(t *testing.T) { + r := bufio.NewReader(strings.NewReader("123αb")) + var i int + var a string + n, err := Fscanf(r, "%d", &i) + if n != 1 || err != nil { + t.Errorf("reading int expected one item, no errors; got %d %q", n, err) + } + if i != 123 { + t.Errorf("expected 123; got %d", i) + } + n, err = Fscanf(r, "%s", &a) + if n != 1 || err != nil { + t.Errorf("reading string expected one item, no errors; got %d %q", n, err) + } + if a != "αb" { + t.Errorf("expected αb; got %q", a) + } +} + +type TwoLines string + +// Scan attempts to read two lines into the object. Scanln should prevent this +// because it stops at newline; Scan and Scanf should be fine. +func (t *TwoLines) Scan(state ScanState, verb rune) error { + chars := make([]rune, 0, 100) + for nlCount := 0; nlCount < 2; { + c, _, err := state.ReadRune() + if err != nil { + return err + } + chars = append(chars, c) + if c == '\n' { + nlCount++ + } + } + *t = TwoLines(string(chars)) + return nil +} + +func TestMultiLine(t *testing.T) { + input := "abc\ndef\n" + // Sscan should work + var tscan TwoLines + n, err := Sscan(input, &tscan) + if n != 1 { + t.Errorf("Sscan: expected 1 item; got %d", n) + } + if err != nil { + t.Errorf("Sscan: expected no error; got %s", err) + } + if string(tscan) != input { + t.Errorf("Sscan: expected %q; got %q", input, tscan) + } + // Sscanf should work + var tscanf TwoLines + n, err = Sscanf(input, "%s", &tscanf) + if n != 1 { + t.Errorf("Sscanf: expected 1 item; got %d", n) + } + if err != nil { + t.Errorf("Sscanf: expected no error; got %s", err) + } + if string(tscanf) != input { + t.Errorf("Sscanf: expected %q; got %q", input, tscanf) + } + // Sscanln should not work + var tscanln TwoLines + n, err = Sscanln(input, &tscanln) + if n != 0 { + t.Errorf("Sscanln: expected 0 items; got %d: %q", n, tscanln) + } + if err == nil { + t.Error("Sscanln: expected error; got none") + } else if err != io.ErrUnexpectedEOF { + t.Errorf("Sscanln: expected io.ErrUnexpectedEOF (ha!); got %s", err) + } +} + +// TestLineByLineFscanf tests that Fscanf does not read past newline. Issue +// 3481. +func TestLineByLineFscanf(t *testing.T) { + r := struct{ io.Reader }{strings.NewReader("1\n2\n")} + var i, j int + n, err := Fscanf(r, "%v\n", &i) + if n != 1 || err != nil { + t.Fatalf("first read: %d %q", n, err) + } + n, err = Fscanf(r, "%v\n", &j) + if n != 1 || err != nil { + t.Fatalf("second read: %d %q", n, err) + } + if i != 1 || j != 2 { + t.Errorf("wrong values; wanted 1 2 got %d %d", i, j) + } +} + +// TestScanStateCount verifies the correct byte count is returned. Issue 8512. + +// runeScanner implements the Scanner interface for TestScanStateCount. +type runeScanner struct { + rune rune + size int +} + +func (rs *runeScanner) Scan(state ScanState, verb rune) error { + r, size, err := state.ReadRune() + rs.rune = r + rs.size = size + return err +} + +func TestScanStateCount(t *testing.T) { + var a, b, c runeScanner + n, err := Sscanf("12➂", "%c%c%c", &a, &b, &c) + if err != nil { + t.Fatal(err) + } + if n != 3 { + t.Fatalf("expected 3 items consumed, got %d", n) + } + if a.rune != '1' || b.rune != '2' || c.rune != '➂' { + t.Errorf("bad scan rune: %q %q %q should be '1' '2' '➂'", a.rune, b.rune, c.rune) + } + if a.size != 1 || b.size != 1 || c.size != 3 { + t.Errorf("bad scan size: %d %d %d should be 1 1 3", a.size, b.size, c.size) + } +} + +// RecursiveInt accepts a string matching %d.%d.%d.... +// and parses it into a linked list. +// It allows us to benchmark recursive descent style scanners. +type RecursiveInt struct { + i int + next *RecursiveInt +} + +func (r *RecursiveInt) Scan(state ScanState, verb rune) (err error) { + _, err = Fscan(state, &r.i) + if err != nil { + return + } + next := new(RecursiveInt) + _, err = Fscanf(state, ".%v", next) + if err != nil { + if err == io.ErrUnexpectedEOF { + err = nil + } + return + } + r.next = next + return +} + +// scanInts performs the same scanning task as RecursiveInt.Scan +// but without recurring through scanner, so we can compare +// performance more directly. +func scanInts(r *RecursiveInt, b *bytes.Buffer) (err error) { + r.next = nil + _, err = Fscan(b, &r.i) + if err != nil { + return + } + c, _, err := b.ReadRune() + if err != nil { + if err == io.EOF { + err = nil + } + return + } + if c != '.' { + return + } + next := new(RecursiveInt) + err = scanInts(next, b) + if err == nil { + r.next = next + } + return +} + +func makeInts(n int) []byte { + var buf bytes.Buffer + Fprintf(&buf, "1") + for i := 1; i < n; i++ { + Fprintf(&buf, ".%d", i+1) + } + return buf.Bytes() +} + +func TestScanInts(t *testing.T) { + testScanInts(t, scanInts) + testScanInts(t, func(r *RecursiveInt, b *bytes.Buffer) (err error) { + _, err = Fscan(b, r) + return + }) +} + +// 800 is small enough to not overflow the stack when using gccgo on a +// platform that does not support split stack. +const intCount = 800 + +func testScanInts(t *testing.T, scan func(*RecursiveInt, *bytes.Buffer) error) { + r := new(RecursiveInt) + ints := makeInts(intCount) + buf := bytes.NewBuffer(ints) + err := scan(r, buf) + if err != nil { + t.Error("unexpected error", err) + } + i := 1 + for ; r != nil; r = r.next { + if r.i != i { + t.Fatalf("bad scan: expected %d got %d", i, r.i) + } + i++ + } + if i-1 != intCount { + t.Fatalf("bad scan count: expected %d got %d", intCount, i-1) + } +} + +func BenchmarkScanInts(b *testing.B) { + b.StopTimer() + ints := makeInts(intCount) + var r RecursiveInt + for i := 0; i < b.N; i++ { + buf := bytes.NewBuffer(ints) + b.StartTimer() + scanInts(&r, buf) + b.StopTimer() + } +} + +func BenchmarkScanRecursiveInt(b *testing.B) { + b.StopTimer() + ints := makeInts(intCount) + var r RecursiveInt + for i := 0; i < b.N; i++ { + buf := bytes.NewBuffer(ints) + b.StartTimer() + Fscan(buf, &r) + b.StopTimer() + } +} + +func BenchmarkScanRecursiveIntReaderWrapper(b *testing.B) { + b.StopTimer() + ints := makeInts(intCount) + var r RecursiveInt + for i := 0; i < b.N; i++ { + buf := struct{ io.Reader }{strings.NewReader(string(ints))} + b.StartTimer() + Fscan(buf, &r) + b.StopTimer() + } +} + +// Issue 9124. +// %x on bytes couldn't handle non-space bytes terminating the scan. +func TestHexBytes(t *testing.T) { + var a, b []byte + n, err := Sscanf("00010203", "%x", &a) + if n != 1 || err != nil { + t.Errorf("simple: got count, err = %d, %v; expected 1, nil", n, err) + } + check := func(msg string, x []byte) { + if len(x) != 4 { + t.Errorf("%s: bad length %d", msg, len(x)) + } + for i, b := range x { + if int(b) != i { + t.Errorf("%s: bad x[%d] = %x", msg, i, x[i]) + } + } + } + check("simple", a) + a = nil + + n, err = Sscanf("00010203 00010203", "%x %x", &a, &b) + if n != 2 || err != nil { + t.Errorf("simple pair: got count, err = %d, %v; expected 2, nil", n, err) + } + check("simple pair a", a) + check("simple pair b", b) + a = nil + b = nil + + n, err = Sscanf("00010203:", "%x", &a) + if n != 1 || err != nil { + t.Errorf("colon: got count, err = %d, %v; expected 1, nil", n, err) + } + check("colon", a) + a = nil + + n, err = Sscanf("00010203:00010203", "%x:%x", &a, &b) + if n != 2 || err != nil { + t.Errorf("colon pair: got count, err = %d, %v; expected 2, nil", n, err) + } + check("colon pair a", a) + check("colon pair b", b) + a = nil + b = nil + + // This one fails because there is a hex byte after the data, + // that is, an odd number of hex input bytes. + n, err = Sscanf("000102034:", "%x", &a) + if n != 0 || err == nil { + t.Errorf("odd count: got count, err = %d, %v; expected 0, error", n, err) + } +} + +func TestScanNewlinesAreSpaces(t *testing.T) { + var a, b int + var tests = []struct { + name string + text string + count int + }{ + {"newlines", "1\n2\n", 2}, + {"no final newline", "1\n2", 2}, + {"newlines with spaces ", "1 \n 2 \n", 2}, + {"no final newline with spaces", "1 \n 2", 2}, + } + for _, test := range tests { + n, err := Sscan(test.text, &a, &b) + if n != test.count { + t.Errorf("%s: expected to scan %d item(s), scanned %d", test.name, test.count, n) + } + if err != nil { + t.Errorf("%s: unexpected error: %s", test.name, err) + } + } +} + +func TestScanlnNewlinesTerminate(t *testing.T) { + var a, b int + var tests = []struct { + name string + text string + count int + ok bool + }{ + {"one line one item", "1\n", 1, false}, + {"one line two items with spaces ", " 1 2 \n", 2, true}, + {"one line two items no newline", " 1 2", 2, true}, + {"two lines two items", "1\n2\n", 1, false}, + } + for _, test := range tests { + n, err := Sscanln(test.text, &a, &b) + if n != test.count { + t.Errorf("%s: expected to scan %d item(s), scanned %d", test.name, test.count, n) + } + if test.ok && err != nil { + t.Errorf("%s: unexpected error: %s", test.name, err) + } + if !test.ok && err == nil { + t.Errorf("%s: expected error; got none", test.name) + } + } +} + +func TestScanfNewlineMatchFormat(t *testing.T) { + var a, b int + var tests = []struct { + name string + text string + format string + count int + ok bool + }{ + {"newline in both", "1\n2", "%d\n%d\n", 2, true}, + {"newline in input", "1\n2", "%d %d", 1, false}, + {"space-newline in input", "1 \n2", "%d %d", 1, false}, + {"newline in format", "1 2", "%d\n%d", 1, false}, + {"space-newline in format", "1 2", "%d \n%d", 1, false}, + {"space-newline in both", "1 \n2", "%d \n%d", 2, true}, + {"extra space in format", "1\n2", "%d\n %d", 2, true}, + {"two extra spaces in format", "1\n2", "%d \n %d", 2, true}, + {"space vs newline 0000", "1\n2", "%d\n%d", 2, true}, + {"space vs newline 0001", "1\n2", "%d\n %d", 2, true}, + {"space vs newline 0010", "1\n2", "%d \n%d", 2, true}, + {"space vs newline 0011", "1\n2", "%d \n %d", 2, true}, + {"space vs newline 0100", "1\n 2", "%d\n%d", 2, true}, + {"space vs newline 0101", "1\n 2", "%d\n%d ", 2, true}, + {"space vs newline 0110", "1\n 2", "%d \n%d", 2, true}, + {"space vs newline 0111", "1\n 2", "%d \n %d", 2, true}, + {"space vs newline 1000", "1 \n2", "%d\n%d", 2, true}, + {"space vs newline 1001", "1 \n2", "%d\n %d", 2, true}, + {"space vs newline 1010", "1 \n2", "%d \n%d", 2, true}, + {"space vs newline 1011", "1 \n2", "%d \n %d", 2, true}, + {"space vs newline 1100", "1 \n 2", "%d\n%d", 2, true}, + {"space vs newline 1101", "1 \n 2", "%d\n %d", 2, true}, + {"space vs newline 1110", "1 \n 2", "%d \n%d", 2, true}, + {"space vs newline 1111", "1 \n 2", "%d \n %d", 2, true}, + {"space vs newline no-percent 0000", "1\n2", "1\n2", 0, true}, + {"space vs newline no-percent 0001", "1\n2", "1\n 2", 0, true}, + {"space vs newline no-percent 0010", "1\n2", "1 \n2", 0, true}, + {"space vs newline no-percent 0011", "1\n2", "1 \n 2", 0, true}, + {"space vs newline no-percent 0100", "1\n 2", "1\n2", 0, false}, // fails: space after nl in input but not pattern + {"space vs newline no-percent 0101", "1\n 2", "1\n2 ", 0, false}, // fails: space after nl in input but not pattern + {"space vs newline no-percent 0110", "1\n 2", "1 \n2", 0, false}, // fails: space after nl in input but not pattern + {"space vs newline no-percent 0111", "1\n 2", "1 \n 2", 0, true}, + {"space vs newline no-percent 1000", "1 \n2", "1\n2", 0, true}, + {"space vs newline no-percent 1001", "1 \n2", "1\n 2", 0, true}, + {"space vs newline no-percent 1010", "1 \n2", "1 \n2", 0, true}, + {"space vs newline no-percent 1011", "1 \n2", "1 \n 2", 0, true}, + {"space vs newline no-percent 1100", "1 \n 2", "1\n2", 0, false}, // fails: space after nl in input but not pattern + {"space vs newline no-percent 1101", "1 \n 2", "1\n 2", 0, true}, + {"space vs newline no-percent 1110", "1 \n 2", "1 \n2", 0, false}, // fails: space after nl in input but not pattern + {"space vs newline no-percent 1111", "1 \n 2", "1 \n 2", 0, true}, + } + for _, test := range tests { + var n int + var err error + if strings.Contains(test.format, "%") { + n, err = Sscanf(test.text, test.format, &a, &b) + } else { + n, err = Sscanf(test.text, test.format) + } + if n != test.count { + t.Errorf("%s: expected to scan %d item(s), scanned %d", test.name, test.count, n) + } + if test.ok && err != nil { + t.Errorf("%s: unexpected error: %s", test.name, err) + } + if !test.ok && err == nil { + t.Errorf("%s: expected error; got none", test.name) + } + } +} + +// Test for issue 12090: Was unreading at EOF, double-scanning a byte. + +type hexBytes [2]byte + +func (h *hexBytes) Scan(ss ScanState, verb rune) error { + var b []byte + _, err := Fscanf(ss, "%4x", &b) + if err != nil { + panic(err) // Really shouldn't happen. + } + copy((*h)[:], b) + return err +} + +func TestHexByte(t *testing.T) { + var h hexBytes + n, err := Sscanln("0123\n", &h) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("expected 1 item; scanned %d", n) + } + if h[0] != 0x01 || h[1] != 0x23 { + t.Fatalf("expected 0123 got %x", h) + } +} diff --git a/go/src/fmt/state_test.go b/go/src/fmt/state_test.go new file mode 100644 index 0000000000000000000000000000000000000000..fda660aa3241bbdec6bc81f39913fdd8e8d6b1b9 --- /dev/null +++ b/go/src/fmt/state_test.go @@ -0,0 +1,80 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + "fmt" + "testing" +) + +type testState struct { + width int + widthOK bool + prec int + precOK bool + flag map[int]bool +} + +var _ fmt.State = testState{} + +func (s testState) Write(b []byte) (n int, err error) { + panic("unimplemented") +} + +func (s testState) Width() (wid int, ok bool) { + return s.width, s.widthOK +} + +func (s testState) Precision() (prec int, ok bool) { + return s.prec, s.precOK +} + +func (s testState) Flag(c int) bool { + return s.flag[c] +} + +const NO = -1000 + +func mkState(w, p int, flags string) testState { + s := testState{} + if w != NO { + s.width = w + s.widthOK = true + } + if p != NO { + s.prec = p + s.precOK = true + } + s.flag = make(map[int]bool) + for _, c := range flags { + s.flag[int(c)] = true + } + return s +} + +func TestFormatString(t *testing.T) { + var tests = []struct { + width, prec int + flags string + result string + }{ + {NO, NO, "", "%x"}, + {NO, 3, "", "%.3x"}, + {3, NO, "", "%3x"}, + {7, 3, "", "%7.3x"}, + {NO, NO, " +-#0", "% +-#0x"}, + {7, 3, "+", "%+7.3x"}, + {7, -3, "-", "%-7.-3x"}, + {7, 3, " ", "% 7.3x"}, + {7, 3, "#", "%#7.3x"}, + {7, 3, "0", "%07.3x"}, + } + for _, test := range tests { + got := fmt.FormatString(mkState(test.width, test.prec, test.flags), 'x') + if got != test.result { + t.Errorf("%v: got %s", test, got) + } + } +} diff --git a/go/src/fmt/stringer_example_test.go b/go/src/fmt/stringer_example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c77e78809cc56ccdfa0f13aaddeed1a7a58e3abc --- /dev/null +++ b/go/src/fmt/stringer_example_test.go @@ -0,0 +1,29 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + "fmt" +) + +// Animal has a Name and an Age to represent an animal. +type Animal struct { + Name string + Age uint +} + +// String makes Animal satisfy the Stringer interface. +func (a Animal) String() string { + return fmt.Sprintf("%v (%d)", a.Name, a.Age) +} + +func ExampleStringer() { + a := Animal{ + Name: "Gopher", + Age: 2, + } + fmt.Println(a) + // Output: Gopher (2) +} diff --git a/go/src/fmt/stringer_test.go b/go/src/fmt/stringer_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0ca3f522d622aa7d6b2af6a97f253fa3eca869b5 --- /dev/null +++ b/go/src/fmt/stringer_test.go @@ -0,0 +1,61 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fmt_test + +import ( + . "fmt" + "testing" +) + +type TI int +type TI8 int8 +type TI16 int16 +type TI32 int32 +type TI64 int64 +type TU uint +type TU8 uint8 +type TU16 uint16 +type TU32 uint32 +type TU64 uint64 +type TUI uintptr +type TF float64 +type TF32 float32 +type TF64 float64 +type TB bool +type TS string + +func (v TI) String() string { return Sprintf("I: %d", int(v)) } +func (v TI8) String() string { return Sprintf("I8: %d", int8(v)) } +func (v TI16) String() string { return Sprintf("I16: %d", int16(v)) } +func (v TI32) String() string { return Sprintf("I32: %d", int32(v)) } +func (v TI64) String() string { return Sprintf("I64: %d", int64(v)) } +func (v TU) String() string { return Sprintf("U: %d", uint(v)) } +func (v TU8) String() string { return Sprintf("U8: %d", uint8(v)) } +func (v TU16) String() string { return Sprintf("U16: %d", uint16(v)) } +func (v TU32) String() string { return Sprintf("U32: %d", uint32(v)) } +func (v TU64) String() string { return Sprintf("U64: %d", uint64(v)) } +func (v TUI) String() string { return Sprintf("UI: %d", uintptr(v)) } +func (v TF) String() string { return Sprintf("F: %f", float64(v)) } +func (v TF32) String() string { return Sprintf("F32: %f", float32(v)) } +func (v TF64) String() string { return Sprintf("F64: %f", float64(v)) } +func (v TB) String() string { return Sprintf("B: %t", bool(v)) } +func (v TS) String() string { return Sprintf("S: %q", string(v)) } + +func check(t *testing.T, got, want string) { + if got != want { + t.Error(got, "!=", want) + } +} + +func TestStringer(t *testing.T) { + s := Sprintf("%v %v %v %v %v", TI(0), TI8(1), TI16(2), TI32(3), TI64(4)) + check(t, s, "I: 0 I8: 1 I16: 2 I32: 3 I64: 4") + s = Sprintf("%v %v %v %v %v %v", TU(5), TU8(6), TU16(7), TU32(8), TU64(9), TUI(10)) + check(t, s, "U: 5 U8: 6 U16: 7 U32: 8 U64: 9 UI: 10") + s = Sprintf("%v %v %v", TF(1.0), TF32(2.0), TF64(3.0)) + check(t, s, "F: 1.000000 F32: 2.000000 F64: 3.000000") + s = Sprintf("%v %v", TB(true), TS("x")) + check(t, s, "B: true S: \"x\"") +} diff --git a/go/src/hash/example_test.go b/go/src/hash/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f07b9aaa2c4898b5765ba66da0faf6cf48fa4e42 --- /dev/null +++ b/go/src/hash/example_test.go @@ -0,0 +1,51 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package hash_test + +import ( + "bytes" + "crypto/sha256" + "encoding" + "fmt" + "log" +) + +func Example_binaryMarshaler() { + const ( + input1 = "The tunneling gopher digs downwards, " + input2 = "unaware of what he will find." + ) + + first := sha256.New() + first.Write([]byte(input1)) + + marshaler, ok := first.(encoding.BinaryMarshaler) + if !ok { + log.Fatal("first does not implement encoding.BinaryMarshaler") + } + state, err := marshaler.MarshalBinary() + if err != nil { + log.Fatal("unable to marshal hash:", err) + } + + second := sha256.New() + + unmarshaler, ok := second.(encoding.BinaryUnmarshaler) + if !ok { + log.Fatal("second does not implement encoding.BinaryUnmarshaler") + } + if err := unmarshaler.UnmarshalBinary(state); err != nil { + log.Fatal("unable to unmarshal hash:", err) + } + + first.Write([]byte(input2)) + second.Write([]byte(input2)) + + fmt.Printf("%x\n", first.Sum(nil)) + fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil))) + // Output: + // 57d51a066f3a39942649cd9a76c77e97ceab246756ff3888659e6aa5a07f4a52 + // true +} diff --git a/go/src/hash/hash.go b/go/src/hash/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..24ee9929c9587d7873675febe6b4bb59e6f57a07 --- /dev/null +++ b/go/src/hash/hash.go @@ -0,0 +1,92 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package hash provides interfaces for hash functions. +package hash + +import "io" + +// Hash is the common interface implemented by all hash functions. +// +// Hash implementations in the standard library (e.g. [hash/crc32] and +// [crypto/sha256]) implement the [encoding.BinaryMarshaler], [encoding.BinaryAppender], +// [encoding.BinaryUnmarshaler] and [Cloner] interfaces. Marshaling a hash implementation +// allows its internal state to be saved and used for additional processing +// later, without having to re-write the data previously written to the hash. +// The hash state may contain portions of the input in its original form, +// which users are expected to handle for any possible security implications. +// +// Compatibility: Any future changes to hash or crypto packages will endeavor +// to maintain compatibility with state encoded using previous versions. +// That is, any released versions of the packages should be able to +// decode data written with any previously released version, +// subject to issues such as security fixes. +// See the Go compatibility document for background: https://golang.org/doc/go1compat +type Hash interface { + // Write (via the embedded io.Writer interface) adds more data to the running hash. + // It never returns an error. + io.Writer + + // Sum appends the current hash to b and returns the resulting slice. + // It does not change the underlying hash state. + Sum(b []byte) []byte + + // Reset resets the Hash to its initial state. + Reset() + + // Size returns the number of bytes Sum will return. + Size() int + + // BlockSize returns the hash's underlying block size. + // The Write method must be able to accept any amount + // of data, but it may operate more efficiently if all writes + // are a multiple of the block size. + BlockSize() int +} + +// Hash32 is the common interface implemented by all 32-bit hash functions. +type Hash32 interface { + Hash + Sum32() uint32 +} + +// Hash64 is the common interface implemented by all 64-bit hash functions. +type Hash64 interface { + Hash + Sum64() uint64 +} + +// A Cloner is a hash function whose state can be cloned, returning a value with +// equivalent and independent state. +// +// All [Hash] implementations in the standard library implement this interface, +// unless GOFIPS140=v1.0.0 is set. +// +// If a hash can only determine at runtime if it can be cloned (e.g. if it wraps +// another hash), Clone may return an error wrapping [errors.ErrUnsupported]. +// Otherwise, Clone must always return a nil error. +type Cloner interface { + Hash + Clone() (Cloner, error) +} + +// XOF (extendable output function) is a hash function with arbitrary or unlimited output length. +type XOF interface { + // Write absorbs more data into the XOF's state. It panics if called + // after Read. + io.Writer + + // Read reads more output from the XOF. It may return io.EOF if there + // is a limit to the XOF output length. + io.Reader + + // Reset resets the XOF to its initial state. + Reset() + + // BlockSize returns the XOF's underlying block size. + // The Write method must be able to accept any amount + // of data, but it may operate more efficiently if all writes + // are a multiple of the block size. + BlockSize() int +} diff --git a/go/src/hash/marshal_test.go b/go/src/hash/marshal_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3091f7a67acedeaf72fd3851cf295c1e7bd88e8f --- /dev/null +++ b/go/src/hash/marshal_test.go @@ -0,0 +1,107 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that the hashes in the standard library implement +// BinaryMarshaler, BinaryUnmarshaler, +// and lock in the current representations. + +package hash_test + +import ( + "bytes" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "crypto/sha512" + "encoding" + "encoding/hex" + "hash" + "hash/adler32" + "hash/crc32" + "hash/crc64" + "hash/fnv" + "testing" +) + +func fromHex(s string) []byte { + b, err := hex.DecodeString(s) + if err != nil { + panic(err) + } + return b +} + +var marshalTests = []struct { + name string + new func() hash.Hash + golden []byte +}{ + {"adler32", func() hash.Hash { return adler32.New() }, fromHex("61646c01460a789d")}, + {"crc32", func() hash.Hash { return crc32.NewIEEE() }, fromHex("63726301ca87914dc956d3e8")}, + {"crc64", func() hash.Hash { return crc64.New(crc64.MakeTable(crc64.ISO)) }, fromHex("6372630273ba8484bbcd5def5d51c83c581695be")}, + {"fnv32", func() hash.Hash { return fnv.New32() }, fromHex("666e760171ba3d77")}, + {"fnv32a", func() hash.Hash { return fnv.New32a() }, fromHex("666e76027439f86f")}, + {"fnv64", func() hash.Hash { return fnv.New64() }, fromHex("666e7603cc64e0e97692c637")}, + {"fnv64a", func() hash.Hash { return fnv.New64a() }, fromHex("666e7604c522af9b0dede66f")}, + {"fnv128", func() hash.Hash { return fnv.New128() }, fromHex("666e760561587a70a0f66d7981dc980e2cabbaf7")}, + {"fnv128a", func() hash.Hash { return fnv.New128a() }, fromHex("666e7606a955802b0136cb67622b461d9f91e6ff")}, + {"md5", md5.New, fromHex("6d643501a91b0023007aa14740a3979210b5f024c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, + {"sha1", sha1.New, fromHex("736861016dad5acb4dc003952f7a0b352ee5537ec381a228c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, + {"sha224", sha256.New224, fromHex("73686102f8b92fc047c9b4d82f01a6370841277b7a0d92108440178c83db855a8e66c2d9c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, + {"sha256", sha256.New, fromHex("736861032bed68b99987cae48183b2b049d393d0050868e4e8ba3730e9112b08765929b7c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, + {"sha384", sha512.New384, fromHex("736861046f1664d213dd802f7c47bc50637cf93592570a2b8695839148bf38341c6eacd05326452ef1cbe64d90f1ef73bb5ac7d2803565467d0ddb10c5ee3fc050f9f0c1808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, + {"sha512_224", sha512.New512_224, fromHex("736861056f1a450ec15af20572d0d1ee6518104d7cbbbe79a038557af5450ed7dbd420b53b7335209e951b4d9aff401f90549b9604fa3d823fbb8581c73582a88aa84022808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, + {"sha512_256", sha512.New512_256, fromHex("736861067c541f1d1a72536b1f5dad64026bcc7c508f8a2126b51f46f8b9bff63a26fee70980718031e96832e95547f4fe76160ff84076db53b4549b86354af8e17b5116808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, + {"sha512", sha512.New, fromHex("736861078e03953cd57cd6879321270afa70c5827bb5b69be59a8f0130147e94f2aedf7bdc01c56c92343ca8bd837bb7f0208f5a23e155694516b6f147099d491a30b151808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")}, +} + +func TestMarshalHash(t *testing.T) { + for _, tt := range marshalTests { + t.Run(tt.name, func(t *testing.T) { + buf := make([]byte, 256) + for i := range buf { + buf[i] = byte(i) + } + + h := tt.new() + h.Write(buf[:256]) + sum := h.Sum(nil) + + h2 := tt.new() + h3 := tt.new() + const split = 249 + for i := 0; i < split; i++ { + h2.Write(buf[i : i+1]) + } + h2m, ok := h2.(encoding.BinaryMarshaler) + if !ok { + t.Fatalf("Hash does not implement MarshalBinary") + } + enc, err := h2m.MarshalBinary() + if err != nil { + t.Fatalf("MarshalBinary: %v", err) + } + if !bytes.Equal(enc, tt.golden) { + t.Errorf("MarshalBinary = %x, want %x", enc, tt.golden) + } + h3u, ok := h3.(encoding.BinaryUnmarshaler) + if !ok { + t.Fatalf("Hash does not implement UnmarshalBinary") + } + if err := h3u.UnmarshalBinary(enc); err != nil { + t.Fatalf("UnmarshalBinary: %v", err) + } + h2.Write(buf[split:]) + h3.Write(buf[split:]) + sum2 := h2.Sum(nil) + sum3 := h3.Sum(nil) + if !bytes.Equal(sum2, sum) { + t.Fatalf("Sum after MarshalBinary = %x, want %x", sum2, sum) + } + if !bytes.Equal(sum3, sum) { + t.Fatalf("Sum after UnmarshalBinary = %x, want %x", sum3, sum) + } + }) + } +} diff --git a/go/src/hash/test_cases.txt b/go/src/hash/test_cases.txt new file mode 100644 index 0000000000000000000000000000000000000000..26d3ccc052495c1517ce4e5a30af947c3fb176c0 --- /dev/null +++ b/go/src/hash/test_cases.txt @@ -0,0 +1,31 @@ + +a +ab +abc +abcd +abcde +abcdef +abcdefg +abcdefgh +abcdefghi +abcdefghij +Discard medicine more than two years old. +He who has a shady past knows that nice guys finish last. +I wouldn't marry him with a ten foot pole. +Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave +The days of the digital watch are numbered. -Tom Stoppard +Nepal premier won't resign. +For every action there is an equal and opposite government program. +His money is twice tainted: 'taint yours and 'taint mine. +There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977 +It's a tiny change to the code and not completely disgusting. - Bob Manchek +size: a.out: bad magic +The major problem is with sendmail. -Mark Horton +Give me a rock, paper and scissors and I will move the world. CCFestoon +If the enemy is within range, then so are you. +It's well we cannot hear the screams/That we create in others' dreams. +You remind me of a TV show, but that's all right: I watch it anyway. +C is as portable as Stonehedge!! +Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley +The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule +How can you write a big system without C++? -Paul Glick diff --git a/go/src/hash/test_gen.awk b/go/src/hash/test_gen.awk new file mode 100644 index 0000000000000000000000000000000000000000..804f786795fa84cae233259bde18c1d7997ffa74 --- /dev/null +++ b/go/src/hash/test_gen.awk @@ -0,0 +1,14 @@ +# Copyright 2009 The Go Authors. All rights reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file. + +# awk -f test_gen.awk test_cases.txt +# generates test case table. +# edit next line to set particular reference implementation and name. +BEGIN { cmd = "echo -n `9 sha1sum`"; name = "Sha1Test" } +{ + printf("\t%s{ \"", name); + printf("%s", $0) |cmd; + close(cmd); + printf("\", \"%s\" },\n", $0); +} diff --git a/go/src/html/entity.go b/go/src/html/entity.go new file mode 100644 index 0000000000000000000000000000000000000000..421a54ab572eb27cfa15b2f415007ae751bb4a64 --- /dev/null +++ b/go/src/html/entity.go @@ -0,0 +1,2261 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import "sync" + +// All entities that do not end with ';' are 6 or fewer bytes long. +const longestEntityWithoutSemicolon = 6 + +// entityMaps returns entity and entity2. +// +// entity is a map from HTML entity names to their values. The semicolon matters: +// https://html.spec.whatwg.org/multipage/named-characters.html +// lists both "amp" and "amp;" as two separate entries. +// Note that the HTML5 list is larger than the HTML4 list at +// http://www.w3.org/TR/html4/sgml/entities.html +// +// entity2 is a map of HTML entities to two unicode codepoints. +var entityMaps = sync.OnceValues(func() (entity map[string]rune, entity2 map[string][2]rune) { + entity = map[string]rune{ + "AElig;": '\U000000C6', + "AMP;": '\U00000026', + "Aacute;": '\U000000C1', + "Abreve;": '\U00000102', + "Acirc;": '\U000000C2', + "Acy;": '\U00000410', + "Afr;": '\U0001D504', + "Agrave;": '\U000000C0', + "Alpha;": '\U00000391', + "Amacr;": '\U00000100', + "And;": '\U00002A53', + "Aogon;": '\U00000104', + "Aopf;": '\U0001D538', + "ApplyFunction;": '\U00002061', + "Aring;": '\U000000C5', + "Ascr;": '\U0001D49C', + "Assign;": '\U00002254', + "Atilde;": '\U000000C3', + "Auml;": '\U000000C4', + "Backslash;": '\U00002216', + "Barv;": '\U00002AE7', + "Barwed;": '\U00002306', + "Bcy;": '\U00000411', + "Because;": '\U00002235', + "Bernoullis;": '\U0000212C', + "Beta;": '\U00000392', + "Bfr;": '\U0001D505', + "Bopf;": '\U0001D539', + "Breve;": '\U000002D8', + "Bscr;": '\U0000212C', + "Bumpeq;": '\U0000224E', + "CHcy;": '\U00000427', + "COPY;": '\U000000A9', + "Cacute;": '\U00000106', + "Cap;": '\U000022D2', + "CapitalDifferentialD;": '\U00002145', + "Cayleys;": '\U0000212D', + "Ccaron;": '\U0000010C', + "Ccedil;": '\U000000C7', + "Ccirc;": '\U00000108', + "Cconint;": '\U00002230', + "Cdot;": '\U0000010A', + "Cedilla;": '\U000000B8', + "CenterDot;": '\U000000B7', + "Cfr;": '\U0000212D', + "Chi;": '\U000003A7', + "CircleDot;": '\U00002299', + "CircleMinus;": '\U00002296', + "CirclePlus;": '\U00002295', + "CircleTimes;": '\U00002297', + "ClockwiseContourIntegral;": '\U00002232', + "CloseCurlyDoubleQuote;": '\U0000201D', + "CloseCurlyQuote;": '\U00002019', + "Colon;": '\U00002237', + "Colone;": '\U00002A74', + "Congruent;": '\U00002261', + "Conint;": '\U0000222F', + "ContourIntegral;": '\U0000222E', + "Copf;": '\U00002102', + "Coproduct;": '\U00002210', + "CounterClockwiseContourIntegral;": '\U00002233', + "Cross;": '\U00002A2F', + "Cscr;": '\U0001D49E', + "Cup;": '\U000022D3', + "CupCap;": '\U0000224D', + "DD;": '\U00002145', + "DDotrahd;": '\U00002911', + "DJcy;": '\U00000402', + "DScy;": '\U00000405', + "DZcy;": '\U0000040F', + "Dagger;": '\U00002021', + "Darr;": '\U000021A1', + "Dashv;": '\U00002AE4', + "Dcaron;": '\U0000010E', + "Dcy;": '\U00000414', + "Del;": '\U00002207', + "Delta;": '\U00000394', + "Dfr;": '\U0001D507', + "DiacriticalAcute;": '\U000000B4', + "DiacriticalDot;": '\U000002D9', + "DiacriticalDoubleAcute;": '\U000002DD', + "DiacriticalGrave;": '\U00000060', + "DiacriticalTilde;": '\U000002DC', + "Diamond;": '\U000022C4', + "DifferentialD;": '\U00002146', + "Dopf;": '\U0001D53B', + "Dot;": '\U000000A8', + "DotDot;": '\U000020DC', + "DotEqual;": '\U00002250', + "DoubleContourIntegral;": '\U0000222F', + "DoubleDot;": '\U000000A8', + "DoubleDownArrow;": '\U000021D3', + "DoubleLeftArrow;": '\U000021D0', + "DoubleLeftRightArrow;": '\U000021D4', + "DoubleLeftTee;": '\U00002AE4', + "DoubleLongLeftArrow;": '\U000027F8', + "DoubleLongLeftRightArrow;": '\U000027FA', + "DoubleLongRightArrow;": '\U000027F9', + "DoubleRightArrow;": '\U000021D2', + "DoubleRightTee;": '\U000022A8', + "DoubleUpArrow;": '\U000021D1', + "DoubleUpDownArrow;": '\U000021D5', + "DoubleVerticalBar;": '\U00002225', + "DownArrow;": '\U00002193', + "DownArrowBar;": '\U00002913', + "DownArrowUpArrow;": '\U000021F5', + "DownBreve;": '\U00000311', + "DownLeftRightVector;": '\U00002950', + "DownLeftTeeVector;": '\U0000295E', + "DownLeftVector;": '\U000021BD', + "DownLeftVectorBar;": '\U00002956', + "DownRightTeeVector;": '\U0000295F', + "DownRightVector;": '\U000021C1', + "DownRightVectorBar;": '\U00002957', + "DownTee;": '\U000022A4', + "DownTeeArrow;": '\U000021A7', + "Downarrow;": '\U000021D3', + "Dscr;": '\U0001D49F', + "Dstrok;": '\U00000110', + "ENG;": '\U0000014A', + "ETH;": '\U000000D0', + "Eacute;": '\U000000C9', + "Ecaron;": '\U0000011A', + "Ecirc;": '\U000000CA', + "Ecy;": '\U0000042D', + "Edot;": '\U00000116', + "Efr;": '\U0001D508', + "Egrave;": '\U000000C8', + "Element;": '\U00002208', + "Emacr;": '\U00000112', + "EmptySmallSquare;": '\U000025FB', + "EmptyVerySmallSquare;": '\U000025AB', + "Eogon;": '\U00000118', + "Eopf;": '\U0001D53C', + "Epsilon;": '\U00000395', + "Equal;": '\U00002A75', + "EqualTilde;": '\U00002242', + "Equilibrium;": '\U000021CC', + "Escr;": '\U00002130', + "Esim;": '\U00002A73', + "Eta;": '\U00000397', + "Euml;": '\U000000CB', + "Exists;": '\U00002203', + "ExponentialE;": '\U00002147', + "Fcy;": '\U00000424', + "Ffr;": '\U0001D509', + "FilledSmallSquare;": '\U000025FC', + "FilledVerySmallSquare;": '\U000025AA', + "Fopf;": '\U0001D53D', + "ForAll;": '\U00002200', + "Fouriertrf;": '\U00002131', + "Fscr;": '\U00002131', + "GJcy;": '\U00000403', + "GT;": '\U0000003E', + "Gamma;": '\U00000393', + "Gammad;": '\U000003DC', + "Gbreve;": '\U0000011E', + "Gcedil;": '\U00000122', + "Gcirc;": '\U0000011C', + "Gcy;": '\U00000413', + "Gdot;": '\U00000120', + "Gfr;": '\U0001D50A', + "Gg;": '\U000022D9', + "Gopf;": '\U0001D53E', + "GreaterEqual;": '\U00002265', + "GreaterEqualLess;": '\U000022DB', + "GreaterFullEqual;": '\U00002267', + "GreaterGreater;": '\U00002AA2', + "GreaterLess;": '\U00002277', + "GreaterSlantEqual;": '\U00002A7E', + "GreaterTilde;": '\U00002273', + "Gscr;": '\U0001D4A2', + "Gt;": '\U0000226B', + "HARDcy;": '\U0000042A', + "Hacek;": '\U000002C7', + "Hat;": '\U0000005E', + "Hcirc;": '\U00000124', + "Hfr;": '\U0000210C', + "HilbertSpace;": '\U0000210B', + "Hopf;": '\U0000210D', + "HorizontalLine;": '\U00002500', + "Hscr;": '\U0000210B', + "Hstrok;": '\U00000126', + "HumpDownHump;": '\U0000224E', + "HumpEqual;": '\U0000224F', + "IEcy;": '\U00000415', + "IJlig;": '\U00000132', + "IOcy;": '\U00000401', + "Iacute;": '\U000000CD', + "Icirc;": '\U000000CE', + "Icy;": '\U00000418', + "Idot;": '\U00000130', + "Ifr;": '\U00002111', + "Igrave;": '\U000000CC', + "Im;": '\U00002111', + "Imacr;": '\U0000012A', + "ImaginaryI;": '\U00002148', + "Implies;": '\U000021D2', + "Int;": '\U0000222C', + "Integral;": '\U0000222B', + "Intersection;": '\U000022C2', + "InvisibleComma;": '\U00002063', + "InvisibleTimes;": '\U00002062', + "Iogon;": '\U0000012E', + "Iopf;": '\U0001D540', + "Iota;": '\U00000399', + "Iscr;": '\U00002110', + "Itilde;": '\U00000128', + "Iukcy;": '\U00000406', + "Iuml;": '\U000000CF', + "Jcirc;": '\U00000134', + "Jcy;": '\U00000419', + "Jfr;": '\U0001D50D', + "Jopf;": '\U0001D541', + "Jscr;": '\U0001D4A5', + "Jsercy;": '\U00000408', + "Jukcy;": '\U00000404', + "KHcy;": '\U00000425', + "KJcy;": '\U0000040C', + "Kappa;": '\U0000039A', + "Kcedil;": '\U00000136', + "Kcy;": '\U0000041A', + "Kfr;": '\U0001D50E', + "Kopf;": '\U0001D542', + "Kscr;": '\U0001D4A6', + "LJcy;": '\U00000409', + "LT;": '\U0000003C', + "Lacute;": '\U00000139', + "Lambda;": '\U0000039B', + "Lang;": '\U000027EA', + "Laplacetrf;": '\U00002112', + "Larr;": '\U0000219E', + "Lcaron;": '\U0000013D', + "Lcedil;": '\U0000013B', + "Lcy;": '\U0000041B', + "LeftAngleBracket;": '\U000027E8', + "LeftArrow;": '\U00002190', + "LeftArrowBar;": '\U000021E4', + "LeftArrowRightArrow;": '\U000021C6', + "LeftCeiling;": '\U00002308', + "LeftDoubleBracket;": '\U000027E6', + "LeftDownTeeVector;": '\U00002961', + "LeftDownVector;": '\U000021C3', + "LeftDownVectorBar;": '\U00002959', + "LeftFloor;": '\U0000230A', + "LeftRightArrow;": '\U00002194', + "LeftRightVector;": '\U0000294E', + "LeftTee;": '\U000022A3', + "LeftTeeArrow;": '\U000021A4', + "LeftTeeVector;": '\U0000295A', + "LeftTriangle;": '\U000022B2', + "LeftTriangleBar;": '\U000029CF', + "LeftTriangleEqual;": '\U000022B4', + "LeftUpDownVector;": '\U00002951', + "LeftUpTeeVector;": '\U00002960', + "LeftUpVector;": '\U000021BF', + "LeftUpVectorBar;": '\U00002958', + "LeftVector;": '\U000021BC', + "LeftVectorBar;": '\U00002952', + "Leftarrow;": '\U000021D0', + "Leftrightarrow;": '\U000021D4', + "LessEqualGreater;": '\U000022DA', + "LessFullEqual;": '\U00002266', + "LessGreater;": '\U00002276', + "LessLess;": '\U00002AA1', + "LessSlantEqual;": '\U00002A7D', + "LessTilde;": '\U00002272', + "Lfr;": '\U0001D50F', + "Ll;": '\U000022D8', + "Lleftarrow;": '\U000021DA', + "Lmidot;": '\U0000013F', + "LongLeftArrow;": '\U000027F5', + "LongLeftRightArrow;": '\U000027F7', + "LongRightArrow;": '\U000027F6', + "Longleftarrow;": '\U000027F8', + "Longleftrightarrow;": '\U000027FA', + "Longrightarrow;": '\U000027F9', + "Lopf;": '\U0001D543', + "LowerLeftArrow;": '\U00002199', + "LowerRightArrow;": '\U00002198', + "Lscr;": '\U00002112', + "Lsh;": '\U000021B0', + "Lstrok;": '\U00000141', + "Lt;": '\U0000226A', + "Map;": '\U00002905', + "Mcy;": '\U0000041C', + "MediumSpace;": '\U0000205F', + "Mellintrf;": '\U00002133', + "Mfr;": '\U0001D510', + "MinusPlus;": '\U00002213', + "Mopf;": '\U0001D544', + "Mscr;": '\U00002133', + "Mu;": '\U0000039C', + "NJcy;": '\U0000040A', + "Nacute;": '\U00000143', + "Ncaron;": '\U00000147', + "Ncedil;": '\U00000145', + "Ncy;": '\U0000041D', + "NegativeMediumSpace;": '\U0000200B', + "NegativeThickSpace;": '\U0000200B', + "NegativeThinSpace;": '\U0000200B', + "NegativeVeryThinSpace;": '\U0000200B', + "NestedGreaterGreater;": '\U0000226B', + "NestedLessLess;": '\U0000226A', + "NewLine;": '\U0000000A', + "Nfr;": '\U0001D511', + "NoBreak;": '\U00002060', + "NonBreakingSpace;": '\U000000A0', + "Nopf;": '\U00002115', + "Not;": '\U00002AEC', + "NotCongruent;": '\U00002262', + "NotCupCap;": '\U0000226D', + "NotDoubleVerticalBar;": '\U00002226', + "NotElement;": '\U00002209', + "NotEqual;": '\U00002260', + "NotExists;": '\U00002204', + "NotGreater;": '\U0000226F', + "NotGreaterEqual;": '\U00002271', + "NotGreaterLess;": '\U00002279', + "NotGreaterTilde;": '\U00002275', + "NotLeftTriangle;": '\U000022EA', + "NotLeftTriangleEqual;": '\U000022EC', + "NotLess;": '\U0000226E', + "NotLessEqual;": '\U00002270', + "NotLessGreater;": '\U00002278', + "NotLessTilde;": '\U00002274', + "NotPrecedes;": '\U00002280', + "NotPrecedesSlantEqual;": '\U000022E0', + "NotReverseElement;": '\U0000220C', + "NotRightTriangle;": '\U000022EB', + "NotRightTriangleEqual;": '\U000022ED', + "NotSquareSubsetEqual;": '\U000022E2', + "NotSquareSupersetEqual;": '\U000022E3', + "NotSubsetEqual;": '\U00002288', + "NotSucceeds;": '\U00002281', + "NotSucceedsSlantEqual;": '\U000022E1', + "NotSupersetEqual;": '\U00002289', + "NotTilde;": '\U00002241', + "NotTildeEqual;": '\U00002244', + "NotTildeFullEqual;": '\U00002247', + "NotTildeTilde;": '\U00002249', + "NotVerticalBar;": '\U00002224', + "Nscr;": '\U0001D4A9', + "Ntilde;": '\U000000D1', + "Nu;": '\U0000039D', + "OElig;": '\U00000152', + "Oacute;": '\U000000D3', + "Ocirc;": '\U000000D4', + "Ocy;": '\U0000041E', + "Odblac;": '\U00000150', + "Ofr;": '\U0001D512', + "Ograve;": '\U000000D2', + "Omacr;": '\U0000014C', + "Omega;": '\U000003A9', + "Omicron;": '\U0000039F', + "Oopf;": '\U0001D546', + "OpenCurlyDoubleQuote;": '\U0000201C', + "OpenCurlyQuote;": '\U00002018', + "Or;": '\U00002A54', + "Oscr;": '\U0001D4AA', + "Oslash;": '\U000000D8', + "Otilde;": '\U000000D5', + "Otimes;": '\U00002A37', + "Ouml;": '\U000000D6', + "OverBar;": '\U0000203E', + "OverBrace;": '\U000023DE', + "OverBracket;": '\U000023B4', + "OverParenthesis;": '\U000023DC', + "PartialD;": '\U00002202', + "Pcy;": '\U0000041F', + "Pfr;": '\U0001D513', + "Phi;": '\U000003A6', + "Pi;": '\U000003A0', + "PlusMinus;": '\U000000B1', + "Poincareplane;": '\U0000210C', + "Popf;": '\U00002119', + "Pr;": '\U00002ABB', + "Precedes;": '\U0000227A', + "PrecedesEqual;": '\U00002AAF', + "PrecedesSlantEqual;": '\U0000227C', + "PrecedesTilde;": '\U0000227E', + "Prime;": '\U00002033', + "Product;": '\U0000220F', + "Proportion;": '\U00002237', + "Proportional;": '\U0000221D', + "Pscr;": '\U0001D4AB', + "Psi;": '\U000003A8', + "QUOT;": '\U00000022', + "Qfr;": '\U0001D514', + "Qopf;": '\U0000211A', + "Qscr;": '\U0001D4AC', + "RBarr;": '\U00002910', + "REG;": '\U000000AE', + "Racute;": '\U00000154', + "Rang;": '\U000027EB', + "Rarr;": '\U000021A0', + "Rarrtl;": '\U00002916', + "Rcaron;": '\U00000158', + "Rcedil;": '\U00000156', + "Rcy;": '\U00000420', + "Re;": '\U0000211C', + "ReverseElement;": '\U0000220B', + "ReverseEquilibrium;": '\U000021CB', + "ReverseUpEquilibrium;": '\U0000296F', + "Rfr;": '\U0000211C', + "Rho;": '\U000003A1', + "RightAngleBracket;": '\U000027E9', + "RightArrow;": '\U00002192', + "RightArrowBar;": '\U000021E5', + "RightArrowLeftArrow;": '\U000021C4', + "RightCeiling;": '\U00002309', + "RightDoubleBracket;": '\U000027E7', + "RightDownTeeVector;": '\U0000295D', + "RightDownVector;": '\U000021C2', + "RightDownVectorBar;": '\U00002955', + "RightFloor;": '\U0000230B', + "RightTee;": '\U000022A2', + "RightTeeArrow;": '\U000021A6', + "RightTeeVector;": '\U0000295B', + "RightTriangle;": '\U000022B3', + "RightTriangleBar;": '\U000029D0', + "RightTriangleEqual;": '\U000022B5', + "RightUpDownVector;": '\U0000294F', + "RightUpTeeVector;": '\U0000295C', + "RightUpVector;": '\U000021BE', + "RightUpVectorBar;": '\U00002954', + "RightVector;": '\U000021C0', + "RightVectorBar;": '\U00002953', + "Rightarrow;": '\U000021D2', + "Ropf;": '\U0000211D', + "RoundImplies;": '\U00002970', + "Rrightarrow;": '\U000021DB', + "Rscr;": '\U0000211B', + "Rsh;": '\U000021B1', + "RuleDelayed;": '\U000029F4', + "SHCHcy;": '\U00000429', + "SHcy;": '\U00000428', + "SOFTcy;": '\U0000042C', + "Sacute;": '\U0000015A', + "Sc;": '\U00002ABC', + "Scaron;": '\U00000160', + "Scedil;": '\U0000015E', + "Scirc;": '\U0000015C', + "Scy;": '\U00000421', + "Sfr;": '\U0001D516', + "ShortDownArrow;": '\U00002193', + "ShortLeftArrow;": '\U00002190', + "ShortRightArrow;": '\U00002192', + "ShortUpArrow;": '\U00002191', + "Sigma;": '\U000003A3', + "SmallCircle;": '\U00002218', + "Sopf;": '\U0001D54A', + "Sqrt;": '\U0000221A', + "Square;": '\U000025A1', + "SquareIntersection;": '\U00002293', + "SquareSubset;": '\U0000228F', + "SquareSubsetEqual;": '\U00002291', + "SquareSuperset;": '\U00002290', + "SquareSupersetEqual;": '\U00002292', + "SquareUnion;": '\U00002294', + "Sscr;": '\U0001D4AE', + "Star;": '\U000022C6', + "Sub;": '\U000022D0', + "Subset;": '\U000022D0', + "SubsetEqual;": '\U00002286', + "Succeeds;": '\U0000227B', + "SucceedsEqual;": '\U00002AB0', + "SucceedsSlantEqual;": '\U0000227D', + "SucceedsTilde;": '\U0000227F', + "SuchThat;": '\U0000220B', + "Sum;": '\U00002211', + "Sup;": '\U000022D1', + "Superset;": '\U00002283', + "SupersetEqual;": '\U00002287', + "Supset;": '\U000022D1', + "THORN;": '\U000000DE', + "TRADE;": '\U00002122', + "TSHcy;": '\U0000040B', + "TScy;": '\U00000426', + "Tab;": '\U00000009', + "Tau;": '\U000003A4', + "Tcaron;": '\U00000164', + "Tcedil;": '\U00000162', + "Tcy;": '\U00000422', + "Tfr;": '\U0001D517', + "Therefore;": '\U00002234', + "Theta;": '\U00000398', + "ThinSpace;": '\U00002009', + "Tilde;": '\U0000223C', + "TildeEqual;": '\U00002243', + "TildeFullEqual;": '\U00002245', + "TildeTilde;": '\U00002248', + "Topf;": '\U0001D54B', + "TripleDot;": '\U000020DB', + "Tscr;": '\U0001D4AF', + "Tstrok;": '\U00000166', + "Uacute;": '\U000000DA', + "Uarr;": '\U0000219F', + "Uarrocir;": '\U00002949', + "Ubrcy;": '\U0000040E', + "Ubreve;": '\U0000016C', + "Ucirc;": '\U000000DB', + "Ucy;": '\U00000423', + "Udblac;": '\U00000170', + "Ufr;": '\U0001D518', + "Ugrave;": '\U000000D9', + "Umacr;": '\U0000016A', + "UnderBar;": '\U0000005F', + "UnderBrace;": '\U000023DF', + "UnderBracket;": '\U000023B5', + "UnderParenthesis;": '\U000023DD', + "Union;": '\U000022C3', + "UnionPlus;": '\U0000228E', + "Uogon;": '\U00000172', + "Uopf;": '\U0001D54C', + "UpArrow;": '\U00002191', + "UpArrowBar;": '\U00002912', + "UpArrowDownArrow;": '\U000021C5', + "UpDownArrow;": '\U00002195', + "UpEquilibrium;": '\U0000296E', + "UpTee;": '\U000022A5', + "UpTeeArrow;": '\U000021A5', + "Uparrow;": '\U000021D1', + "Updownarrow;": '\U000021D5', + "UpperLeftArrow;": '\U00002196', + "UpperRightArrow;": '\U00002197', + "Upsi;": '\U000003D2', + "Upsilon;": '\U000003A5', + "Uring;": '\U0000016E', + "Uscr;": '\U0001D4B0', + "Utilde;": '\U00000168', + "Uuml;": '\U000000DC', + "VDash;": '\U000022AB', + "Vbar;": '\U00002AEB', + "Vcy;": '\U00000412', + "Vdash;": '\U000022A9', + "Vdashl;": '\U00002AE6', + "Vee;": '\U000022C1', + "Verbar;": '\U00002016', + "Vert;": '\U00002016', + "VerticalBar;": '\U00002223', + "VerticalLine;": '\U0000007C', + "VerticalSeparator;": '\U00002758', + "VerticalTilde;": '\U00002240', + "VeryThinSpace;": '\U0000200A', + "Vfr;": '\U0001D519', + "Vopf;": '\U0001D54D', + "Vscr;": '\U0001D4B1', + "Vvdash;": '\U000022AA', + "Wcirc;": '\U00000174', + "Wedge;": '\U000022C0', + "Wfr;": '\U0001D51A', + "Wopf;": '\U0001D54E', + "Wscr;": '\U0001D4B2', + "Xfr;": '\U0001D51B', + "Xi;": '\U0000039E', + "Xopf;": '\U0001D54F', + "Xscr;": '\U0001D4B3', + "YAcy;": '\U0000042F', + "YIcy;": '\U00000407', + "YUcy;": '\U0000042E', + "Yacute;": '\U000000DD', + "Ycirc;": '\U00000176', + "Ycy;": '\U0000042B', + "Yfr;": '\U0001D51C', + "Yopf;": '\U0001D550', + "Yscr;": '\U0001D4B4', + "Yuml;": '\U00000178', + "ZHcy;": '\U00000416', + "Zacute;": '\U00000179', + "Zcaron;": '\U0000017D', + "Zcy;": '\U00000417', + "Zdot;": '\U0000017B', + "ZeroWidthSpace;": '\U0000200B', + "Zeta;": '\U00000396', + "Zfr;": '\U00002128', + "Zopf;": '\U00002124', + "Zscr;": '\U0001D4B5', + "aacute;": '\U000000E1', + "abreve;": '\U00000103', + "ac;": '\U0000223E', + "acd;": '\U0000223F', + "acirc;": '\U000000E2', + "acute;": '\U000000B4', + "acy;": '\U00000430', + "aelig;": '\U000000E6', + "af;": '\U00002061', + "afr;": '\U0001D51E', + "agrave;": '\U000000E0', + "alefsym;": '\U00002135', + "aleph;": '\U00002135', + "alpha;": '\U000003B1', + "amacr;": '\U00000101', + "amalg;": '\U00002A3F', + "amp;": '\U00000026', + "and;": '\U00002227', + "andand;": '\U00002A55', + "andd;": '\U00002A5C', + "andslope;": '\U00002A58', + "andv;": '\U00002A5A', + "ang;": '\U00002220', + "ange;": '\U000029A4', + "angle;": '\U00002220', + "angmsd;": '\U00002221', + "angmsdaa;": '\U000029A8', + "angmsdab;": '\U000029A9', + "angmsdac;": '\U000029AA', + "angmsdad;": '\U000029AB', + "angmsdae;": '\U000029AC', + "angmsdaf;": '\U000029AD', + "angmsdag;": '\U000029AE', + "angmsdah;": '\U000029AF', + "angrt;": '\U0000221F', + "angrtvb;": '\U000022BE', + "angrtvbd;": '\U0000299D', + "angsph;": '\U00002222', + "angst;": '\U000000C5', + "angzarr;": '\U0000237C', + "aogon;": '\U00000105', + "aopf;": '\U0001D552', + "ap;": '\U00002248', + "apE;": '\U00002A70', + "apacir;": '\U00002A6F', + "ape;": '\U0000224A', + "apid;": '\U0000224B', + "apos;": '\U00000027', + "approx;": '\U00002248', + "approxeq;": '\U0000224A', + "aring;": '\U000000E5', + "ascr;": '\U0001D4B6', + "ast;": '\U0000002A', + "asymp;": '\U00002248', + "asympeq;": '\U0000224D', + "atilde;": '\U000000E3', + "auml;": '\U000000E4', + "awconint;": '\U00002233', + "awint;": '\U00002A11', + "bNot;": '\U00002AED', + "backcong;": '\U0000224C', + "backepsilon;": '\U000003F6', + "backprime;": '\U00002035', + "backsim;": '\U0000223D', + "backsimeq;": '\U000022CD', + "barvee;": '\U000022BD', + "barwed;": '\U00002305', + "barwedge;": '\U00002305', + "bbrk;": '\U000023B5', + "bbrktbrk;": '\U000023B6', + "bcong;": '\U0000224C', + "bcy;": '\U00000431', + "bdquo;": '\U0000201E', + "becaus;": '\U00002235', + "because;": '\U00002235', + "bemptyv;": '\U000029B0', + "bepsi;": '\U000003F6', + "bernou;": '\U0000212C', + "beta;": '\U000003B2', + "beth;": '\U00002136', + "between;": '\U0000226C', + "bfr;": '\U0001D51F', + "bigcap;": '\U000022C2', + "bigcirc;": '\U000025EF', + "bigcup;": '\U000022C3', + "bigodot;": '\U00002A00', + "bigoplus;": '\U00002A01', + "bigotimes;": '\U00002A02', + "bigsqcup;": '\U00002A06', + "bigstar;": '\U00002605', + "bigtriangledown;": '\U000025BD', + "bigtriangleup;": '\U000025B3', + "biguplus;": '\U00002A04', + "bigvee;": '\U000022C1', + "bigwedge;": '\U000022C0', + "bkarow;": '\U0000290D', + "blacklozenge;": '\U000029EB', + "blacksquare;": '\U000025AA', + "blacktriangle;": '\U000025B4', + "blacktriangledown;": '\U000025BE', + "blacktriangleleft;": '\U000025C2', + "blacktriangleright;": '\U000025B8', + "blank;": '\U00002423', + "blk12;": '\U00002592', + "blk14;": '\U00002591', + "blk34;": '\U00002593', + "block;": '\U00002588', + "bnot;": '\U00002310', + "bopf;": '\U0001D553', + "bot;": '\U000022A5', + "bottom;": '\U000022A5', + "bowtie;": '\U000022C8', + "boxDL;": '\U00002557', + "boxDR;": '\U00002554', + "boxDl;": '\U00002556', + "boxDr;": '\U00002553', + "boxH;": '\U00002550', + "boxHD;": '\U00002566', + "boxHU;": '\U00002569', + "boxHd;": '\U00002564', + "boxHu;": '\U00002567', + "boxUL;": '\U0000255D', + "boxUR;": '\U0000255A', + "boxUl;": '\U0000255C', + "boxUr;": '\U00002559', + "boxV;": '\U00002551', + "boxVH;": '\U0000256C', + "boxVL;": '\U00002563', + "boxVR;": '\U00002560', + "boxVh;": '\U0000256B', + "boxVl;": '\U00002562', + "boxVr;": '\U0000255F', + "boxbox;": '\U000029C9', + "boxdL;": '\U00002555', + "boxdR;": '\U00002552', + "boxdl;": '\U00002510', + "boxdr;": '\U0000250C', + "boxh;": '\U00002500', + "boxhD;": '\U00002565', + "boxhU;": '\U00002568', + "boxhd;": '\U0000252C', + "boxhu;": '\U00002534', + "boxminus;": '\U0000229F', + "boxplus;": '\U0000229E', + "boxtimes;": '\U000022A0', + "boxuL;": '\U0000255B', + "boxuR;": '\U00002558', + "boxul;": '\U00002518', + "boxur;": '\U00002514', + "boxv;": '\U00002502', + "boxvH;": '\U0000256A', + "boxvL;": '\U00002561', + "boxvR;": '\U0000255E', + "boxvh;": '\U0000253C', + "boxvl;": '\U00002524', + "boxvr;": '\U0000251C', + "bprime;": '\U00002035', + "breve;": '\U000002D8', + "brvbar;": '\U000000A6', + "bscr;": '\U0001D4B7', + "bsemi;": '\U0000204F', + "bsim;": '\U0000223D', + "bsime;": '\U000022CD', + "bsol;": '\U0000005C', + "bsolb;": '\U000029C5', + "bsolhsub;": '\U000027C8', + "bull;": '\U00002022', + "bullet;": '\U00002022', + "bump;": '\U0000224E', + "bumpE;": '\U00002AAE', + "bumpe;": '\U0000224F', + "bumpeq;": '\U0000224F', + "cacute;": '\U00000107', + "cap;": '\U00002229', + "capand;": '\U00002A44', + "capbrcup;": '\U00002A49', + "capcap;": '\U00002A4B', + "capcup;": '\U00002A47', + "capdot;": '\U00002A40', + "caret;": '\U00002041', + "caron;": '\U000002C7', + "ccaps;": '\U00002A4D', + "ccaron;": '\U0000010D', + "ccedil;": '\U000000E7', + "ccirc;": '\U00000109', + "ccups;": '\U00002A4C', + "ccupssm;": '\U00002A50', + "cdot;": '\U0000010B', + "cedil;": '\U000000B8', + "cemptyv;": '\U000029B2', + "cent;": '\U000000A2', + "centerdot;": '\U000000B7', + "cfr;": '\U0001D520', + "chcy;": '\U00000447', + "check;": '\U00002713', + "checkmark;": '\U00002713', + "chi;": '\U000003C7', + "cir;": '\U000025CB', + "cirE;": '\U000029C3', + "circ;": '\U000002C6', + "circeq;": '\U00002257', + "circlearrowleft;": '\U000021BA', + "circlearrowright;": '\U000021BB', + "circledR;": '\U000000AE', + "circledS;": '\U000024C8', + "circledast;": '\U0000229B', + "circledcirc;": '\U0000229A', + "circleddash;": '\U0000229D', + "cire;": '\U00002257', + "cirfnint;": '\U00002A10', + "cirmid;": '\U00002AEF', + "cirscir;": '\U000029C2', + "clubs;": '\U00002663', + "clubsuit;": '\U00002663', + "colon;": '\U0000003A', + "colone;": '\U00002254', + "coloneq;": '\U00002254', + "comma;": '\U0000002C', + "commat;": '\U00000040', + "comp;": '\U00002201', + "compfn;": '\U00002218', + "complement;": '\U00002201', + "complexes;": '\U00002102', + "cong;": '\U00002245', + "congdot;": '\U00002A6D', + "conint;": '\U0000222E', + "copf;": '\U0001D554', + "coprod;": '\U00002210', + "copy;": '\U000000A9', + "copysr;": '\U00002117', + "crarr;": '\U000021B5', + "cross;": '\U00002717', + "cscr;": '\U0001D4B8', + "csub;": '\U00002ACF', + "csube;": '\U00002AD1', + "csup;": '\U00002AD0', + "csupe;": '\U00002AD2', + "ctdot;": '\U000022EF', + "cudarrl;": '\U00002938', + "cudarrr;": '\U00002935', + "cuepr;": '\U000022DE', + "cuesc;": '\U000022DF', + "cularr;": '\U000021B6', + "cularrp;": '\U0000293D', + "cup;": '\U0000222A', + "cupbrcap;": '\U00002A48', + "cupcap;": '\U00002A46', + "cupcup;": '\U00002A4A', + "cupdot;": '\U0000228D', + "cupor;": '\U00002A45', + "curarr;": '\U000021B7', + "curarrm;": '\U0000293C', + "curlyeqprec;": '\U000022DE', + "curlyeqsucc;": '\U000022DF', + "curlyvee;": '\U000022CE', + "curlywedge;": '\U000022CF', + "curren;": '\U000000A4', + "curvearrowleft;": '\U000021B6', + "curvearrowright;": '\U000021B7', + "cuvee;": '\U000022CE', + "cuwed;": '\U000022CF', + "cwconint;": '\U00002232', + "cwint;": '\U00002231', + "cylcty;": '\U0000232D', + "dArr;": '\U000021D3', + "dHar;": '\U00002965', + "dagger;": '\U00002020', + "daleth;": '\U00002138', + "darr;": '\U00002193', + "dash;": '\U00002010', + "dashv;": '\U000022A3', + "dbkarow;": '\U0000290F', + "dblac;": '\U000002DD', + "dcaron;": '\U0000010F', + "dcy;": '\U00000434', + "dd;": '\U00002146', + "ddagger;": '\U00002021', + "ddarr;": '\U000021CA', + "ddotseq;": '\U00002A77', + "deg;": '\U000000B0', + "delta;": '\U000003B4', + "demptyv;": '\U000029B1', + "dfisht;": '\U0000297F', + "dfr;": '\U0001D521', + "dharl;": '\U000021C3', + "dharr;": '\U000021C2', + "diam;": '\U000022C4', + "diamond;": '\U000022C4', + "diamondsuit;": '\U00002666', + "diams;": '\U00002666', + "die;": '\U000000A8', + "digamma;": '\U000003DD', + "disin;": '\U000022F2', + "div;": '\U000000F7', + "divide;": '\U000000F7', + "divideontimes;": '\U000022C7', + "divonx;": '\U000022C7', + "djcy;": '\U00000452', + "dlcorn;": '\U0000231E', + "dlcrop;": '\U0000230D', + "dollar;": '\U00000024', + "dopf;": '\U0001D555', + "dot;": '\U000002D9', + "doteq;": '\U00002250', + "doteqdot;": '\U00002251', + "dotminus;": '\U00002238', + "dotplus;": '\U00002214', + "dotsquare;": '\U000022A1', + "doublebarwedge;": '\U00002306', + "downarrow;": '\U00002193', + "downdownarrows;": '\U000021CA', + "downharpoonleft;": '\U000021C3', + "downharpoonright;": '\U000021C2', + "drbkarow;": '\U00002910', + "drcorn;": '\U0000231F', + "drcrop;": '\U0000230C', + "dscr;": '\U0001D4B9', + "dscy;": '\U00000455', + "dsol;": '\U000029F6', + "dstrok;": '\U00000111', + "dtdot;": '\U000022F1', + "dtri;": '\U000025BF', + "dtrif;": '\U000025BE', + "duarr;": '\U000021F5', + "duhar;": '\U0000296F', + "dwangle;": '\U000029A6', + "dzcy;": '\U0000045F', + "dzigrarr;": '\U000027FF', + "eDDot;": '\U00002A77', + "eDot;": '\U00002251', + "eacute;": '\U000000E9', + "easter;": '\U00002A6E', + "ecaron;": '\U0000011B', + "ecir;": '\U00002256', + "ecirc;": '\U000000EA', + "ecolon;": '\U00002255', + "ecy;": '\U0000044D', + "edot;": '\U00000117', + "ee;": '\U00002147', + "efDot;": '\U00002252', + "efr;": '\U0001D522', + "eg;": '\U00002A9A', + "egrave;": '\U000000E8', + "egs;": '\U00002A96', + "egsdot;": '\U00002A98', + "el;": '\U00002A99', + "elinters;": '\U000023E7', + "ell;": '\U00002113', + "els;": '\U00002A95', + "elsdot;": '\U00002A97', + "emacr;": '\U00000113', + "empty;": '\U00002205', + "emptyset;": '\U00002205', + "emptyv;": '\U00002205', + "emsp;": '\U00002003', + "emsp13;": '\U00002004', + "emsp14;": '\U00002005', + "eng;": '\U0000014B', + "ensp;": '\U00002002', + "eogon;": '\U00000119', + "eopf;": '\U0001D556', + "epar;": '\U000022D5', + "eparsl;": '\U000029E3', + "eplus;": '\U00002A71', + "epsi;": '\U000003B5', + "epsilon;": '\U000003B5', + "epsiv;": '\U000003F5', + "eqcirc;": '\U00002256', + "eqcolon;": '\U00002255', + "eqsim;": '\U00002242', + "eqslantgtr;": '\U00002A96', + "eqslantless;": '\U00002A95', + "equals;": '\U0000003D', + "equest;": '\U0000225F', + "equiv;": '\U00002261', + "equivDD;": '\U00002A78', + "eqvparsl;": '\U000029E5', + "erDot;": '\U00002253', + "erarr;": '\U00002971', + "escr;": '\U0000212F', + "esdot;": '\U00002250', + "esim;": '\U00002242', + "eta;": '\U000003B7', + "eth;": '\U000000F0', + "euml;": '\U000000EB', + "euro;": '\U000020AC', + "excl;": '\U00000021', + "exist;": '\U00002203', + "expectation;": '\U00002130', + "exponentiale;": '\U00002147', + "fallingdotseq;": '\U00002252', + "fcy;": '\U00000444', + "female;": '\U00002640', + "ffilig;": '\U0000FB03', + "fflig;": '\U0000FB00', + "ffllig;": '\U0000FB04', + "ffr;": '\U0001D523', + "filig;": '\U0000FB01', + "flat;": '\U0000266D', + "fllig;": '\U0000FB02', + "fltns;": '\U000025B1', + "fnof;": '\U00000192', + "fopf;": '\U0001D557', + "forall;": '\U00002200', + "fork;": '\U000022D4', + "forkv;": '\U00002AD9', + "fpartint;": '\U00002A0D', + "frac12;": '\U000000BD', + "frac13;": '\U00002153', + "frac14;": '\U000000BC', + "frac15;": '\U00002155', + "frac16;": '\U00002159', + "frac18;": '\U0000215B', + "frac23;": '\U00002154', + "frac25;": '\U00002156', + "frac34;": '\U000000BE', + "frac35;": '\U00002157', + "frac38;": '\U0000215C', + "frac45;": '\U00002158', + "frac56;": '\U0000215A', + "frac58;": '\U0000215D', + "frac78;": '\U0000215E', + "frasl;": '\U00002044', + "frown;": '\U00002322', + "fscr;": '\U0001D4BB', + "gE;": '\U00002267', + "gEl;": '\U00002A8C', + "gacute;": '\U000001F5', + "gamma;": '\U000003B3', + "gammad;": '\U000003DD', + "gap;": '\U00002A86', + "gbreve;": '\U0000011F', + "gcirc;": '\U0000011D', + "gcy;": '\U00000433', + "gdot;": '\U00000121', + "ge;": '\U00002265', + "gel;": '\U000022DB', + "geq;": '\U00002265', + "geqq;": '\U00002267', + "geqslant;": '\U00002A7E', + "ges;": '\U00002A7E', + "gescc;": '\U00002AA9', + "gesdot;": '\U00002A80', + "gesdoto;": '\U00002A82', + "gesdotol;": '\U00002A84', + "gesles;": '\U00002A94', + "gfr;": '\U0001D524', + "gg;": '\U0000226B', + "ggg;": '\U000022D9', + "gimel;": '\U00002137', + "gjcy;": '\U00000453', + "gl;": '\U00002277', + "glE;": '\U00002A92', + "gla;": '\U00002AA5', + "glj;": '\U00002AA4', + "gnE;": '\U00002269', + "gnap;": '\U00002A8A', + "gnapprox;": '\U00002A8A', + "gne;": '\U00002A88', + "gneq;": '\U00002A88', + "gneqq;": '\U00002269', + "gnsim;": '\U000022E7', + "gopf;": '\U0001D558', + "grave;": '\U00000060', + "gscr;": '\U0000210A', + "gsim;": '\U00002273', + "gsime;": '\U00002A8E', + "gsiml;": '\U00002A90', + "gt;": '\U0000003E', + "gtcc;": '\U00002AA7', + "gtcir;": '\U00002A7A', + "gtdot;": '\U000022D7', + "gtlPar;": '\U00002995', + "gtquest;": '\U00002A7C', + "gtrapprox;": '\U00002A86', + "gtrarr;": '\U00002978', + "gtrdot;": '\U000022D7', + "gtreqless;": '\U000022DB', + "gtreqqless;": '\U00002A8C', + "gtrless;": '\U00002277', + "gtrsim;": '\U00002273', + "hArr;": '\U000021D4', + "hairsp;": '\U0000200A', + "half;": '\U000000BD', + "hamilt;": '\U0000210B', + "hardcy;": '\U0000044A', + "harr;": '\U00002194', + "harrcir;": '\U00002948', + "harrw;": '\U000021AD', + "hbar;": '\U0000210F', + "hcirc;": '\U00000125', + "hearts;": '\U00002665', + "heartsuit;": '\U00002665', + "hellip;": '\U00002026', + "hercon;": '\U000022B9', + "hfr;": '\U0001D525', + "hksearow;": '\U00002925', + "hkswarow;": '\U00002926', + "hoarr;": '\U000021FF', + "homtht;": '\U0000223B', + "hookleftarrow;": '\U000021A9', + "hookrightarrow;": '\U000021AA', + "hopf;": '\U0001D559', + "horbar;": '\U00002015', + "hscr;": '\U0001D4BD', + "hslash;": '\U0000210F', + "hstrok;": '\U00000127', + "hybull;": '\U00002043', + "hyphen;": '\U00002010', + "iacute;": '\U000000ED', + "ic;": '\U00002063', + "icirc;": '\U000000EE', + "icy;": '\U00000438', + "iecy;": '\U00000435', + "iexcl;": '\U000000A1', + "iff;": '\U000021D4', + "ifr;": '\U0001D526', + "igrave;": '\U000000EC', + "ii;": '\U00002148', + "iiiint;": '\U00002A0C', + "iiint;": '\U0000222D', + "iinfin;": '\U000029DC', + "iiota;": '\U00002129', + "ijlig;": '\U00000133', + "imacr;": '\U0000012B', + "image;": '\U00002111', + "imagline;": '\U00002110', + "imagpart;": '\U00002111', + "imath;": '\U00000131', + "imof;": '\U000022B7', + "imped;": '\U000001B5', + "in;": '\U00002208', + "incare;": '\U00002105', + "infin;": '\U0000221E', + "infintie;": '\U000029DD', + "inodot;": '\U00000131', + "int;": '\U0000222B', + "intcal;": '\U000022BA', + "integers;": '\U00002124', + "intercal;": '\U000022BA', + "intlarhk;": '\U00002A17', + "intprod;": '\U00002A3C', + "iocy;": '\U00000451', + "iogon;": '\U0000012F', + "iopf;": '\U0001D55A', + "iota;": '\U000003B9', + "iprod;": '\U00002A3C', + "iquest;": '\U000000BF', + "iscr;": '\U0001D4BE', + "isin;": '\U00002208', + "isinE;": '\U000022F9', + "isindot;": '\U000022F5', + "isins;": '\U000022F4', + "isinsv;": '\U000022F3', + "isinv;": '\U00002208', + "it;": '\U00002062', + "itilde;": '\U00000129', + "iukcy;": '\U00000456', + "iuml;": '\U000000EF', + "jcirc;": '\U00000135', + "jcy;": '\U00000439', + "jfr;": '\U0001D527', + "jmath;": '\U00000237', + "jopf;": '\U0001D55B', + "jscr;": '\U0001D4BF', + "jsercy;": '\U00000458', + "jukcy;": '\U00000454', + "kappa;": '\U000003BA', + "kappav;": '\U000003F0', + "kcedil;": '\U00000137', + "kcy;": '\U0000043A', + "kfr;": '\U0001D528', + "kgreen;": '\U00000138', + "khcy;": '\U00000445', + "kjcy;": '\U0000045C', + "kopf;": '\U0001D55C', + "kscr;": '\U0001D4C0', + "lAarr;": '\U000021DA', + "lArr;": '\U000021D0', + "lAtail;": '\U0000291B', + "lBarr;": '\U0000290E', + "lE;": '\U00002266', + "lEg;": '\U00002A8B', + "lHar;": '\U00002962', + "lacute;": '\U0000013A', + "laemptyv;": '\U000029B4', + "lagran;": '\U00002112', + "lambda;": '\U000003BB', + "lang;": '\U000027E8', + "langd;": '\U00002991', + "langle;": '\U000027E8', + "lap;": '\U00002A85', + "laquo;": '\U000000AB', + "larr;": '\U00002190', + "larrb;": '\U000021E4', + "larrbfs;": '\U0000291F', + "larrfs;": '\U0000291D', + "larrhk;": '\U000021A9', + "larrlp;": '\U000021AB', + "larrpl;": '\U00002939', + "larrsim;": '\U00002973', + "larrtl;": '\U000021A2', + "lat;": '\U00002AAB', + "latail;": '\U00002919', + "late;": '\U00002AAD', + "lbarr;": '\U0000290C', + "lbbrk;": '\U00002772', + "lbrace;": '\U0000007B', + "lbrack;": '\U0000005B', + "lbrke;": '\U0000298B', + "lbrksld;": '\U0000298F', + "lbrkslu;": '\U0000298D', + "lcaron;": '\U0000013E', + "lcedil;": '\U0000013C', + "lceil;": '\U00002308', + "lcub;": '\U0000007B', + "lcy;": '\U0000043B', + "ldca;": '\U00002936', + "ldquo;": '\U0000201C', + "ldquor;": '\U0000201E', + "ldrdhar;": '\U00002967', + "ldrushar;": '\U0000294B', + "ldsh;": '\U000021B2', + "le;": '\U00002264', + "leftarrow;": '\U00002190', + "leftarrowtail;": '\U000021A2', + "leftharpoondown;": '\U000021BD', + "leftharpoonup;": '\U000021BC', + "leftleftarrows;": '\U000021C7', + "leftrightarrow;": '\U00002194', + "leftrightarrows;": '\U000021C6', + "leftrightharpoons;": '\U000021CB', + "leftrightsquigarrow;": '\U000021AD', + "leftthreetimes;": '\U000022CB', + "leg;": '\U000022DA', + "leq;": '\U00002264', + "leqq;": '\U00002266', + "leqslant;": '\U00002A7D', + "les;": '\U00002A7D', + "lescc;": '\U00002AA8', + "lesdot;": '\U00002A7F', + "lesdoto;": '\U00002A81', + "lesdotor;": '\U00002A83', + "lesges;": '\U00002A93', + "lessapprox;": '\U00002A85', + "lessdot;": '\U000022D6', + "lesseqgtr;": '\U000022DA', + "lesseqqgtr;": '\U00002A8B', + "lessgtr;": '\U00002276', + "lesssim;": '\U00002272', + "lfisht;": '\U0000297C', + "lfloor;": '\U0000230A', + "lfr;": '\U0001D529', + "lg;": '\U00002276', + "lgE;": '\U00002A91', + "lhard;": '\U000021BD', + "lharu;": '\U000021BC', + "lharul;": '\U0000296A', + "lhblk;": '\U00002584', + "ljcy;": '\U00000459', + "ll;": '\U0000226A', + "llarr;": '\U000021C7', + "llcorner;": '\U0000231E', + "llhard;": '\U0000296B', + "lltri;": '\U000025FA', + "lmidot;": '\U00000140', + "lmoust;": '\U000023B0', + "lmoustache;": '\U000023B0', + "lnE;": '\U00002268', + "lnap;": '\U00002A89', + "lnapprox;": '\U00002A89', + "lne;": '\U00002A87', + "lneq;": '\U00002A87', + "lneqq;": '\U00002268', + "lnsim;": '\U000022E6', + "loang;": '\U000027EC', + "loarr;": '\U000021FD', + "lobrk;": '\U000027E6', + "longleftarrow;": '\U000027F5', + "longleftrightarrow;": '\U000027F7', + "longmapsto;": '\U000027FC', + "longrightarrow;": '\U000027F6', + "looparrowleft;": '\U000021AB', + "looparrowright;": '\U000021AC', + "lopar;": '\U00002985', + "lopf;": '\U0001D55D', + "loplus;": '\U00002A2D', + "lotimes;": '\U00002A34', + "lowast;": '\U00002217', + "lowbar;": '\U0000005F', + "loz;": '\U000025CA', + "lozenge;": '\U000025CA', + "lozf;": '\U000029EB', + "lpar;": '\U00000028', + "lparlt;": '\U00002993', + "lrarr;": '\U000021C6', + "lrcorner;": '\U0000231F', + "lrhar;": '\U000021CB', + "lrhard;": '\U0000296D', + "lrm;": '\U0000200E', + "lrtri;": '\U000022BF', + "lsaquo;": '\U00002039', + "lscr;": '\U0001D4C1', + "lsh;": '\U000021B0', + "lsim;": '\U00002272', + "lsime;": '\U00002A8D', + "lsimg;": '\U00002A8F', + "lsqb;": '\U0000005B', + "lsquo;": '\U00002018', + "lsquor;": '\U0000201A', + "lstrok;": '\U00000142', + "lt;": '\U0000003C', + "ltcc;": '\U00002AA6', + "ltcir;": '\U00002A79', + "ltdot;": '\U000022D6', + "lthree;": '\U000022CB', + "ltimes;": '\U000022C9', + "ltlarr;": '\U00002976', + "ltquest;": '\U00002A7B', + "ltrPar;": '\U00002996', + "ltri;": '\U000025C3', + "ltrie;": '\U000022B4', + "ltrif;": '\U000025C2', + "lurdshar;": '\U0000294A', + "luruhar;": '\U00002966', + "mDDot;": '\U0000223A', + "macr;": '\U000000AF', + "male;": '\U00002642', + "malt;": '\U00002720', + "maltese;": '\U00002720', + "map;": '\U000021A6', + "mapsto;": '\U000021A6', + "mapstodown;": '\U000021A7', + "mapstoleft;": '\U000021A4', + "mapstoup;": '\U000021A5', + "marker;": '\U000025AE', + "mcomma;": '\U00002A29', + "mcy;": '\U0000043C', + "mdash;": '\U00002014', + "measuredangle;": '\U00002221', + "mfr;": '\U0001D52A', + "mho;": '\U00002127', + "micro;": '\U000000B5', + "mid;": '\U00002223', + "midast;": '\U0000002A', + "midcir;": '\U00002AF0', + "middot;": '\U000000B7', + "minus;": '\U00002212', + "minusb;": '\U0000229F', + "minusd;": '\U00002238', + "minusdu;": '\U00002A2A', + "mlcp;": '\U00002ADB', + "mldr;": '\U00002026', + "mnplus;": '\U00002213', + "models;": '\U000022A7', + "mopf;": '\U0001D55E', + "mp;": '\U00002213', + "mscr;": '\U0001D4C2', + "mstpos;": '\U0000223E', + "mu;": '\U000003BC', + "multimap;": '\U000022B8', + "mumap;": '\U000022B8', + "nLeftarrow;": '\U000021CD', + "nLeftrightarrow;": '\U000021CE', + "nRightarrow;": '\U000021CF', + "nVDash;": '\U000022AF', + "nVdash;": '\U000022AE', + "nabla;": '\U00002207', + "nacute;": '\U00000144', + "nap;": '\U00002249', + "napos;": '\U00000149', + "napprox;": '\U00002249', + "natur;": '\U0000266E', + "natural;": '\U0000266E', + "naturals;": '\U00002115', + "nbsp;": '\U000000A0', + "ncap;": '\U00002A43', + "ncaron;": '\U00000148', + "ncedil;": '\U00000146', + "ncong;": '\U00002247', + "ncup;": '\U00002A42', + "ncy;": '\U0000043D', + "ndash;": '\U00002013', + "ne;": '\U00002260', + "neArr;": '\U000021D7', + "nearhk;": '\U00002924', + "nearr;": '\U00002197', + "nearrow;": '\U00002197', + "nequiv;": '\U00002262', + "nesear;": '\U00002928', + "nexist;": '\U00002204', + "nexists;": '\U00002204', + "nfr;": '\U0001D52B', + "nge;": '\U00002271', + "ngeq;": '\U00002271', + "ngsim;": '\U00002275', + "ngt;": '\U0000226F', + "ngtr;": '\U0000226F', + "nhArr;": '\U000021CE', + "nharr;": '\U000021AE', + "nhpar;": '\U00002AF2', + "ni;": '\U0000220B', + "nis;": '\U000022FC', + "nisd;": '\U000022FA', + "niv;": '\U0000220B', + "njcy;": '\U0000045A', + "nlArr;": '\U000021CD', + "nlarr;": '\U0000219A', + "nldr;": '\U00002025', + "nle;": '\U00002270', + "nleftarrow;": '\U0000219A', + "nleftrightarrow;": '\U000021AE', + "nleq;": '\U00002270', + "nless;": '\U0000226E', + "nlsim;": '\U00002274', + "nlt;": '\U0000226E', + "nltri;": '\U000022EA', + "nltrie;": '\U000022EC', + "nmid;": '\U00002224', + "nopf;": '\U0001D55F', + "not;": '\U000000AC', + "notin;": '\U00002209', + "notinva;": '\U00002209', + "notinvb;": '\U000022F7', + "notinvc;": '\U000022F6', + "notni;": '\U0000220C', + "notniva;": '\U0000220C', + "notnivb;": '\U000022FE', + "notnivc;": '\U000022FD', + "npar;": '\U00002226', + "nparallel;": '\U00002226', + "npolint;": '\U00002A14', + "npr;": '\U00002280', + "nprcue;": '\U000022E0', + "nprec;": '\U00002280', + "nrArr;": '\U000021CF', + "nrarr;": '\U0000219B', + "nrightarrow;": '\U0000219B', + "nrtri;": '\U000022EB', + "nrtrie;": '\U000022ED', + "nsc;": '\U00002281', + "nsccue;": '\U000022E1', + "nscr;": '\U0001D4C3', + "nshortmid;": '\U00002224', + "nshortparallel;": '\U00002226', + "nsim;": '\U00002241', + "nsime;": '\U00002244', + "nsimeq;": '\U00002244', + "nsmid;": '\U00002224', + "nspar;": '\U00002226', + "nsqsube;": '\U000022E2', + "nsqsupe;": '\U000022E3', + "nsub;": '\U00002284', + "nsube;": '\U00002288', + "nsubseteq;": '\U00002288', + "nsucc;": '\U00002281', + "nsup;": '\U00002285', + "nsupe;": '\U00002289', + "nsupseteq;": '\U00002289', + "ntgl;": '\U00002279', + "ntilde;": '\U000000F1', + "ntlg;": '\U00002278', + "ntriangleleft;": '\U000022EA', + "ntrianglelefteq;": '\U000022EC', + "ntriangleright;": '\U000022EB', + "ntrianglerighteq;": '\U000022ED', + "nu;": '\U000003BD', + "num;": '\U00000023', + "numero;": '\U00002116', + "numsp;": '\U00002007', + "nvDash;": '\U000022AD', + "nvHarr;": '\U00002904', + "nvdash;": '\U000022AC', + "nvinfin;": '\U000029DE', + "nvlArr;": '\U00002902', + "nvrArr;": '\U00002903', + "nwArr;": '\U000021D6', + "nwarhk;": '\U00002923', + "nwarr;": '\U00002196', + "nwarrow;": '\U00002196', + "nwnear;": '\U00002927', + "oS;": '\U000024C8', + "oacute;": '\U000000F3', + "oast;": '\U0000229B', + "ocir;": '\U0000229A', + "ocirc;": '\U000000F4', + "ocy;": '\U0000043E', + "odash;": '\U0000229D', + "odblac;": '\U00000151', + "odiv;": '\U00002A38', + "odot;": '\U00002299', + "odsold;": '\U000029BC', + "oelig;": '\U00000153', + "ofcir;": '\U000029BF', + "ofr;": '\U0001D52C', + "ogon;": '\U000002DB', + "ograve;": '\U000000F2', + "ogt;": '\U000029C1', + "ohbar;": '\U000029B5', + "ohm;": '\U000003A9', + "oint;": '\U0000222E', + "olarr;": '\U000021BA', + "olcir;": '\U000029BE', + "olcross;": '\U000029BB', + "oline;": '\U0000203E', + "olt;": '\U000029C0', + "omacr;": '\U0000014D', + "omega;": '\U000003C9', + "omicron;": '\U000003BF', + "omid;": '\U000029B6', + "ominus;": '\U00002296', + "oopf;": '\U0001D560', + "opar;": '\U000029B7', + "operp;": '\U000029B9', + "oplus;": '\U00002295', + "or;": '\U00002228', + "orarr;": '\U000021BB', + "ord;": '\U00002A5D', + "order;": '\U00002134', + "orderof;": '\U00002134', + "ordf;": '\U000000AA', + "ordm;": '\U000000BA', + "origof;": '\U000022B6', + "oror;": '\U00002A56', + "orslope;": '\U00002A57', + "orv;": '\U00002A5B', + "oscr;": '\U00002134', + "oslash;": '\U000000F8', + "osol;": '\U00002298', + "otilde;": '\U000000F5', + "otimes;": '\U00002297', + "otimesas;": '\U00002A36', + "ouml;": '\U000000F6', + "ovbar;": '\U0000233D', + "par;": '\U00002225', + "para;": '\U000000B6', + "parallel;": '\U00002225', + "parsim;": '\U00002AF3', + "parsl;": '\U00002AFD', + "part;": '\U00002202', + "pcy;": '\U0000043F', + "percnt;": '\U00000025', + "period;": '\U0000002E', + "permil;": '\U00002030', + "perp;": '\U000022A5', + "pertenk;": '\U00002031', + "pfr;": '\U0001D52D', + "phi;": '\U000003C6', + "phiv;": '\U000003D5', + "phmmat;": '\U00002133', + "phone;": '\U0000260E', + "pi;": '\U000003C0', + "pitchfork;": '\U000022D4', + "piv;": '\U000003D6', + "planck;": '\U0000210F', + "planckh;": '\U0000210E', + "plankv;": '\U0000210F', + "plus;": '\U0000002B', + "plusacir;": '\U00002A23', + "plusb;": '\U0000229E', + "pluscir;": '\U00002A22', + "plusdo;": '\U00002214', + "plusdu;": '\U00002A25', + "pluse;": '\U00002A72', + "plusmn;": '\U000000B1', + "plussim;": '\U00002A26', + "plustwo;": '\U00002A27', + "pm;": '\U000000B1', + "pointint;": '\U00002A15', + "popf;": '\U0001D561', + "pound;": '\U000000A3', + "pr;": '\U0000227A', + "prE;": '\U00002AB3', + "prap;": '\U00002AB7', + "prcue;": '\U0000227C', + "pre;": '\U00002AAF', + "prec;": '\U0000227A', + "precapprox;": '\U00002AB7', + "preccurlyeq;": '\U0000227C', + "preceq;": '\U00002AAF', + "precnapprox;": '\U00002AB9', + "precneqq;": '\U00002AB5', + "precnsim;": '\U000022E8', + "precsim;": '\U0000227E', + "prime;": '\U00002032', + "primes;": '\U00002119', + "prnE;": '\U00002AB5', + "prnap;": '\U00002AB9', + "prnsim;": '\U000022E8', + "prod;": '\U0000220F', + "profalar;": '\U0000232E', + "profline;": '\U00002312', + "profsurf;": '\U00002313', + "prop;": '\U0000221D', + "propto;": '\U0000221D', + "prsim;": '\U0000227E', + "prurel;": '\U000022B0', + "pscr;": '\U0001D4C5', + "psi;": '\U000003C8', + "puncsp;": '\U00002008', + "qfr;": '\U0001D52E', + "qint;": '\U00002A0C', + "qopf;": '\U0001D562', + "qprime;": '\U00002057', + "qscr;": '\U0001D4C6', + "quaternions;": '\U0000210D', + "quatint;": '\U00002A16', + "quest;": '\U0000003F', + "questeq;": '\U0000225F', + "quot;": '\U00000022', + "rAarr;": '\U000021DB', + "rArr;": '\U000021D2', + "rAtail;": '\U0000291C', + "rBarr;": '\U0000290F', + "rHar;": '\U00002964', + "racute;": '\U00000155', + "radic;": '\U0000221A', + "raemptyv;": '\U000029B3', + "rang;": '\U000027E9', + "rangd;": '\U00002992', + "range;": '\U000029A5', + "rangle;": '\U000027E9', + "raquo;": '\U000000BB', + "rarr;": '\U00002192', + "rarrap;": '\U00002975', + "rarrb;": '\U000021E5', + "rarrbfs;": '\U00002920', + "rarrc;": '\U00002933', + "rarrfs;": '\U0000291E', + "rarrhk;": '\U000021AA', + "rarrlp;": '\U000021AC', + "rarrpl;": '\U00002945', + "rarrsim;": '\U00002974', + "rarrtl;": '\U000021A3', + "rarrw;": '\U0000219D', + "ratail;": '\U0000291A', + "ratio;": '\U00002236', + "rationals;": '\U0000211A', + "rbarr;": '\U0000290D', + "rbbrk;": '\U00002773', + "rbrace;": '\U0000007D', + "rbrack;": '\U0000005D', + "rbrke;": '\U0000298C', + "rbrksld;": '\U0000298E', + "rbrkslu;": '\U00002990', + "rcaron;": '\U00000159', + "rcedil;": '\U00000157', + "rceil;": '\U00002309', + "rcub;": '\U0000007D', + "rcy;": '\U00000440', + "rdca;": '\U00002937', + "rdldhar;": '\U00002969', + "rdquo;": '\U0000201D', + "rdquor;": '\U0000201D', + "rdsh;": '\U000021B3', + "real;": '\U0000211C', + "realine;": '\U0000211B', + "realpart;": '\U0000211C', + "reals;": '\U0000211D', + "rect;": '\U000025AD', + "reg;": '\U000000AE', + "rfisht;": '\U0000297D', + "rfloor;": '\U0000230B', + "rfr;": '\U0001D52F', + "rhard;": '\U000021C1', + "rharu;": '\U000021C0', + "rharul;": '\U0000296C', + "rho;": '\U000003C1', + "rhov;": '\U000003F1', + "rightarrow;": '\U00002192', + "rightarrowtail;": '\U000021A3', + "rightharpoondown;": '\U000021C1', + "rightharpoonup;": '\U000021C0', + "rightleftarrows;": '\U000021C4', + "rightleftharpoons;": '\U000021CC', + "rightrightarrows;": '\U000021C9', + "rightsquigarrow;": '\U0000219D', + "rightthreetimes;": '\U000022CC', + "ring;": '\U000002DA', + "risingdotseq;": '\U00002253', + "rlarr;": '\U000021C4', + "rlhar;": '\U000021CC', + "rlm;": '\U0000200F', + "rmoust;": '\U000023B1', + "rmoustache;": '\U000023B1', + "rnmid;": '\U00002AEE', + "roang;": '\U000027ED', + "roarr;": '\U000021FE', + "robrk;": '\U000027E7', + "ropar;": '\U00002986', + "ropf;": '\U0001D563', + "roplus;": '\U00002A2E', + "rotimes;": '\U00002A35', + "rpar;": '\U00000029', + "rpargt;": '\U00002994', + "rppolint;": '\U00002A12', + "rrarr;": '\U000021C9', + "rsaquo;": '\U0000203A', + "rscr;": '\U0001D4C7', + "rsh;": '\U000021B1', + "rsqb;": '\U0000005D', + "rsquo;": '\U00002019', + "rsquor;": '\U00002019', + "rthree;": '\U000022CC', + "rtimes;": '\U000022CA', + "rtri;": '\U000025B9', + "rtrie;": '\U000022B5', + "rtrif;": '\U000025B8', + "rtriltri;": '\U000029CE', + "ruluhar;": '\U00002968', + "rx;": '\U0000211E', + "sacute;": '\U0000015B', + "sbquo;": '\U0000201A', + "sc;": '\U0000227B', + "scE;": '\U00002AB4', + "scap;": '\U00002AB8', + "scaron;": '\U00000161', + "sccue;": '\U0000227D', + "sce;": '\U00002AB0', + "scedil;": '\U0000015F', + "scirc;": '\U0000015D', + "scnE;": '\U00002AB6', + "scnap;": '\U00002ABA', + "scnsim;": '\U000022E9', + "scpolint;": '\U00002A13', + "scsim;": '\U0000227F', + "scy;": '\U00000441', + "sdot;": '\U000022C5', + "sdotb;": '\U000022A1', + "sdote;": '\U00002A66', + "seArr;": '\U000021D8', + "searhk;": '\U00002925', + "searr;": '\U00002198', + "searrow;": '\U00002198', + "sect;": '\U000000A7', + "semi;": '\U0000003B', + "seswar;": '\U00002929', + "setminus;": '\U00002216', + "setmn;": '\U00002216', + "sext;": '\U00002736', + "sfr;": '\U0001D530', + "sfrown;": '\U00002322', + "sharp;": '\U0000266F', + "shchcy;": '\U00000449', + "shcy;": '\U00000448', + "shortmid;": '\U00002223', + "shortparallel;": '\U00002225', + "shy;": '\U000000AD', + "sigma;": '\U000003C3', + "sigmaf;": '\U000003C2', + "sigmav;": '\U000003C2', + "sim;": '\U0000223C', + "simdot;": '\U00002A6A', + "sime;": '\U00002243', + "simeq;": '\U00002243', + "simg;": '\U00002A9E', + "simgE;": '\U00002AA0', + "siml;": '\U00002A9D', + "simlE;": '\U00002A9F', + "simne;": '\U00002246', + "simplus;": '\U00002A24', + "simrarr;": '\U00002972', + "slarr;": '\U00002190', + "smallsetminus;": '\U00002216', + "smashp;": '\U00002A33', + "smeparsl;": '\U000029E4', + "smid;": '\U00002223', + "smile;": '\U00002323', + "smt;": '\U00002AAA', + "smte;": '\U00002AAC', + "softcy;": '\U0000044C', + "sol;": '\U0000002F', + "solb;": '\U000029C4', + "solbar;": '\U0000233F', + "sopf;": '\U0001D564', + "spades;": '\U00002660', + "spadesuit;": '\U00002660', + "spar;": '\U00002225', + "sqcap;": '\U00002293', + "sqcup;": '\U00002294', + "sqsub;": '\U0000228F', + "sqsube;": '\U00002291', + "sqsubset;": '\U0000228F', + "sqsubseteq;": '\U00002291', + "sqsup;": '\U00002290', + "sqsupe;": '\U00002292', + "sqsupset;": '\U00002290', + "sqsupseteq;": '\U00002292', + "squ;": '\U000025A1', + "square;": '\U000025A1', + "squarf;": '\U000025AA', + "squf;": '\U000025AA', + "srarr;": '\U00002192', + "sscr;": '\U0001D4C8', + "ssetmn;": '\U00002216', + "ssmile;": '\U00002323', + "sstarf;": '\U000022C6', + "star;": '\U00002606', + "starf;": '\U00002605', + "straightepsilon;": '\U000003F5', + "straightphi;": '\U000003D5', + "strns;": '\U000000AF', + "sub;": '\U00002282', + "subE;": '\U00002AC5', + "subdot;": '\U00002ABD', + "sube;": '\U00002286', + "subedot;": '\U00002AC3', + "submult;": '\U00002AC1', + "subnE;": '\U00002ACB', + "subne;": '\U0000228A', + "subplus;": '\U00002ABF', + "subrarr;": '\U00002979', + "subset;": '\U00002282', + "subseteq;": '\U00002286', + "subseteqq;": '\U00002AC5', + "subsetneq;": '\U0000228A', + "subsetneqq;": '\U00002ACB', + "subsim;": '\U00002AC7', + "subsub;": '\U00002AD5', + "subsup;": '\U00002AD3', + "succ;": '\U0000227B', + "succapprox;": '\U00002AB8', + "succcurlyeq;": '\U0000227D', + "succeq;": '\U00002AB0', + "succnapprox;": '\U00002ABA', + "succneqq;": '\U00002AB6', + "succnsim;": '\U000022E9', + "succsim;": '\U0000227F', + "sum;": '\U00002211', + "sung;": '\U0000266A', + "sup;": '\U00002283', + "sup1;": '\U000000B9', + "sup2;": '\U000000B2', + "sup3;": '\U000000B3', + "supE;": '\U00002AC6', + "supdot;": '\U00002ABE', + "supdsub;": '\U00002AD8', + "supe;": '\U00002287', + "supedot;": '\U00002AC4', + "suphsol;": '\U000027C9', + "suphsub;": '\U00002AD7', + "suplarr;": '\U0000297B', + "supmult;": '\U00002AC2', + "supnE;": '\U00002ACC', + "supne;": '\U0000228B', + "supplus;": '\U00002AC0', + "supset;": '\U00002283', + "supseteq;": '\U00002287', + "supseteqq;": '\U00002AC6', + "supsetneq;": '\U0000228B', + "supsetneqq;": '\U00002ACC', + "supsim;": '\U00002AC8', + "supsub;": '\U00002AD4', + "supsup;": '\U00002AD6', + "swArr;": '\U000021D9', + "swarhk;": '\U00002926', + "swarr;": '\U00002199', + "swarrow;": '\U00002199', + "swnwar;": '\U0000292A', + "szlig;": '\U000000DF', + "target;": '\U00002316', + "tau;": '\U000003C4', + "tbrk;": '\U000023B4', + "tcaron;": '\U00000165', + "tcedil;": '\U00000163', + "tcy;": '\U00000442', + "tdot;": '\U000020DB', + "telrec;": '\U00002315', + "tfr;": '\U0001D531', + "there4;": '\U00002234', + "therefore;": '\U00002234', + "theta;": '\U000003B8', + "thetasym;": '\U000003D1', + "thetav;": '\U000003D1', + "thickapprox;": '\U00002248', + "thicksim;": '\U0000223C', + "thinsp;": '\U00002009', + "thkap;": '\U00002248', + "thksim;": '\U0000223C', + "thorn;": '\U000000FE', + "tilde;": '\U000002DC', + "times;": '\U000000D7', + "timesb;": '\U000022A0', + "timesbar;": '\U00002A31', + "timesd;": '\U00002A30', + "tint;": '\U0000222D', + "toea;": '\U00002928', + "top;": '\U000022A4', + "topbot;": '\U00002336', + "topcir;": '\U00002AF1', + "topf;": '\U0001D565', + "topfork;": '\U00002ADA', + "tosa;": '\U00002929', + "tprime;": '\U00002034', + "trade;": '\U00002122', + "triangle;": '\U000025B5', + "triangledown;": '\U000025BF', + "triangleleft;": '\U000025C3', + "trianglelefteq;": '\U000022B4', + "triangleq;": '\U0000225C', + "triangleright;": '\U000025B9', + "trianglerighteq;": '\U000022B5', + "tridot;": '\U000025EC', + "trie;": '\U0000225C', + "triminus;": '\U00002A3A', + "triplus;": '\U00002A39', + "trisb;": '\U000029CD', + "tritime;": '\U00002A3B', + "trpezium;": '\U000023E2', + "tscr;": '\U0001D4C9', + "tscy;": '\U00000446', + "tshcy;": '\U0000045B', + "tstrok;": '\U00000167', + "twixt;": '\U0000226C', + "twoheadleftarrow;": '\U0000219E', + "twoheadrightarrow;": '\U000021A0', + "uArr;": '\U000021D1', + "uHar;": '\U00002963', + "uacute;": '\U000000FA', + "uarr;": '\U00002191', + "ubrcy;": '\U0000045E', + "ubreve;": '\U0000016D', + "ucirc;": '\U000000FB', + "ucy;": '\U00000443', + "udarr;": '\U000021C5', + "udblac;": '\U00000171', + "udhar;": '\U0000296E', + "ufisht;": '\U0000297E', + "ufr;": '\U0001D532', + "ugrave;": '\U000000F9', + "uharl;": '\U000021BF', + "uharr;": '\U000021BE', + "uhblk;": '\U00002580', + "ulcorn;": '\U0000231C', + "ulcorner;": '\U0000231C', + "ulcrop;": '\U0000230F', + "ultri;": '\U000025F8', + "umacr;": '\U0000016B', + "uml;": '\U000000A8', + "uogon;": '\U00000173', + "uopf;": '\U0001D566', + "uparrow;": '\U00002191', + "updownarrow;": '\U00002195', + "upharpoonleft;": '\U000021BF', + "upharpoonright;": '\U000021BE', + "uplus;": '\U0000228E', + "upsi;": '\U000003C5', + "upsih;": '\U000003D2', + "upsilon;": '\U000003C5', + "upuparrows;": '\U000021C8', + "urcorn;": '\U0000231D', + "urcorner;": '\U0000231D', + "urcrop;": '\U0000230E', + "uring;": '\U0000016F', + "urtri;": '\U000025F9', + "uscr;": '\U0001D4CA', + "utdot;": '\U000022F0', + "utilde;": '\U00000169', + "utri;": '\U000025B5', + "utrif;": '\U000025B4', + "uuarr;": '\U000021C8', + "uuml;": '\U000000FC', + "uwangle;": '\U000029A7', + "vArr;": '\U000021D5', + "vBar;": '\U00002AE8', + "vBarv;": '\U00002AE9', + "vDash;": '\U000022A8', + "vangrt;": '\U0000299C', + "varepsilon;": '\U000003F5', + "varkappa;": '\U000003F0', + "varnothing;": '\U00002205', + "varphi;": '\U000003D5', + "varpi;": '\U000003D6', + "varpropto;": '\U0000221D', + "varr;": '\U00002195', + "varrho;": '\U000003F1', + "varsigma;": '\U000003C2', + "vartheta;": '\U000003D1', + "vartriangleleft;": '\U000022B2', + "vartriangleright;": '\U000022B3', + "vcy;": '\U00000432', + "vdash;": '\U000022A2', + "vee;": '\U00002228', + "veebar;": '\U000022BB', + "veeeq;": '\U0000225A', + "vellip;": '\U000022EE', + "verbar;": '\U0000007C', + "vert;": '\U0000007C', + "vfr;": '\U0001D533', + "vltri;": '\U000022B2', + "vopf;": '\U0001D567', + "vprop;": '\U0000221D', + "vrtri;": '\U000022B3', + "vscr;": '\U0001D4CB', + "vzigzag;": '\U0000299A', + "wcirc;": '\U00000175', + "wedbar;": '\U00002A5F', + "wedge;": '\U00002227', + "wedgeq;": '\U00002259', + "weierp;": '\U00002118', + "wfr;": '\U0001D534', + "wopf;": '\U0001D568', + "wp;": '\U00002118', + "wr;": '\U00002240', + "wreath;": '\U00002240', + "wscr;": '\U0001D4CC', + "xcap;": '\U000022C2', + "xcirc;": '\U000025EF', + "xcup;": '\U000022C3', + "xdtri;": '\U000025BD', + "xfr;": '\U0001D535', + "xhArr;": '\U000027FA', + "xharr;": '\U000027F7', + "xi;": '\U000003BE', + "xlArr;": '\U000027F8', + "xlarr;": '\U000027F5', + "xmap;": '\U000027FC', + "xnis;": '\U000022FB', + "xodot;": '\U00002A00', + "xopf;": '\U0001D569', + "xoplus;": '\U00002A01', + "xotime;": '\U00002A02', + "xrArr;": '\U000027F9', + "xrarr;": '\U000027F6', + "xscr;": '\U0001D4CD', + "xsqcup;": '\U00002A06', + "xuplus;": '\U00002A04', + "xutri;": '\U000025B3', + "xvee;": '\U000022C1', + "xwedge;": '\U000022C0', + "yacute;": '\U000000FD', + "yacy;": '\U0000044F', + "ycirc;": '\U00000177', + "ycy;": '\U0000044B', + "yen;": '\U000000A5', + "yfr;": '\U0001D536', + "yicy;": '\U00000457', + "yopf;": '\U0001D56A', + "yscr;": '\U0001D4CE', + "yucy;": '\U0000044E', + "yuml;": '\U000000FF', + "zacute;": '\U0000017A', + "zcaron;": '\U0000017E', + "zcy;": '\U00000437', + "zdot;": '\U0000017C', + "zeetrf;": '\U00002128', + "zeta;": '\U000003B6', + "zfr;": '\U0001D537', + "zhcy;": '\U00000436', + "zigrarr;": '\U000021DD', + "zopf;": '\U0001D56B', + "zscr;": '\U0001D4CF', + "zwj;": '\U0000200D', + "zwnj;": '\U0000200C', + "AElig": '\U000000C6', + "AMP": '\U00000026', + "Aacute": '\U000000C1', + "Acirc": '\U000000C2', + "Agrave": '\U000000C0', + "Aring": '\U000000C5', + "Atilde": '\U000000C3', + "Auml": '\U000000C4', + "COPY": '\U000000A9', + "Ccedil": '\U000000C7', + "ETH": '\U000000D0', + "Eacute": '\U000000C9', + "Ecirc": '\U000000CA', + "Egrave": '\U000000C8', + "Euml": '\U000000CB', + "GT": '\U0000003E', + "Iacute": '\U000000CD', + "Icirc": '\U000000CE', + "Igrave": '\U000000CC', + "Iuml": '\U000000CF', + "LT": '\U0000003C', + "Ntilde": '\U000000D1', + "Oacute": '\U000000D3', + "Ocirc": '\U000000D4', + "Ograve": '\U000000D2', + "Oslash": '\U000000D8', + "Otilde": '\U000000D5', + "Ouml": '\U000000D6', + "QUOT": '\U00000022', + "REG": '\U000000AE', + "THORN": '\U000000DE', + "Uacute": '\U000000DA', + "Ucirc": '\U000000DB', + "Ugrave": '\U000000D9', + "Uuml": '\U000000DC', + "Yacute": '\U000000DD', + "aacute": '\U000000E1', + "acirc": '\U000000E2', + "acute": '\U000000B4', + "aelig": '\U000000E6', + "agrave": '\U000000E0', + "amp": '\U00000026', + "aring": '\U000000E5', + "atilde": '\U000000E3', + "auml": '\U000000E4', + "brvbar": '\U000000A6', + "ccedil": '\U000000E7', + "cedil": '\U000000B8', + "cent": '\U000000A2', + "copy": '\U000000A9', + "curren": '\U000000A4', + "deg": '\U000000B0', + "divide": '\U000000F7', + "eacute": '\U000000E9', + "ecirc": '\U000000EA', + "egrave": '\U000000E8', + "eth": '\U000000F0', + "euml": '\U000000EB', + "frac12": '\U000000BD', + "frac14": '\U000000BC', + "frac34": '\U000000BE', + "gt": '\U0000003E', + "iacute": '\U000000ED', + "icirc": '\U000000EE', + "iexcl": '\U000000A1', + "igrave": '\U000000EC', + "iquest": '\U000000BF', + "iuml": '\U000000EF', + "laquo": '\U000000AB', + "lt": '\U0000003C', + "macr": '\U000000AF', + "micro": '\U000000B5', + "middot": '\U000000B7', + "nbsp": '\U000000A0', + "not": '\U000000AC', + "ntilde": '\U000000F1', + "oacute": '\U000000F3', + "ocirc": '\U000000F4', + "ograve": '\U000000F2', + "ordf": '\U000000AA', + "ordm": '\U000000BA', + "oslash": '\U000000F8', + "otilde": '\U000000F5', + "ouml": '\U000000F6', + "para": '\U000000B6', + "plusmn": '\U000000B1', + "pound": '\U000000A3', + "quot": '\U00000022', + "raquo": '\U000000BB', + "reg": '\U000000AE', + "sect": '\U000000A7', + "shy": '\U000000AD', + "sup1": '\U000000B9', + "sup2": '\U000000B2', + "sup3": '\U000000B3', + "szlig": '\U000000DF', + "thorn": '\U000000FE', + "times": '\U000000D7', + "uacute": '\U000000FA', + "ucirc": '\U000000FB', + "ugrave": '\U000000F9', + "uml": '\U000000A8', + "uuml": '\U000000FC', + "yacute": '\U000000FD', + "yen": '\U000000A5', + "yuml": '\U000000FF', + } + + entity2 = map[string][2]rune{ + // TODO(nigeltao): Handle replacements that are wider than their names. + // "nLt;": {'\u226A', '\u20D2'}, + // "nGt;": {'\u226B', '\u20D2'}, + "NotEqualTilde;": {'\u2242', '\u0338'}, + "NotGreaterFullEqual;": {'\u2267', '\u0338'}, + "NotGreaterGreater;": {'\u226B', '\u0338'}, + "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'}, + "NotHumpDownHump;": {'\u224E', '\u0338'}, + "NotHumpEqual;": {'\u224F', '\u0338'}, + "NotLeftTriangleBar;": {'\u29CF', '\u0338'}, + "NotLessLess;": {'\u226A', '\u0338'}, + "NotLessSlantEqual;": {'\u2A7D', '\u0338'}, + "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'}, + "NotNestedLessLess;": {'\u2AA1', '\u0338'}, + "NotPrecedesEqual;": {'\u2AAF', '\u0338'}, + "NotRightTriangleBar;": {'\u29D0', '\u0338'}, + "NotSquareSubset;": {'\u228F', '\u0338'}, + "NotSquareSuperset;": {'\u2290', '\u0338'}, + "NotSubset;": {'\u2282', '\u20D2'}, + "NotSucceedsEqual;": {'\u2AB0', '\u0338'}, + "NotSucceedsTilde;": {'\u227F', '\u0338'}, + "NotSuperset;": {'\u2283', '\u20D2'}, + "ThickSpace;": {'\u205F', '\u200A'}, + "acE;": {'\u223E', '\u0333'}, + "bne;": {'\u003D', '\u20E5'}, + "bnequiv;": {'\u2261', '\u20E5'}, + "caps;": {'\u2229', '\uFE00'}, + "cups;": {'\u222A', '\uFE00'}, + "fjlig;": {'\u0066', '\u006A'}, + "gesl;": {'\u22DB', '\uFE00'}, + "gvertneqq;": {'\u2269', '\uFE00'}, + "gvnE;": {'\u2269', '\uFE00'}, + "lates;": {'\u2AAD', '\uFE00'}, + "lesg;": {'\u22DA', '\uFE00'}, + "lvertneqq;": {'\u2268', '\uFE00'}, + "lvnE;": {'\u2268', '\uFE00'}, + "nGg;": {'\u22D9', '\u0338'}, + "nGtv;": {'\u226B', '\u0338'}, + "nLl;": {'\u22D8', '\u0338'}, + "nLtv;": {'\u226A', '\u0338'}, + "nang;": {'\u2220', '\u20D2'}, + "napE;": {'\u2A70', '\u0338'}, + "napid;": {'\u224B', '\u0338'}, + "nbump;": {'\u224E', '\u0338'}, + "nbumpe;": {'\u224F', '\u0338'}, + "ncongdot;": {'\u2A6D', '\u0338'}, + "nedot;": {'\u2250', '\u0338'}, + "nesim;": {'\u2242', '\u0338'}, + "ngE;": {'\u2267', '\u0338'}, + "ngeqq;": {'\u2267', '\u0338'}, + "ngeqslant;": {'\u2A7E', '\u0338'}, + "nges;": {'\u2A7E', '\u0338'}, + "nlE;": {'\u2266', '\u0338'}, + "nleqq;": {'\u2266', '\u0338'}, + "nleqslant;": {'\u2A7D', '\u0338'}, + "nles;": {'\u2A7D', '\u0338'}, + "notinE;": {'\u22F9', '\u0338'}, + "notindot;": {'\u22F5', '\u0338'}, + "nparsl;": {'\u2AFD', '\u20E5'}, + "npart;": {'\u2202', '\u0338'}, + "npre;": {'\u2AAF', '\u0338'}, + "npreceq;": {'\u2AAF', '\u0338'}, + "nrarrc;": {'\u2933', '\u0338'}, + "nrarrw;": {'\u219D', '\u0338'}, + "nsce;": {'\u2AB0', '\u0338'}, + "nsubE;": {'\u2AC5', '\u0338'}, + "nsubset;": {'\u2282', '\u20D2'}, + "nsubseteqq;": {'\u2AC5', '\u0338'}, + "nsucceq;": {'\u2AB0', '\u0338'}, + "nsupE;": {'\u2AC6', '\u0338'}, + "nsupset;": {'\u2283', '\u20D2'}, + "nsupseteqq;": {'\u2AC6', '\u0338'}, + "nvap;": {'\u224D', '\u20D2'}, + "nvge;": {'\u2265', '\u20D2'}, + "nvgt;": {'\u003E', '\u20D2'}, + "nvle;": {'\u2264', '\u20D2'}, + "nvlt;": {'\u003C', '\u20D2'}, + "nvltrie;": {'\u22B4', '\u20D2'}, + "nvrtrie;": {'\u22B5', '\u20D2'}, + "nvsim;": {'\u223C', '\u20D2'}, + "race;": {'\u223D', '\u0331'}, + "smtes;": {'\u2AAC', '\uFE00'}, + "sqcaps;": {'\u2293', '\uFE00'}, + "sqcups;": {'\u2294', '\uFE00'}, + "varsubsetneq;": {'\u228A', '\uFE00'}, + "varsubsetneqq;": {'\u2ACB', '\uFE00'}, + "varsupsetneq;": {'\u228B', '\uFE00'}, + "varsupsetneqq;": {'\u2ACC', '\uFE00'}, + "vnsub;": {'\u2282', '\u20D2'}, + "vnsup;": {'\u2283', '\u20D2'}, + "vsubnE;": {'\u2ACB', '\uFE00'}, + "vsubne;": {'\u228A', '\uFE00'}, + "vsupnE;": {'\u2ACC', '\uFE00'}, + "vsupne;": {'\u228B', '\uFE00'}, + } + + return entity, entity2 +}) diff --git a/go/src/html/entity_test.go b/go/src/html/entity_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4011da6141db4bc9fc82021b6a7ba59001ab0c78 --- /dev/null +++ b/go/src/html/entity_test.go @@ -0,0 +1,35 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import ( + "testing" + "unicode/utf8" +) + +func TestEntityLength(t *testing.T) { + entity, entity2 := entityMaps() + + if len(entity) == 0 || len(entity2) == 0 { + t.Fatal("maps not loaded") + } + + // We verify that the length of UTF-8 encoding of each value is <= 1 + len(key). + // The +1 comes from the leading "&". This property implies that the length of + // unescaped text is <= the length of escaped text. + for k, v := range entity { + if 1+len(k) < utf8.RuneLen(v) { + t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v)) + } + if len(k) > longestEntityWithoutSemicolon && k[len(k)-1] != ';' { + t.Errorf("entity name %s is %d characters, but longestEntityWithoutSemicolon=%d", k, len(k), longestEntityWithoutSemicolon) + } + } + for k, v := range entity2 { + if 1+len(k) < utf8.RuneLen(v[0])+utf8.RuneLen(v[1]) { + t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v[0]) + string(v[1])) + } + } +} diff --git a/go/src/html/escape.go b/go/src/html/escape.go new file mode 100644 index 0000000000000000000000000000000000000000..d66a3e48378faa4beba20ed388d22afc1f605cfa --- /dev/null +++ b/go/src/html/escape.go @@ -0,0 +1,214 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package html provides functions for escaping and unescaping HTML text. +package html + +import ( + "strings" + "unicode/utf8" +) + +// These replacements permit compatibility with old numeric entities that +// assumed Windows-1252 encoding. +// https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state +var replacementTable = [...]rune{ + '\u20AC', // First entry is what 0x80 should be replaced with. + '\u0081', + '\u201A', + '\u0192', + '\u201E', + '\u2026', + '\u2020', + '\u2021', + '\u02C6', + '\u2030', + '\u0160', + '\u2039', + '\u0152', + '\u008D', + '\u017D', + '\u008F', + '\u0090', + '\u2018', + '\u2019', + '\u201C', + '\u201D', + '\u2022', + '\u2013', + '\u2014', + '\u02DC', + '\u2122', + '\u0161', + '\u203A', + '\u0153', + '\u009D', + '\u017E', + '\u0178', // Last entry is 0x9F. + // 0x00->'\uFFFD' is handled programmatically. + // 0x0D->'\u000D' is a no-op. +} + +// unescapeEntity reads an entity like "<" from b[src:] and writes the +// corresponding "<" to b[dst:], returning the incremented dst and src cursors. +// Precondition: b[src] == '&' && dst <= src. +func unescapeEntity(b []byte, dst, src int, entity map[string]rune, entity2 map[string][2]rune) (dst1, src1 int) { + const attribute = false + + // http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#consume-a-character-reference + + // i starts at 1 because we already know that s[0] == '&'. + i, s := 1, b[src:] + + if len(s) <= 1 { + b[dst] = b[src] + return dst + 1, src + 1 + } + + if s[i] == '#' { + if len(s) <= 3 { // We need to have at least "&#.". + b[dst] = b[src] + return dst + 1, src + 1 + } + i++ + c := s[i] + hex := false + if c == 'x' || c == 'X' { + hex = true + i++ + } + + x := '\x00' + for i < len(s) { + c = s[i] + i++ + if hex { + if '0' <= c && c <= '9' { + x = 16*x + rune(c) - '0' + continue + } else if 'a' <= c && c <= 'f' { + x = 16*x + rune(c) - 'a' + 10 + continue + } else if 'A' <= c && c <= 'F' { + x = 16*x + rune(c) - 'A' + 10 + continue + } + } else if '0' <= c && c <= '9' { + x = 10*x + rune(c) - '0' + continue + } + if c != ';' { + i-- + } + break + } + + if i <= 3 { // No characters matched. + b[dst] = b[src] + return dst + 1, src + 1 + } + + if 0x80 <= x && x <= 0x9F { + // Replace characters from Windows-1252 with UTF-8 equivalents. + x = replacementTable[x-0x80] + } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF { + // Replace invalid characters with the replacement character. + x = '\uFFFD' + } + + return dst + utf8.EncodeRune(b[dst:], x), src + i + } + + // Consume the maximum number of characters possible, with the + // consumed characters matching one of the named references. + + for i < len(s) { + c := s[i] + i++ + // Lower-cased characters are more common in entities, so we check for them first. + if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { + continue + } + if c != ';' { + i-- + } + break + } + + entityName := s[1:i] + if len(entityName) == 0 { + // No-op. + } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { + // No-op. + } else if x := entity[string(entityName)]; x != 0 { + return dst + utf8.EncodeRune(b[dst:], x), src + i + } else if x := entity2[string(entityName)]; x[0] != 0 { + dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) + return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i + } else if !attribute { + maxLen := len(entityName) - 1 + if maxLen > longestEntityWithoutSemicolon { + maxLen = longestEntityWithoutSemicolon + } + for j := maxLen; j > 1; j-- { + if x := entity[string(entityName[:j])]; x != 0 { + return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 + } + } + } + + dst1, src1 = dst+i, src+i + copy(b[dst:dst1], b[src:src1]) + return dst1, src1 +} + +var htmlEscaper = strings.NewReplacer( + `&`, "&", + `'`, "'", // "'" is shorter than "'" and apos was not in HTML until HTML5. + `<`, "<", + `>`, ">", + `"`, """, // """ is shorter than """. +) + +// EscapeString escapes special characters like "<" to become "<". It +// escapes only five such characters: <, >, &, ' and ". +// [UnescapeString](EscapeString(s)) == s always holds, but the converse isn't +// always true. +func EscapeString(s string) string { + return htmlEscaper.Replace(s) +} + +// UnescapeString unescapes entities like "<" to become "<". It unescapes a +// larger range of entities than [EscapeString] escapes. For example, "á" +// unescapes to "á", as does "á" and "á". +// UnescapeString([EscapeString](s)) == s always holds, but the converse isn't +// always true. +func UnescapeString(s string) string { + i := strings.IndexByte(s, '&') + + if i < 0 { + return s + } + + b := []byte(s) + entity, entity2 := entityMaps() + dst, src := unescapeEntity(b, i, i, entity, entity2) + for len(s[src:]) > 0 { + if s[src] == '&' { + i = 0 + } else { + i = strings.IndexByte(s[src:], '&') + } + if i < 0 { + dst += copy(b[dst:], s[src:]) + break + } + + if i > 0 { + copy(b[dst:], s[src:src+i]) + } + dst, src = unescapeEntity(b, dst+i, src+i, entity, entity2) + } + return string(b[:dst]) +} diff --git a/go/src/html/escape_test.go b/go/src/html/escape_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8b51a55409fa55ee04149b31bafbe4657312d138 --- /dev/null +++ b/go/src/html/escape_test.go @@ -0,0 +1,169 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import ( + "strings" + "testing" +) + +type unescapeTest struct { + // A short description of the test case. + desc string + // The HTML text. + html string + // The unescaped text. + unescaped string +} + +var unescapeTests = []unescapeTest{ + // Handle no entities. + { + "copy", + "A\ttext\nstring", + "A\ttext\nstring", + }, + // Handle simple named entities. + { + "simple", + "& > <", + "& > <", + }, + // Handle hitting the end of the string. + { + "stringEnd", + "& &", + "& &", + }, + // Handle entities with two codepoints. + { + "multiCodepoint", + "text ⋛︀ blah", + "text \u22db\ufe00 blah", + }, + // Handle decimal numeric entities. + { + "decimalEntity", + "Delta = Δ ", + "Delta = Δ ", + }, + // Handle hexadecimal numeric entities. + { + "hexadecimalEntity", + "Lambda = λ = λ ", + "Lambda = λ = λ ", + }, + // Handle numeric early termination. + { + "numericEnds", + "&# &#x €43 © = ©f = ©", + "&# &#x €43 © = ©f = ©", + }, + // Handle numeric ISO-8859-1 entity replacements. + { + "numericReplacements", + "Footnote‡", + "Footnote‡", + }, + // Handle single ampersand. + { + "copySingleAmpersand", + "&", + "&", + }, + // Handle ampersand followed by non-entity. + { + "copyAmpersandNonEntity", + "text &test", + "text &test", + }, + // Handle "&#". + { + "copyAmpersandHash", + "text &#", + "text &#", + }, +} + +func TestUnescape(t *testing.T) { + for _, tt := range unescapeTests { + unescaped := UnescapeString(tt.html) + if unescaped != tt.unescaped { + t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped) + } + } +} + +func TestUnescapeEscape(t *testing.T) { + ss := []string{ + ``, + `abc def`, + `a & b`, + `a&b`, + `a & b`, + `"`, + `"`, + `"<&>"`, + `"<&>"`, + `3&5==1 && 0<1, "0<1", a+acute=á`, + `The special characters are: <, >, &, ' and "`, + } + for _, s := range ss { + if got := UnescapeString(EscapeString(s)); got != s { + t.Errorf("got %q want %q", got, s) + } + } +} + +var ( + benchEscapeData = strings.Repeat("AAAAA < BBBBB > CCCCC & DDDDD ' EEEEE \" ", 100) + benchEscapeNone = strings.Repeat("AAAAA x BBBBB x CCCCC x DDDDD x EEEEE x ", 100) + benchUnescapeSparse = strings.Repeat(strings.Repeat("AAAAA x BBBBB x CCCCC x DDDDD x EEEEE x ", 10)+"&", 10) + benchUnescapeDense = strings.Repeat("&< & <", 100) +) + +func BenchmarkEscape(b *testing.B) { + n := 0 + for i := 0; i < b.N; i++ { + n += len(EscapeString(benchEscapeData)) + } +} + +func BenchmarkEscapeNone(b *testing.B) { + n := 0 + for i := 0; i < b.N; i++ { + n += len(EscapeString(benchEscapeNone)) + } +} + +func BenchmarkUnescape(b *testing.B) { + s := EscapeString(benchEscapeData) + n := 0 + for i := 0; i < b.N; i++ { + n += len(UnescapeString(s)) + } +} + +func BenchmarkUnescapeNone(b *testing.B) { + s := EscapeString(benchEscapeNone) + n := 0 + for i := 0; i < b.N; i++ { + n += len(UnescapeString(s)) + } +} + +func BenchmarkUnescapeSparse(b *testing.B) { + n := 0 + for i := 0; i < b.N; i++ { + n += len(UnescapeString(benchUnescapeSparse)) + } +} + +func BenchmarkUnescapeDense(b *testing.B) { + n := 0 + for i := 0; i < b.N; i++ { + n += len(UnescapeString(benchUnescapeDense)) + } +} diff --git a/go/src/html/example_test.go b/go/src/html/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e28cac1be5e4f8ead17ffb4b4cfd90803fc2e48 --- /dev/null +++ b/go/src/html/example_test.go @@ -0,0 +1,22 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html_test + +import ( + "fmt" + "html" +) + +func ExampleEscapeString() { + const s = `"Fran & Freddie's Diner" ` + fmt.Println(html.EscapeString(s)) + // Output: "Fran & Freddie's Diner" <tasty@example.com> +} + +func ExampleUnescapeString() { + const s = `"Fran & Freddie's Diner" <tasty@example.com>` + fmt.Println(html.UnescapeString(s)) + // Output: "Fran & Freddie's Diner" +} diff --git a/go/src/html/fuzz_test.go b/go/src/html/fuzz_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ed15d8f270b93e49ee852ba1b7bec901256b9076 --- /dev/null +++ b/go/src/html/fuzz_test.go @@ -0,0 +1,22 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import "testing" + +func FuzzEscapeUnescape(f *testing.F) { + f.Fuzz(func(t *testing.T, v string) { + e := EscapeString(v) + u := UnescapeString(e) + if u != v { + t.Errorf("EscapeString(%q) = %q, UnescapeString(%q) = %q, want %q", v, e, e, u, v) + } + + // As per the documentation, this isn't always equal to v, so it makes + // no sense to check for equality. It can still be interesting to find + // panics in it though. + EscapeString(UnescapeString(v)) + }) +} diff --git a/go/src/image/decode_example_test.go b/go/src/image/decode_example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..252ac868c0fc6cba22ee80ed4f98b76adf37a0ab --- /dev/null +++ b/go/src/image/decode_example_test.go @@ -0,0 +1,149 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This example demonstrates decoding a JPEG image and examining its pixels. +package image_test + +import ( + "encoding/base64" + "fmt" + "image" + "log" + "strings" + + // Package image/jpeg is not used explicitly in the code below, + // but is imported for its initialization side-effect, which allows + // image.Decode to understand JPEG formatted images. Uncomment these + // two lines to also understand GIF and PNG images: + // _ "image/gif" + // _ "image/png" + _ "image/jpeg" +) + +func Example_decodeConfig() { + reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)) + config, format, err := image.DecodeConfig(reader) + if err != nil { + log.Fatal(err) + } + fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format) +} + +func Example() { + // Decode the JPEG data. If reading from file, create a reader with + // + // reader, err := os.Open("testdata/video-001.q50.420.jpeg") + // if err != nil { + // log.Fatal(err) + // } + // defer reader.Close() + reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)) + m, _, err := image.Decode(reader) + if err != nil { + log.Fatal(err) + } + bounds := m.Bounds() + + // Calculate a 16-bin histogram for m's red, green, blue and alpha components. + // + // An image's bounds do not necessarily start at (0, 0), so the two loops start + // at bounds.Min.Y and bounds.Min.X. Looping over Y first and X second is more + // likely to result in better memory access patterns than X first and Y second. + var histogram [16][4]int + for y := bounds.Min.Y; y < bounds.Max.Y; y++ { + for x := bounds.Min.X; x < bounds.Max.X; x++ { + r, g, b, a := m.At(x, y).RGBA() + // A color's RGBA method returns values in the range [0, 65535]. + // Shifting by 12 reduces this to the range [0, 15]. + histogram[r>>12][0]++ + histogram[g>>12][1]++ + histogram[b>>12][2]++ + histogram[a>>12][3]++ + } + } + + // Print the results. + fmt.Printf("%-14s %6s %6s %6s %6s\n", "bin", "red", "green", "blue", "alpha") + for i, x := range histogram { + fmt.Printf("0x%04x-0x%04x: %6d %6d %6d %6d\n", i<<12, (i+1)<<12-1, x[0], x[1], x[2], x[3]) + } + // Output: + // bin red green blue alpha + // 0x0000-0x0fff: 362 793 7245 0 + // 0x1000-0x1fff: 648 2963 1036 0 + // 0x2000-0x2fff: 1072 2301 977 0 + // 0x3000-0x3fff: 819 2266 982 0 + // 0x4000-0x4fff: 537 1303 541 0 + // 0x5000-0x5fff: 321 964 261 0 + // 0x6000-0x6fff: 321 375 177 0 + // 0x7000-0x7fff: 599 278 213 0 + // 0x8000-0x8fff: 3478 228 275 0 + // 0x9000-0x9fff: 2260 233 328 0 + // 0xa000-0xafff: 921 282 374 0 + // 0xb000-0xbfff: 322 335 395 0 + // 0xc000-0xcfff: 228 388 299 0 + // 0xd000-0xdfff: 261 415 277 0 + // 0xe000-0xefff: 516 423 297 0 + // 0xf000-0xffff: 2785 1903 1773 15450 +} + +const data = ` +/9j/4AAQSkZJRgABAQIAHAAcAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdA +SFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2Nj +Y2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABnAJYDASIAAhEBAxEB/8QA +HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIh +MUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW +V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG +x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQF +BgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAV +YnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE +hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq +8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDlwKMD0pwzSiuK57QzGDxS7D6in8Y5ximnAPUfSlcq4m3ilUYp +2OKXHvRcVxnTtS7c07HNFK4DQPakC4PNOA+tOx70XAjK/So5gBGP94fzqfvUVx/qxx/EP51UXqRP4WSE +cmgjilP3jSEZqS0IO/NGDnpUiocDg/McDjvV6HTPOdVWYgsM5KcfzzQ2JySM2jp6VYu7SWzmMUwG4cgj +kMPUVBjjtTGtRu0Zopw+lFFxhinrGzuqqMsxAA9yaXFSRv5cqSEcIwYj6GpuZ30O30fSLKzhUpbpNMv3 +5XGTn29BV28jt7pPLuIVljPBBFVreYx+VbqAjycgt3x14zRcNOxGyVFHQkIc/wA61exyKLbuzjdZ046d +ftEuTEw3Rk9SPT8P8Kpbea3tchbyVae4JkjbbGpGdwOM89Af6ViFTWUtGdcXoM2+woK1JtpNtTcoZt+l +Jt7ZqTbRtouFyPFRXI/c9D94fzqzioLsfuD/ALw/nVReqIn8LJCOTSY+tSMOTmkIpXLRu+F0t5pJxPHG +wjjUAuBjJJz1+laD6Pai+WaK9SBX6puzn6ZP+NV/Dkdtc6ZNbyAFwxLAHDYPv6VoQ21nPNEEiQGEFRtk +Gf0NaWTOeW7Of8QwGG4MRZnEbYXPJwRnOR0zWNXW+KrqBLUWi5EjbWCgcAA9c/gRXKYqZaGlK/LqMH0F +FLtHvRSNiYD2pSDTgpp6p0ywUHoTULXYxcktzrdCf7Xo8LP/AKyEmMNjJ46dfbFWJ5TDGNwB9lFUvDV9 +YrbfYGbyrjcWG88S57g+vtV26ZIvMlumKwwjLZ6V0WfU54yTvYwtbubea2WNWbzg4bYQeBgj8OtYeKhj +u4y2HQxqxOD1xzxmrWAQCCGB6EGsaikndmsJxeiYzBo280/Z7UbayuaXGY5oIp+2lx9KLjIsVDeD/Rj/ +ALy/zq1t96r3y4tT/vL/ADq4P3kRP4WSleTSFKkkKoCW4GaqNcMxIjXj1pxjKT0FKrGC1Nrw3vGrKkYz +5kTAr6455/HH510UdwPtRgWCbzF5+YYUf4Vwun39xpmoR3qASMmQUJwGU9Rnt/8AWrpbrxhb8/ZdOmaQ +gAGZwFH5ZJrpVKVlY5ZYhN6kXiu2eO/ikZlIljAAB5yM549OawSOOlPuLqe+umuLqTfM4OSOAo7ADsKh +hl/cRsTuJHPv7mlKi3sVTxNtGP20VJhThgSQaK52mnZnUqsWrpkyeUrr5pABOAPU1AGaXUCWJISHGPfP +P8qL7BiKnsMg46H3qrbzupbj5mPTPTpXVSglG551SpzSsXJ4/MBUgYIxyKpySyGBYJriV1D7kRpCVH4V +bSeNJ4xchni3DeqnBI+td7F4b0mKIRjT45VbktJlzk455+n6VtYzv2PNwFZWBHBGKVJDGVC54/nXQeMN +NttLNkba1jgWVWDmM8bhg4/nzXLSSbXVj6fyNKUdNRp21RtIRJGrjuM0u3FQ2DbodvcEkfQmrW2vLqLl +k0ejCXNFMj2/jQV9qkxSYNRcsZiq2oI32N2CkhWXJxwOe9XMcVt6hoPn6dFaW0wgRpNzvKDlz6+/0rai +ryv2Jm9LHJai+ZRGCBjnr71ErdAxAY9B611t1Y2cunbbaOQ3FvKZI3UqGlZMbiWwfcfhV231iwvLSM3U +lt5Uq52TuZG+hGMA12xXJGxxzjzybOQtNOvb5j9ktZJhnBIHyg+5PFX38JayqK/2eLJIBUTgkDA9q7ex +itrSHFpGsUbndhRgc+g7VNIyfZJAoJZUbb3I46CtFJMylBo8sdWhmYMuCnylc9wef5VUT7+1chc5NS7h +sUZO5RtIPUH3pkBDOxxxmqM9TQtn+WilhHfHaik43KTG3Z4IyPyrNVjGCsZ+dmwv6V3cXhSG8sYpJLud +JJIwxChdoJGcYx/Wkg8DafA4knvLiQr/ALqj+VQpKw3FtnFFfvbiSMgZJ6/jXp2n3d9cQRBTFsKD96EP +oOxPU/8A68VVtbbRtMVntbePKDLTSHJH/Aj/AEqHTvE66rq72VugMMcbSGTnL4wMAfjT5n0HyW3L+s6b +baxaJBdzN+7bcrxkAhun0rz3VNCv7e7lgigknWI43xLu6jjIHTjtXqfkpPGVYsBkghTikgsYIN/lhgXb +cxLkknp/ShczQ7xtY8vtEmhkj8yGRBuCnehUcnHcVtmwfJ/fQ8e7f/E12txZW91C0U6b42xlST2OR/Ko +Bo1gM/uW55/1jf41nOipu7LhV5FZHIGzI6zwj/vr/Ck+yr3uYf8Ax7/CutbQdMb71tn/ALaN/jSf8I/p +X/PoP++2/wAan6rAr6wzkWt0II+1Rc/7Lf4Vd1eeCSKBbdZDdShYoiZNoyfY10P/AAj2lf8APmP++2/x +oPh/SjKspsozIuNrZORjp3qo0FHYPb3OZt7ae3SzjuItsiRSAgnccl/UA+3Q1yNjKLR4ZZYY5VD7tkv3 +WwO/+e1evPp9nI257aJm6bioz1z1+tY+s6Hplnot9PbWMMcqwOFcLyOO1bJWMZSTOPHi+9w3mosrlyd2 +9lCj02g9P/1e9a3hzxAbl2ikZRcdQueHHt7j864Y8Z4I4oRzG6urFWU5BHBB7HNJxTFGbR6he6Vpmtgm +eLy5zwZI/lb8fX8azIvBUUTHdfSFP4QsYB/HNZ+k+KEnRY75hHOvAk6K/v7H9K6yyvlnQBmDZ6GsnzR0 +N0oy1RzOtaN/Y1tHNFO06u+zYy4I4Jzx9KKveJblXuordSGES5b6n/62PzorKVdp2LjQTVyWz8UWEWlq +jSgyxfJt6EgdDzWTdeLIZGO7zHI/hVajGmWWP+PWL8qwlAIURrhpMAHHJA71pRcZrToZzcoEuo6heakA +GHk245CZ6/X1qPTLq40q+W5t2QybSpDAkEEc55/zilk5k2r91eKhLDzWz2rpsczbbuemeD76fUNG865I +MiysmQMZAAwa3a5j4ftu0ByP+fh/5CulkLLG7INzhSVHqe1Fh3uOoqn9qQQxyhndmHIxwOmSR2xQ13KD +KoiBZOV9JBnt707MVy5RWdNdy7wRGf3bfMinnO1jg+vY03WXLaJO3mhQ20b0zwpYf0qlG7S7icrJs08U +VwumgC+YiQyeVtZH567hzj8aSL949oGhE/2v5pJCDkksQwBHC4/+vXQ8LZ2uYxxCavY7us/xCcaBfn0h +b+VP0bnSrb94ZMJgOecj1rl/GfidUE2k2gy5+SeQjgA/wj3rlas2jdao48qrjLAGkSKPk4Gc1WMj92I+ +lIJnU8OfxPWo5inBokmtQTmM4OOh71b0q6vbFmWCbaxHyqQGAP0PT8KhSTzVyo5ocSKA5VfTOTmqsmRd +pl99XjPzThzK3zOeOSeveirNmkgg/fIpYsTkYORxRXmzlTjJqx6EVUcU7mhkKCzdAK59QI9zYxtG1fYU +UVtgtmY4nZEa8Ak9aqFv3rfSiiu1nMeifDv/AJF+T/r4f+QrqqKKQwzQenNFFMCOKFIgNuThdoJ5OPSk +ubeK6t3gnXdG4wwziiii/UTKMOg6dbzJLFE4dSCP3rEdeOM8805tDsGMvySgSsS6rM6gk9eAcUUVftZt +3uyVGNthuq3Eei6DK8H7sRR7YuMgHtXkc8rzTNLM26RyWY+p70UVnLY0iEsUipG7rhZBlDkc1HgYoorM +0HwyBXGeRjmrcUhMg2ghezd//rUUVcTKW5s2jZtY/QDaOKKKK8ip8bPRj8KP/9k= +` diff --git a/go/src/image/decode_test.go b/go/src/image/decode_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2b3ff6ba582662c11c4e19392741513e584e0b38 --- /dev/null +++ b/go/src/image/decode_test.go @@ -0,0 +1,135 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image_test + +import ( + "bufio" + "fmt" + "image" + "image/color" + "os" + "testing" + + _ "image/gif" + _ "image/jpeg" + _ "image/png" +) + +type imageTest struct { + goldenFilename string + filename string + tolerance int +} + +var imageTests = []imageTest{ + {"testdata/video-001.png", "testdata/video-001.png", 0}, + // GIF images are restricted to a 256-color palette and the conversion + // to GIF loses significant image quality. + {"testdata/video-001.png", "testdata/video-001.gif", 64 << 8}, + {"testdata/video-001.png", "testdata/video-001.interlaced.gif", 64 << 8}, + {"testdata/video-001.png", "testdata/video-001.5bpp.gif", 128 << 8}, + // JPEG is a lossy format and hence needs a non-zero tolerance. + {"testdata/video-001.png", "testdata/video-001.jpeg", 8 << 8}, + {"testdata/video-001.png", "testdata/video-001.progressive.jpeg", 8 << 8}, + {"testdata/video-001.221212.png", "testdata/video-001.221212.jpeg", 8 << 8}, + {"testdata/video-001.cmyk.png", "testdata/video-001.cmyk.jpeg", 8 << 8}, + {"testdata/video-001.rgb.png", "testdata/video-001.rgb.jpeg", 8 << 8}, + {"testdata/video-001.progressive.truncated.png", "testdata/video-001.progressive.truncated.jpeg", 8 << 8}, + // Grayscale images. + {"testdata/video-005.gray.png", "testdata/video-005.gray.jpeg", 8 << 8}, + {"testdata/video-005.gray.png", "testdata/video-005.gray.png", 0}, +} + +func decode(filename string) (image.Image, string, error) { + f, err := os.Open(filename) + if err != nil { + return nil, "", err + } + defer f.Close() + return image.Decode(bufio.NewReader(f)) +} + +func decodeConfig(filename string) (image.Config, string, error) { + f, err := os.Open(filename) + if err != nil { + return image.Config{}, "", err + } + defer f.Close() + return image.DecodeConfig(bufio.NewReader(f)) +} + +func delta(u0, u1 uint32) int { + d := int(u0) - int(u1) + if d < 0 { + return -d + } + return d +} + +func withinTolerance(c0, c1 color.Color, tolerance int) bool { + r0, g0, b0, a0 := c0.RGBA() + r1, g1, b1, a1 := c1.RGBA() + r := delta(r0, r1) + g := delta(g0, g1) + b := delta(b0, b1) + a := delta(a0, a1) + return r <= tolerance && g <= tolerance && b <= tolerance && a <= tolerance +} + +func TestDecode(t *testing.T) { + rgba := func(c color.Color) string { + r, g, b, a := c.RGBA() + return fmt.Sprintf("rgba = 0x%04x, 0x%04x, 0x%04x, 0x%04x for %T%v", r, g, b, a, c, c) + } + + golden := make(map[string]image.Image) +loop: + for _, it := range imageTests { + g := golden[it.goldenFilename] + if g == nil { + var err error + g, _, err = decode(it.goldenFilename) + if err != nil { + t.Errorf("%s: %v", it.goldenFilename, err) + continue loop + } + golden[it.goldenFilename] = g + } + m, imageFormat, err := decode(it.filename) + if err != nil { + t.Errorf("%s: %v", it.filename, err) + continue loop + } + b := g.Bounds() + if !b.Eq(m.Bounds()) { + t.Errorf("%s: got bounds %v want %v", it.filename, m.Bounds(), b) + continue loop + } + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + if !withinTolerance(g.At(x, y), m.At(x, y), it.tolerance) { + t.Errorf("%s: at (%d, %d):\ngot %v\nwant %v", + it.filename, x, y, rgba(m.At(x, y)), rgba(g.At(x, y))) + continue loop + } + } + } + if imageFormat == "gif" { + // Each frame of a GIF can have a frame-local palette override the + // GIF-global palette. Thus, image.Decode can yield a different ColorModel + // than image.DecodeConfig. + continue + } + c, _, err := decodeConfig(it.filename) + if err != nil { + t.Errorf("%s: %v", it.filename, err) + continue loop + } + if m.ColorModel() != c.ColorModel { + t.Errorf("%s: color models differ", it.filename) + continue loop + } + } +} diff --git a/go/src/image/format.go b/go/src/image/format.go new file mode 100644 index 0000000000000000000000000000000000000000..7426afb3e69e906406ad69ed68f051366d18a0e8 --- /dev/null +++ b/go/src/image/format.go @@ -0,0 +1,109 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "bufio" + "errors" + "io" + "sync" + "sync/atomic" +) + +// ErrFormat indicates that decoding encountered an unknown format. +var ErrFormat = errors.New("image: unknown format") + +// A format holds an image format's name, magic header and how to decode it. +type format struct { + name, magic string + decode func(io.Reader) (Image, error) + decodeConfig func(io.Reader) (Config, error) +} + +// Formats is the list of registered formats. +var ( + formatsMu sync.Mutex + atomicFormats atomic.Value +) + +// RegisterFormat registers an image format for use by [Decode]. +// Name is the name of the format, like "jpeg" or "png". +// Magic is the magic prefix that identifies the format's encoding. The magic +// string can contain "?" wildcards that each match any one byte. +// [Decode] is the function that decodes the encoded image. +// [DecodeConfig] is the function that decodes just its configuration. +func RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error)) { + formatsMu.Lock() + formats, _ := atomicFormats.Load().([]format) + atomicFormats.Store(append(formats, format{name, magic, decode, decodeConfig})) + formatsMu.Unlock() +} + +// A reader is an io.Reader that can also peek ahead. +type reader interface { + io.Reader + Peek(int) ([]byte, error) +} + +// asReader converts an io.Reader to a reader. +func asReader(r io.Reader) reader { + if rr, ok := r.(reader); ok { + return rr + } + return bufio.NewReader(r) +} + +// match reports whether magic matches b. Magic may contain "?" wildcards. +func match(magic string, b []byte) bool { + if len(magic) != len(b) { + return false + } + for i, c := range b { + if magic[i] != c && magic[i] != '?' { + return false + } + } + return true +} + +// sniff determines the format of r's data. +func sniff(r reader) format { + formats, _ := atomicFormats.Load().([]format) + for _, f := range formats { + b, err := r.Peek(len(f.magic)) + if err == nil && match(f.magic, b) { + return f + } + } + return format{} +} + +// Decode decodes an image that has been encoded in a registered format. +// The string returned is the format name used during format registration. +// Format registration is typically done by an init function in the codec- +// specific package. +func Decode(r io.Reader) (Image, string, error) { + rr := asReader(r) + f := sniff(rr) + if f.decode == nil { + return nil, "", ErrFormat + } + m, err := f.decode(rr) + return m, f.name, err +} + +// DecodeConfig decodes the color model and dimensions of an image that has +// been encoded in a registered format. The string returned is the format name +// used during format registration. Format registration is typically done by +// an init function in the codec-specific package. +func DecodeConfig(r io.Reader) (Config, string, error) { + rr := asReader(r) + f := sniff(rr) + if f.decodeConfig == nil { + return Config{}, "", ErrFormat + } + c, err := f.decodeConfig(rr) + return c, f.name, err +} diff --git a/go/src/image/geom.go b/go/src/image/geom.go new file mode 100644 index 0000000000000000000000000000000000000000..4ee14bff980cf0fde464731f0fb9041215a42631 --- /dev/null +++ b/go/src/image/geom.go @@ -0,0 +1,317 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "image/color" + "math/bits" + "strconv" +) + +// A Point is an X, Y coordinate pair. The axes increase right and down. +type Point struct { + X, Y int +} + +// String returns a string representation of p like "(3,4)". +func (p Point) String() string { + return "(" + strconv.Itoa(p.X) + "," + strconv.Itoa(p.Y) + ")" +} + +// Add returns the vector p+q. +func (p Point) Add(q Point) Point { + return Point{p.X + q.X, p.Y + q.Y} +} + +// Sub returns the vector p-q. +func (p Point) Sub(q Point) Point { + return Point{p.X - q.X, p.Y - q.Y} +} + +// Mul returns the vector p*k. +func (p Point) Mul(k int) Point { + return Point{p.X * k, p.Y * k} +} + +// Div returns the vector p/k. +func (p Point) Div(k int) Point { + return Point{p.X / k, p.Y / k} +} + +// In reports whether p is in r. +func (p Point) In(r Rectangle) bool { + return r.Min.X <= p.X && p.X < r.Max.X && + r.Min.Y <= p.Y && p.Y < r.Max.Y +} + +// Mod returns the point q in r such that p.X-q.X is a multiple of r's width +// and p.Y-q.Y is a multiple of r's height. +func (p Point) Mod(r Rectangle) Point { + w, h := r.Dx(), r.Dy() + p = p.Sub(r.Min) + p.X = p.X % w + if p.X < 0 { + p.X += w + } + p.Y = p.Y % h + if p.Y < 0 { + p.Y += h + } + return p.Add(r.Min) +} + +// Eq reports whether p and q are equal. +func (p Point) Eq(q Point) bool { + return p == q +} + +// ZP is the zero [Point]. +// +// Deprecated: Use a literal [image.Point] instead. +var ZP Point + +// Pt is shorthand for [Point]{X, Y}. +func Pt(X, Y int) Point { + return Point{X, Y} +} + +// A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. +// It is well-formed if Min.X <= Max.X and likewise for Y. Points are always +// well-formed. A rectangle's methods always return well-formed outputs for +// well-formed inputs. +// +// A Rectangle is also an [Image] whose bounds are the rectangle itself. At +// returns color.Opaque for points in the rectangle and color.Transparent +// otherwise. +type Rectangle struct { + Min, Max Point +} + +// String returns a string representation of r like "(3,4)-(6,5)". +func (r Rectangle) String() string { + return r.Min.String() + "-" + r.Max.String() +} + +// Dx returns r's width. +func (r Rectangle) Dx() int { + return r.Max.X - r.Min.X +} + +// Dy returns r's height. +func (r Rectangle) Dy() int { + return r.Max.Y - r.Min.Y +} + +// Size returns r's width and height. +func (r Rectangle) Size() Point { + return Point{ + r.Max.X - r.Min.X, + r.Max.Y - r.Min.Y, + } +} + +// Add returns the rectangle r translated by p. +func (r Rectangle) Add(p Point) Rectangle { + return Rectangle{ + Point{r.Min.X + p.X, r.Min.Y + p.Y}, + Point{r.Max.X + p.X, r.Max.Y + p.Y}, + } +} + +// Sub returns the rectangle r translated by -p. +func (r Rectangle) Sub(p Point) Rectangle { + return Rectangle{ + Point{r.Min.X - p.X, r.Min.Y - p.Y}, + Point{r.Max.X - p.X, r.Max.Y - p.Y}, + } +} + +// Inset returns the rectangle r inset by n, which may be negative. If either +// of r's dimensions is less than 2*n then an empty rectangle near the center +// of r will be returned. +func (r Rectangle) Inset(n int) Rectangle { + if r.Dx() < 2*n { + r.Min.X = (r.Min.X + r.Max.X) / 2 + r.Max.X = r.Min.X + } else { + r.Min.X += n + r.Max.X -= n + } + if r.Dy() < 2*n { + r.Min.Y = (r.Min.Y + r.Max.Y) / 2 + r.Max.Y = r.Min.Y + } else { + r.Min.Y += n + r.Max.Y -= n + } + return r +} + +// Intersect returns the largest rectangle contained by both r and s. If the +// two rectangles do not overlap then the zero rectangle will be returned. +func (r Rectangle) Intersect(s Rectangle) Rectangle { + if r.Min.X < s.Min.X { + r.Min.X = s.Min.X + } + if r.Min.Y < s.Min.Y { + r.Min.Y = s.Min.Y + } + if r.Max.X > s.Max.X { + r.Max.X = s.Max.X + } + if r.Max.Y > s.Max.Y { + r.Max.Y = s.Max.Y + } + // Letting r0 and s0 be the values of r and s at the time that the method + // is called, this next line is equivalent to: + // + // if max(r0.Min.X, s0.Min.X) >= min(r0.Max.X, s0.Max.X) || likewiseForY { etc } + if r.Empty() { + return Rectangle{} + } + return r +} + +// Union returns the smallest rectangle that contains both r and s. +func (r Rectangle) Union(s Rectangle) Rectangle { + if r.Empty() { + return s + } + if s.Empty() { + return r + } + if r.Min.X > s.Min.X { + r.Min.X = s.Min.X + } + if r.Min.Y > s.Min.Y { + r.Min.Y = s.Min.Y + } + if r.Max.X < s.Max.X { + r.Max.X = s.Max.X + } + if r.Max.Y < s.Max.Y { + r.Max.Y = s.Max.Y + } + return r +} + +// Empty reports whether the rectangle contains no points. +func (r Rectangle) Empty() bool { + return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y +} + +// Eq reports whether r and s contain the same set of points. All empty +// rectangles are considered equal. +func (r Rectangle) Eq(s Rectangle) bool { + return r == s || r.Empty() && s.Empty() +} + +// Overlaps reports whether r and s have a non-empty intersection. +func (r Rectangle) Overlaps(s Rectangle) bool { + return !r.Empty() && !s.Empty() && + r.Min.X < s.Max.X && s.Min.X < r.Max.X && + r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y +} + +// In reports whether every point in r is in s. +func (r Rectangle) In(s Rectangle) bool { + if r.Empty() { + return true + } + // Note that r.Max is an exclusive bound for r, so that r.In(s) + // does not require that r.Max.In(s). + return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X && + s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y +} + +// Canon returns the canonical version of r. The returned rectangle has minimum +// and maximum coordinates swapped if necessary so that it is well-formed. +func (r Rectangle) Canon() Rectangle { + if r.Max.X < r.Min.X { + r.Min.X, r.Max.X = r.Max.X, r.Min.X + } + if r.Max.Y < r.Min.Y { + r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y + } + return r +} + +// At implements the [Image] interface. +func (r Rectangle) At(x, y int) color.Color { + if (Point{x, y}).In(r) { + return color.Opaque + } + return color.Transparent +} + +// RGBA64At implements the [RGBA64Image] interface. +func (r Rectangle) RGBA64At(x, y int) color.RGBA64 { + if (Point{x, y}).In(r) { + return color.RGBA64{0xffff, 0xffff, 0xffff, 0xffff} + } + return color.RGBA64{} +} + +// Bounds implements the [Image] interface. +func (r Rectangle) Bounds() Rectangle { + return r +} + +// ColorModel implements the [Image] interface. +func (r Rectangle) ColorModel() color.Model { + return color.Alpha16Model +} + +// ZR is the zero [Rectangle]. +// +// Deprecated: Use a literal [image.Rectangle] instead. +var ZR Rectangle + +// Rect is shorthand for [Rectangle]{Pt(x0, y0), [Pt](x1, y1)}. The returned +// rectangle has minimum and maximum coordinates swapped if necessary so that +// it is well-formed. +func Rect(x0, y0, x1, y1 int) Rectangle { + if x0 > x1 { + x0, x1 = x1, x0 + } + if y0 > y1 { + y0, y1 = y1, y0 + } + return Rectangle{Point{x0, y0}, Point{x1, y1}} +} + +// mul3NonNeg returns (x * y * z), unless at least one argument is negative or +// if the computation overflows the int type, in which case it returns -1. +func mul3NonNeg(x int, y int, z int) int { + if (x < 0) || (y < 0) || (z < 0) { + return -1 + } + hi, lo := bits.Mul64(uint64(x), uint64(y)) + if hi != 0 { + return -1 + } + hi, lo = bits.Mul64(lo, uint64(z)) + if hi != 0 { + return -1 + } + a := int(lo) + if (a < 0) || (uint64(a) != lo) { + return -1 + } + return a +} + +// add2NonNeg returns (x + y), unless at least one argument is negative or if +// the computation overflows the int type, in which case it returns -1. +func add2NonNeg(x int, y int) int { + if (x < 0) || (y < 0) { + return -1 + } + a := x + y + if a < 0 { + return -1 + } + return a +} diff --git a/go/src/image/geom_test.go b/go/src/image/geom_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9fede027218c31e54a478cd6a40bd4e34fac577b --- /dev/null +++ b/go/src/image/geom_test.go @@ -0,0 +1,116 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "fmt" + "testing" +) + +func TestRectangle(t *testing.T) { + // in checks that every point in f is in g. + in := func(f, g Rectangle) error { + if !f.In(g) { + return fmt.Errorf("f=%s, f.In(%s): got false, want true", f, g) + } + for y := f.Min.Y; y < f.Max.Y; y++ { + for x := f.Min.X; x < f.Max.X; x++ { + p := Point{x, y} + if !p.In(g) { + return fmt.Errorf("p=%s, p.In(%s): got false, want true", p, g) + } + } + } + return nil + } + + rects := []Rectangle{ + Rect(0, 0, 10, 10), + Rect(10, 0, 20, 10), + Rect(1, 2, 3, 4), + Rect(4, 6, 10, 10), + Rect(2, 3, 12, 5), + Rect(-1, -2, 0, 0), + Rect(-1, -2, 4, 6), + Rect(-10, -20, 30, 40), + Rect(8, 8, 8, 8), + Rect(88, 88, 88, 88), + Rect(6, 5, 4, 3), + } + + // r.Eq(s) should be equivalent to every point in r being in s, and every + // point in s being in r. + for _, r := range rects { + for _, s := range rects { + got := r.Eq(s) + want := in(r, s) == nil && in(s, r) == nil + if got != want { + t.Errorf("Eq: r=%s, s=%s: got %t, want %t", r, s, got, want) + } + } + } + + // The intersection should be the largest rectangle a such that every point + // in a is both in r and in s. + for _, r := range rects { + for _, s := range rects { + a := r.Intersect(s) + if err := in(a, r); err != nil { + t.Errorf("Intersect: r=%s, s=%s, a=%s, a not in r: %v", r, s, a, err) + } + if err := in(a, s); err != nil { + t.Errorf("Intersect: r=%s, s=%s, a=%s, a not in s: %v", r, s, a, err) + } + if isZero, overlaps := a == (Rectangle{}), r.Overlaps(s); isZero == overlaps { + t.Errorf("Intersect: r=%s, s=%s, a=%s: isZero=%t same as overlaps=%t", + r, s, a, isZero, overlaps) + } + largerThanA := [4]Rectangle{a, a, a, a} + largerThanA[0].Min.X-- + largerThanA[1].Min.Y-- + largerThanA[2].Max.X++ + largerThanA[3].Max.Y++ + for i, b := range largerThanA { + if b.Empty() { + // b isn't actually larger than a. + continue + } + if in(b, r) == nil && in(b, s) == nil { + t.Errorf("Intersect: r=%s, s=%s, a=%s, b=%s, i=%d: intersection could be larger", + r, s, a, b, i) + } + } + } + } + + // The union should be the smallest rectangle a such that every point in r + // is in a and every point in s is in a. + for _, r := range rects { + for _, s := range rects { + a := r.Union(s) + if err := in(r, a); err != nil { + t.Errorf("Union: r=%s, s=%s, a=%s, r not in a: %v", r, s, a, err) + } + if err := in(s, a); err != nil { + t.Errorf("Union: r=%s, s=%s, a=%s, s not in a: %v", r, s, a, err) + } + if a.Empty() { + // You can't get any smaller than a. + continue + } + smallerThanA := [4]Rectangle{a, a, a, a} + smallerThanA[0].Min.X++ + smallerThanA[1].Min.Y++ + smallerThanA[2].Max.X-- + smallerThanA[3].Max.Y-- + for i, b := range smallerThanA { + if in(r, b) == nil && in(s, b) == nil { + t.Errorf("Union: r=%s, s=%s, a=%s, b=%s, i=%d: union could be smaller", + r, s, a, b, i) + } + } + } + } +} diff --git a/go/src/image/image.go b/go/src/image/image.go new file mode 100644 index 0000000000000000000000000000000000000000..2cc94075b29ed3286c79c7857ee8fa74340c557c --- /dev/null +++ b/go/src/image/image.go @@ -0,0 +1,1289 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package image implements a basic 2-D image library. +// +// The fundamental interface is called [Image]. An [Image] contains colors, which +// are described in the image/color package. +// +// Values of the [Image] interface are created either by calling functions such +// as [NewRGBA] and [NewPaletted], or by calling [Decode] on an [io.Reader] containing +// image data in a format such as GIF, JPEG or PNG. Decoding any particular +// image format requires the prior registration of a decoder function. +// Registration is typically automatic as a side effect of initializing that +// format's package so that, to decode a PNG image, it suffices to have +// +// import _ "image/png" +// +// in a program's main package. The _ means to import a package purely for its +// initialization side effects. +// +// See "The Go image package" for more details: +// https://golang.org/doc/articles/image_package.html +// +// # Security Considerations +// +// The image package can be used to parse arbitrarily large images, which can +// cause resource exhaustion on machines which do not have enough memory to +// store them. When operating on arbitrary images, [DecodeConfig] should be called +// before [Decode], so that the program can decide whether the image, as defined +// in the returned header, can be safely decoded with the available resources. A +// call to [Decode] which produces an extremely large image, as defined in the +// header returned by [DecodeConfig], is not considered a security issue, +// regardless of whether the image is itself malformed or not. A call to +// [DecodeConfig] which returns a header which does not match the image returned +// by [Decode] may be considered a security issue, and should be reported per the +// [Go Security Policy]. +// +// [Go Security Policy]: https://go.dev/security/policy +package image + +import ( + "image/color" +) + +// Config holds an image's color model and dimensions. +type Config struct { + ColorModel color.Model + Width, Height int +} + +// Image is a finite rectangular grid of [color.Color] values taken from a color +// model. +type Image interface { + // ColorModel returns the Image's color model. + ColorModel() color.Model + // Bounds returns the domain for which At can return non-zero color. + // The bounds do not necessarily contain the point (0, 0). + Bounds() Rectangle + // At returns the color of the pixel at (x, y). + // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid. + // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one. + At(x, y int) color.Color +} + +// RGBA64Image is an [Image] whose pixels can be converted directly to a +// color.RGBA64. +type RGBA64Image interface { + // RGBA64At returns the RGBA64 color of the pixel at (x, y). It is + // equivalent to calling At(x, y).RGBA() and converting the resulting + // 32-bit return values to a color.RGBA64, but it can avoid allocations + // from converting concrete color types to the color.Color interface type. + RGBA64At(x, y int) color.RGBA64 + Image +} + +// PalettedImage is an image whose colors may come from a limited palette. +// If m is a PalettedImage and m.ColorModel() returns a [color.Palette] p, +// then m.At(x, y) should be equivalent to p[m.ColorIndexAt(x, y)]. If m's +// color model is not a color.Palette, then ColorIndexAt's behavior is +// undefined. +type PalettedImage interface { + // ColorIndexAt returns the palette index of the pixel at (x, y). + ColorIndexAt(x, y int) uint8 + Image +} + +// pixelBufferLength returns the length of the []uint8 typed Pix slice field +// for the NewXxx functions. Conceptually, this is just (bpp * width * height), +// but this function panics if at least one of those is negative or if the +// computation would overflow the int type. +// +// This panics instead of returning an error because of backwards +// compatibility. The NewXxx functions do not return an error. +func pixelBufferLength(bytesPerPixel int, r Rectangle, imageTypeName string) int { + totalLength := mul3NonNeg(bytesPerPixel, r.Dx(), r.Dy()) + if totalLength < 0 { + panic("image: New" + imageTypeName + " Rectangle has huge or negative dimensions") + } + return totalLength +} + +// RGBA is an in-memory image whose At method returns [color.RGBA] values. +type RGBA struct { + // Pix holds the image's pixels, in R, G, B, A order. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *RGBA) ColorModel() color.Model { return color.RGBAModel } + +func (p *RGBA) Bounds() Rectangle { return p.Rect } + +func (p *RGBA) At(x, y int) color.Color { + return p.RGBAAt(x, y) +} + +func (p *RGBA) RGBA64At(x, y int) color.RGBA64 { + if !(Point{x, y}.In(p.Rect)) { + return color.RGBA64{} + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + r := uint16(s[0]) + g := uint16(s[1]) + b := uint16(s[2]) + a := uint16(s[3]) + return color.RGBA64{ + (r << 8) | r, + (g << 8) | g, + (b << 8) | b, + (a << 8) | a, + } +} + +func (p *RGBA) RGBAAt(x, y int) color.RGBA { + if !(Point{x, y}.In(p.Rect)) { + return color.RGBA{} + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + return color.RGBA{s[0], s[1], s[2], s[3]} +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *RGBA) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4 +} + +func (p *RGBA) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + c1 := color.RGBAModel.Convert(c).(color.RGBA) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = c1.R + s[1] = c1.G + s[2] = c1.B + s[3] = c1.A +} + +func (p *RGBA) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = uint8(c.R >> 8) + s[1] = uint8(c.G >> 8) + s[2] = uint8(c.B >> 8) + s[3] = uint8(c.A >> 8) +} + +func (p *RGBA) SetRGBA(x, y int, c color.RGBA) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = c.R + s[1] = c.G + s[2] = c.B + s[3] = c.A +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *RGBA) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &RGBA{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &RGBA{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *RGBA) Opaque() bool { + if p.Rect.Empty() { + return true + } + i0, i1 := 3, p.Rect.Dx()*4 + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for i := i0; i < i1; i += 4 { + if p.Pix[i] != 0xff { + return false + } + } + i0 += p.Stride + i1 += p.Stride + } + return true +} + +// NewRGBA returns a new [RGBA] image with the given bounds. +func NewRGBA(r Rectangle) *RGBA { + return &RGBA{ + Pix: make([]uint8, pixelBufferLength(4, r, "RGBA")), + Stride: 4 * r.Dx(), + Rect: r, + } +} + +// RGBA64 is an in-memory image whose At method returns [color.RGBA64] values. +type RGBA64 struct { + // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *RGBA64) ColorModel() color.Model { return color.RGBA64Model } + +func (p *RGBA64) Bounds() Rectangle { return p.Rect } + +func (p *RGBA64) At(x, y int) color.Color { + return p.RGBA64At(x, y) +} + +func (p *RGBA64) RGBA64At(x, y int) color.RGBA64 { + if !(Point{x, y}.In(p.Rect)) { + return color.RGBA64{} + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857 + return color.RGBA64{ + uint16(s[0])<<8 | uint16(s[1]), + uint16(s[2])<<8 | uint16(s[3]), + uint16(s[4])<<8 | uint16(s[5]), + uint16(s[6])<<8 | uint16(s[7]), + } +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *RGBA64) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*8 +} + +func (p *RGBA64) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + c1 := color.RGBA64Model.Convert(c).(color.RGBA64) + s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = uint8(c1.R >> 8) + s[1] = uint8(c1.R) + s[2] = uint8(c1.G >> 8) + s[3] = uint8(c1.G) + s[4] = uint8(c1.B >> 8) + s[5] = uint8(c1.B) + s[6] = uint8(c1.A >> 8) + s[7] = uint8(c1.A) +} + +func (p *RGBA64) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = uint8(c.R >> 8) + s[1] = uint8(c.R) + s[2] = uint8(c.G >> 8) + s[3] = uint8(c.G) + s[4] = uint8(c.B >> 8) + s[5] = uint8(c.B) + s[6] = uint8(c.A >> 8) + s[7] = uint8(c.A) +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *RGBA64) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &RGBA64{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &RGBA64{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *RGBA64) Opaque() bool { + if p.Rect.Empty() { + return true + } + i0, i1 := 6, p.Rect.Dx()*8 + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for i := i0; i < i1; i += 8 { + if p.Pix[i+0] != 0xff || p.Pix[i+1] != 0xff { + return false + } + } + i0 += p.Stride + i1 += p.Stride + } + return true +} + +// NewRGBA64 returns a new [RGBA64] image with the given bounds. +func NewRGBA64(r Rectangle) *RGBA64 { + return &RGBA64{ + Pix: make([]uint8, pixelBufferLength(8, r, "RGBA64")), + Stride: 8 * r.Dx(), + Rect: r, + } +} + +// NRGBA is an in-memory image whose At method returns [color.NRGBA] values. +type NRGBA struct { + // Pix holds the image's pixels, in R, G, B, A order. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *NRGBA) ColorModel() color.Model { return color.NRGBAModel } + +func (p *NRGBA) Bounds() Rectangle { return p.Rect } + +func (p *NRGBA) At(x, y int) color.Color { + return p.NRGBAAt(x, y) +} + +func (p *NRGBA) RGBA64At(x, y int) color.RGBA64 { + r, g, b, a := p.NRGBAAt(x, y).RGBA() + return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} +} + +func (p *NRGBA) NRGBAAt(x, y int) color.NRGBA { + if !(Point{x, y}.In(p.Rect)) { + return color.NRGBA{} + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + return color.NRGBA{s[0], s[1], s[2], s[3]} +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *NRGBA) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4 +} + +func (p *NRGBA) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + c1 := color.NRGBAModel.Convert(c).(color.NRGBA) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = c1.R + s[1] = c1.G + s[2] = c1.B + s[3] = c1.A +} + +func (p *NRGBA) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + r, g, b, a := uint32(c.R), uint32(c.G), uint32(c.B), uint32(c.A) + if (a != 0) && (a != 0xffff) { + r = (r * 0xffff) / a + g = (g * 0xffff) / a + b = (b * 0xffff) / a + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = uint8(r >> 8) + s[1] = uint8(g >> 8) + s[2] = uint8(b >> 8) + s[3] = uint8(a >> 8) +} + +func (p *NRGBA) SetNRGBA(x, y int, c color.NRGBA) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = c.R + s[1] = c.G + s[2] = c.B + s[3] = c.A +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *NRGBA) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &NRGBA{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &NRGBA{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *NRGBA) Opaque() bool { + if p.Rect.Empty() { + return true + } + i0, i1 := 3, p.Rect.Dx()*4 + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for i := i0; i < i1; i += 4 { + if p.Pix[i] != 0xff { + return false + } + } + i0 += p.Stride + i1 += p.Stride + } + return true +} + +// NewNRGBA returns a new [NRGBA] image with the given bounds. +func NewNRGBA(r Rectangle) *NRGBA { + return &NRGBA{ + Pix: make([]uint8, pixelBufferLength(4, r, "NRGBA")), + Stride: 4 * r.Dx(), + Rect: r, + } +} + +// NRGBA64 is an in-memory image whose At method returns [color.NRGBA64] values. +type NRGBA64 struct { + // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *NRGBA64) ColorModel() color.Model { return color.NRGBA64Model } + +func (p *NRGBA64) Bounds() Rectangle { return p.Rect } + +func (p *NRGBA64) At(x, y int) color.Color { + return p.NRGBA64At(x, y) +} + +func (p *NRGBA64) RGBA64At(x, y int) color.RGBA64 { + r, g, b, a := p.NRGBA64At(x, y).RGBA() + return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} +} + +func (p *NRGBA64) NRGBA64At(x, y int) color.NRGBA64 { + if !(Point{x, y}.In(p.Rect)) { + return color.NRGBA64{} + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857 + return color.NRGBA64{ + uint16(s[0])<<8 | uint16(s[1]), + uint16(s[2])<<8 | uint16(s[3]), + uint16(s[4])<<8 | uint16(s[5]), + uint16(s[6])<<8 | uint16(s[7]), + } +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *NRGBA64) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*8 +} + +func (p *NRGBA64) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + c1 := color.NRGBA64Model.Convert(c).(color.NRGBA64) + s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = uint8(c1.R >> 8) + s[1] = uint8(c1.R) + s[2] = uint8(c1.G >> 8) + s[3] = uint8(c1.G) + s[4] = uint8(c1.B >> 8) + s[5] = uint8(c1.B) + s[6] = uint8(c1.A >> 8) + s[7] = uint8(c1.A) +} + +func (p *NRGBA64) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + r, g, b, a := uint32(c.R), uint32(c.G), uint32(c.B), uint32(c.A) + if (a != 0) && (a != 0xffff) { + r = (r * 0xffff) / a + g = (g * 0xffff) / a + b = (b * 0xffff) / a + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = uint8(r >> 8) + s[1] = uint8(r) + s[2] = uint8(g >> 8) + s[3] = uint8(g) + s[4] = uint8(b >> 8) + s[5] = uint8(b) + s[6] = uint8(a >> 8) + s[7] = uint8(a) +} + +func (p *NRGBA64) SetNRGBA64(x, y int, c color.NRGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = uint8(c.R >> 8) + s[1] = uint8(c.R) + s[2] = uint8(c.G >> 8) + s[3] = uint8(c.G) + s[4] = uint8(c.B >> 8) + s[5] = uint8(c.B) + s[6] = uint8(c.A >> 8) + s[7] = uint8(c.A) +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *NRGBA64) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &NRGBA64{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &NRGBA64{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *NRGBA64) Opaque() bool { + if p.Rect.Empty() { + return true + } + i0, i1 := 6, p.Rect.Dx()*8 + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for i := i0; i < i1; i += 8 { + if p.Pix[i+0] != 0xff || p.Pix[i+1] != 0xff { + return false + } + } + i0 += p.Stride + i1 += p.Stride + } + return true +} + +// NewNRGBA64 returns a new [NRGBA64] image with the given bounds. +func NewNRGBA64(r Rectangle) *NRGBA64 { + return &NRGBA64{ + Pix: make([]uint8, pixelBufferLength(8, r, "NRGBA64")), + Stride: 8 * r.Dx(), + Rect: r, + } +} + +// Alpha is an in-memory image whose At method returns [color.Alpha] values. +type Alpha struct { + // Pix holds the image's pixels, as alpha values. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *Alpha) ColorModel() color.Model { return color.AlphaModel } + +func (p *Alpha) Bounds() Rectangle { return p.Rect } + +func (p *Alpha) At(x, y int) color.Color { + return p.AlphaAt(x, y) +} + +func (p *Alpha) RGBA64At(x, y int) color.RGBA64 { + a := uint16(p.AlphaAt(x, y).A) + a |= a << 8 + return color.RGBA64{a, a, a, a} +} + +func (p *Alpha) AlphaAt(x, y int) color.Alpha { + if !(Point{x, y}.In(p.Rect)) { + return color.Alpha{} + } + i := p.PixOffset(x, y) + return color.Alpha{p.Pix[i]} +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *Alpha) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1 +} + +func (p *Alpha) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = color.AlphaModel.Convert(c).(color.Alpha).A +} + +func (p *Alpha) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = uint8(c.A >> 8) +} + +func (p *Alpha) SetAlpha(x, y int, c color.Alpha) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = c.A +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *Alpha) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &Alpha{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &Alpha{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *Alpha) Opaque() bool { + if p.Rect.Empty() { + return true + } + i0, i1 := 0, p.Rect.Dx() + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for i := i0; i < i1; i++ { + if p.Pix[i] != 0xff { + return false + } + } + i0 += p.Stride + i1 += p.Stride + } + return true +} + +// NewAlpha returns a new [Alpha] image with the given bounds. +func NewAlpha(r Rectangle) *Alpha { + return &Alpha{ + Pix: make([]uint8, pixelBufferLength(1, r, "Alpha")), + Stride: 1 * r.Dx(), + Rect: r, + } +} + +// Alpha16 is an in-memory image whose At method returns [color.Alpha16] values. +type Alpha16 struct { + // Pix holds the image's pixels, as alpha values in big-endian format. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *Alpha16) ColorModel() color.Model { return color.Alpha16Model } + +func (p *Alpha16) Bounds() Rectangle { return p.Rect } + +func (p *Alpha16) At(x, y int) color.Color { + return p.Alpha16At(x, y) +} + +func (p *Alpha16) RGBA64At(x, y int) color.RGBA64 { + a := p.Alpha16At(x, y).A + return color.RGBA64{a, a, a, a} +} + +func (p *Alpha16) Alpha16At(x, y int) color.Alpha16 { + if !(Point{x, y}.In(p.Rect)) { + return color.Alpha16{} + } + i := p.PixOffset(x, y) + return color.Alpha16{uint16(p.Pix[i+0])<<8 | uint16(p.Pix[i+1])} +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *Alpha16) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2 +} + +func (p *Alpha16) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + c1 := color.Alpha16Model.Convert(c).(color.Alpha16) + p.Pix[i+0] = uint8(c1.A >> 8) + p.Pix[i+1] = uint8(c1.A) +} + +func (p *Alpha16) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i+0] = uint8(c.A >> 8) + p.Pix[i+1] = uint8(c.A) +} + +func (p *Alpha16) SetAlpha16(x, y int, c color.Alpha16) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i+0] = uint8(c.A >> 8) + p.Pix[i+1] = uint8(c.A) +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *Alpha16) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &Alpha16{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &Alpha16{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *Alpha16) Opaque() bool { + if p.Rect.Empty() { + return true + } + i0, i1 := 0, p.Rect.Dx()*2 + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for i := i0; i < i1; i += 2 { + if p.Pix[i+0] != 0xff || p.Pix[i+1] != 0xff { + return false + } + } + i0 += p.Stride + i1 += p.Stride + } + return true +} + +// NewAlpha16 returns a new [Alpha16] image with the given bounds. +func NewAlpha16(r Rectangle) *Alpha16 { + return &Alpha16{ + Pix: make([]uint8, pixelBufferLength(2, r, "Alpha16")), + Stride: 2 * r.Dx(), + Rect: r, + } +} + +// Gray is an in-memory image whose At method returns [color.Gray] values. +type Gray struct { + // Pix holds the image's pixels, as gray values. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *Gray) ColorModel() color.Model { return color.GrayModel } + +func (p *Gray) Bounds() Rectangle { return p.Rect } + +func (p *Gray) At(x, y int) color.Color { + return p.GrayAt(x, y) +} + +func (p *Gray) RGBA64At(x, y int) color.RGBA64 { + gray := uint16(p.GrayAt(x, y).Y) + gray |= gray << 8 + return color.RGBA64{gray, gray, gray, 0xffff} +} + +func (p *Gray) GrayAt(x, y int) color.Gray { + if !(Point{x, y}.In(p.Rect)) { + return color.Gray{} + } + i := p.PixOffset(x, y) + return color.Gray{p.Pix[i]} +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *Gray) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1 +} + +func (p *Gray) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = color.GrayModel.Convert(c).(color.Gray).Y +} + +func (p *Gray) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + // This formula is the same as in color.grayModel. + gray := (19595*uint32(c.R) + 38470*uint32(c.G) + 7471*uint32(c.B) + 1<<15) >> 24 + i := p.PixOffset(x, y) + p.Pix[i] = uint8(gray) +} + +func (p *Gray) SetGray(x, y int, c color.Gray) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = c.Y +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *Gray) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &Gray{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &Gray{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *Gray) Opaque() bool { + return true +} + +// NewGray returns a new [Gray] image with the given bounds. +func NewGray(r Rectangle) *Gray { + return &Gray{ + Pix: make([]uint8, pixelBufferLength(1, r, "Gray")), + Stride: 1 * r.Dx(), + Rect: r, + } +} + +// Gray16 is an in-memory image whose At method returns [color.Gray16] values. +type Gray16 struct { + // Pix holds the image's pixels, as gray values in big-endian format. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *Gray16) ColorModel() color.Model { return color.Gray16Model } + +func (p *Gray16) Bounds() Rectangle { return p.Rect } + +func (p *Gray16) At(x, y int) color.Color { + return p.Gray16At(x, y) +} + +func (p *Gray16) RGBA64At(x, y int) color.RGBA64 { + gray := p.Gray16At(x, y).Y + return color.RGBA64{gray, gray, gray, 0xffff} +} + +func (p *Gray16) Gray16At(x, y int) color.Gray16 { + if !(Point{x, y}.In(p.Rect)) { + return color.Gray16{} + } + i := p.PixOffset(x, y) + return color.Gray16{uint16(p.Pix[i+0])<<8 | uint16(p.Pix[i+1])} +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *Gray16) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2 +} + +func (p *Gray16) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + c1 := color.Gray16Model.Convert(c).(color.Gray16) + p.Pix[i+0] = uint8(c1.Y >> 8) + p.Pix[i+1] = uint8(c1.Y) +} + +func (p *Gray16) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + // This formula is the same as in color.gray16Model. + gray := (19595*uint32(c.R) + 38470*uint32(c.G) + 7471*uint32(c.B) + 1<<15) >> 16 + i := p.PixOffset(x, y) + p.Pix[i+0] = uint8(gray >> 8) + p.Pix[i+1] = uint8(gray) +} + +func (p *Gray16) SetGray16(x, y int, c color.Gray16) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i+0] = uint8(c.Y >> 8) + p.Pix[i+1] = uint8(c.Y) +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *Gray16) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &Gray16{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &Gray16{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *Gray16) Opaque() bool { + return true +} + +// NewGray16 returns a new [Gray16] image with the given bounds. +func NewGray16(r Rectangle) *Gray16 { + return &Gray16{ + Pix: make([]uint8, pixelBufferLength(2, r, "Gray16")), + Stride: 2 * r.Dx(), + Rect: r, + } +} + +// CMYK is an in-memory image whose At method returns [color.CMYK] values. +type CMYK struct { + // Pix holds the image's pixels, in C, M, Y, K order. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *CMYK) ColorModel() color.Model { return color.CMYKModel } + +func (p *CMYK) Bounds() Rectangle { return p.Rect } + +func (p *CMYK) At(x, y int) color.Color { + return p.CMYKAt(x, y) +} + +func (p *CMYK) RGBA64At(x, y int) color.RGBA64 { + r, g, b, a := p.CMYKAt(x, y).RGBA() + return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} +} + +func (p *CMYK) CMYKAt(x, y int) color.CMYK { + if !(Point{x, y}.In(p.Rect)) { + return color.CMYK{} + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + return color.CMYK{s[0], s[1], s[2], s[3]} +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *CMYK) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4 +} + +func (p *CMYK) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + c1 := color.CMYKModel.Convert(c).(color.CMYK) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = c1.C + s[1] = c1.M + s[2] = c1.Y + s[3] = c1.K +} + +func (p *CMYK) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + cc, mm, yy, kk := color.RGBToCMYK(uint8(c.R>>8), uint8(c.G>>8), uint8(c.B>>8)) + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = cc + s[1] = mm + s[2] = yy + s[3] = kk +} + +func (p *CMYK) SetCMYK(x, y int, c color.CMYK) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857 + s[0] = c.C + s[1] = c.M + s[2] = c.Y + s[3] = c.K +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *CMYK) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &CMYK{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &CMYK{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *CMYK) Opaque() bool { + return true +} + +// NewCMYK returns a new CMYK image with the given bounds. +func NewCMYK(r Rectangle) *CMYK { + return &CMYK{ + Pix: make([]uint8, pixelBufferLength(4, r, "CMYK")), + Stride: 4 * r.Dx(), + Rect: r, + } +} + +// Paletted is an in-memory image of uint8 indices into a given palette. +type Paletted struct { + // Pix holds the image's pixels, as palette indices. The pixel at + // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1]. + Pix []uint8 + // Stride is the Pix stride (in bytes) between vertically adjacent pixels. + Stride int + // Rect is the image's bounds. + Rect Rectangle + // Palette is the image's palette. + Palette color.Palette +} + +func (p *Paletted) ColorModel() color.Model { return p.Palette } + +func (p *Paletted) Bounds() Rectangle { return p.Rect } + +func (p *Paletted) At(x, y int) color.Color { + if len(p.Palette) == 0 { + return nil + } + if !(Point{x, y}.In(p.Rect)) { + return p.Palette[0] + } + i := p.PixOffset(x, y) + return p.Palette[p.Pix[i]] +} + +func (p *Paletted) RGBA64At(x, y int) color.RGBA64 { + if len(p.Palette) == 0 { + return color.RGBA64{} + } + c := color.Color(nil) + if !(Point{x, y}.In(p.Rect)) { + c = p.Palette[0] + } else { + i := p.PixOffset(x, y) + c = p.Palette[p.Pix[i]] + } + r, g, b, a := c.RGBA() + return color.RGBA64{ + uint16(r), + uint16(g), + uint16(b), + uint16(a), + } +} + +// PixOffset returns the index of the first element of Pix that corresponds to +// the pixel at (x, y). +func (p *Paletted) PixOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1 +} + +func (p *Paletted) Set(x, y int, c color.Color) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = uint8(p.Palette.Index(c)) +} + +func (p *Paletted) SetRGBA64(x, y int, c color.RGBA64) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = uint8(p.Palette.Index(c)) +} + +func (p *Paletted) ColorIndexAt(x, y int) uint8 { + if !(Point{x, y}.In(p.Rect)) { + return 0 + } + i := p.PixOffset(x, y) + return p.Pix[i] +} + +func (p *Paletted) SetColorIndex(x, y int, index uint8) { + if !(Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i] = index +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *Paletted) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &Paletted{ + Palette: p.Palette, + } + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &Paletted{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: p.Rect.Intersect(r), + Palette: p.Palette, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *Paletted) Opaque() bool { + var present [256]bool + i0, i1 := 0, p.Rect.Dx() + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, c := range p.Pix[i0:i1] { + present[c] = true + } + i0 += p.Stride + i1 += p.Stride + } + for i, c := range p.Palette { + if !present[i] { + continue + } + _, _, _, a := c.RGBA() + if a != 0xffff { + return false + } + } + return true +} + +// NewPaletted returns a new [Paletted] image with the given width, height and +// palette. +func NewPaletted(r Rectangle, p color.Palette) *Paletted { + return &Paletted{ + Pix: make([]uint8, pixelBufferLength(1, r, "Paletted")), + Stride: 1 * r.Dx(), + Rect: r, + Palette: p, + } +} diff --git a/go/src/image/image_test.go b/go/src/image/image_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f41bcb6c7086f1eb737fdd33cac1cd8135c488a --- /dev/null +++ b/go/src/image/image_test.go @@ -0,0 +1,458 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "image/color" + "image/color/palette" + "testing" +) + +type image interface { + Image + Opaque() bool + Set(int, int, color.Color) + SubImage(Rectangle) Image +} + +func cmp(cm color.Model, c0, c1 color.Color) bool { + r0, g0, b0, a0 := cm.Convert(c0).RGBA() + r1, g1, b1, a1 := cm.Convert(c1).RGBA() + return r0 == r1 && g0 == g1 && b0 == b1 && a0 == a1 +} + +var testImages = []struct { + name string + image func() image +}{ + {"rgba", func() image { return NewRGBA(Rect(0, 0, 10, 10)) }}, + {"rgba64", func() image { return NewRGBA64(Rect(0, 0, 10, 10)) }}, + {"nrgba", func() image { return NewNRGBA(Rect(0, 0, 10, 10)) }}, + {"nrgba64", func() image { return NewNRGBA64(Rect(0, 0, 10, 10)) }}, + {"alpha", func() image { return NewAlpha(Rect(0, 0, 10, 10)) }}, + {"alpha16", func() image { return NewAlpha16(Rect(0, 0, 10, 10)) }}, + {"gray", func() image { return NewGray(Rect(0, 0, 10, 10)) }}, + {"gray16", func() image { return NewGray16(Rect(0, 0, 10, 10)) }}, + {"paletted", func() image { + return NewPaletted(Rect(0, 0, 10, 10), color.Palette{ + Transparent, + Opaque, + }) + }}, +} + +func TestImage(t *testing.T) { + for _, tc := range testImages { + m := tc.image() + if !Rect(0, 0, 10, 10).Eq(m.Bounds()) { + t.Errorf("%T: want bounds %v, got %v", m, Rect(0, 0, 10, 10), m.Bounds()) + continue + } + if !cmp(m.ColorModel(), Transparent, m.At(6, 3)) { + t.Errorf("%T: at (6, 3), want a zero color, got %v", m, m.At(6, 3)) + continue + } + m.Set(6, 3, Opaque) + if !cmp(m.ColorModel(), Opaque, m.At(6, 3)) { + t.Errorf("%T: at (6, 3), want a non-zero color, got %v", m, m.At(6, 3)) + continue + } + if !m.SubImage(Rect(6, 3, 7, 4)).(image).Opaque() { + t.Errorf("%T: at (6, 3) was not opaque", m) + continue + } + m = m.SubImage(Rect(3, 2, 9, 8)).(image) + if !Rect(3, 2, 9, 8).Eq(m.Bounds()) { + t.Errorf("%T: sub-image want bounds %v, got %v", m, Rect(3, 2, 9, 8), m.Bounds()) + continue + } + if !cmp(m.ColorModel(), Opaque, m.At(6, 3)) { + t.Errorf("%T: sub-image at (6, 3), want a non-zero color, got %v", m, m.At(6, 3)) + continue + } + if !cmp(m.ColorModel(), Transparent, m.At(3, 3)) { + t.Errorf("%T: sub-image at (3, 3), want a zero color, got %v", m, m.At(3, 3)) + continue + } + m.Set(3, 3, Opaque) + if !cmp(m.ColorModel(), Opaque, m.At(3, 3)) { + t.Errorf("%T: sub-image at (3, 3), want a non-zero color, got %v", m, m.At(3, 3)) + continue + } + // Test that taking an empty sub-image starting at a corner does not panic. + m.SubImage(Rect(0, 0, 0, 0)) + m.SubImage(Rect(10, 0, 10, 0)) + m.SubImage(Rect(0, 10, 0, 10)) + m.SubImage(Rect(10, 10, 10, 10)) + } +} + +func TestNewXxxBadRectangle(t *testing.T) { + // call calls f(r) and reports whether it ran without panicking. + call := func(f func(Rectangle), r Rectangle) (ok bool) { + defer func() { + if recover() != nil { + ok = false + } + }() + f(r) + return true + } + + testCases := []struct { + name string + f func(Rectangle) + }{ + {"RGBA", func(r Rectangle) { NewRGBA(r) }}, + {"RGBA64", func(r Rectangle) { NewRGBA64(r) }}, + {"NRGBA", func(r Rectangle) { NewNRGBA(r) }}, + {"NRGBA64", func(r Rectangle) { NewNRGBA64(r) }}, + {"Alpha", func(r Rectangle) { NewAlpha(r) }}, + {"Alpha16", func(r Rectangle) { NewAlpha16(r) }}, + {"Gray", func(r Rectangle) { NewGray(r) }}, + {"Gray16", func(r Rectangle) { NewGray16(r) }}, + {"CMYK", func(r Rectangle) { NewCMYK(r) }}, + {"Paletted", func(r Rectangle) { NewPaletted(r, color.Palette{color.Black, color.White}) }}, + {"YCbCr", func(r Rectangle) { NewYCbCr(r, YCbCrSubsampleRatio422) }}, + {"NYCbCrA", func(r Rectangle) { NewNYCbCrA(r, YCbCrSubsampleRatio444) }}, + } + + for _, tc := range testCases { + // Calling NewXxx(r) should fail (panic, since NewXxx doesn't return an + // error) unless r's width and height are both non-negative. + for _, negDx := range []bool{false, true} { + for _, negDy := range []bool{false, true} { + r := Rectangle{ + Min: Point{15, 28}, + Max: Point{16, 29}, + } + if negDx { + r.Max.X = 14 + } + if negDy { + r.Max.Y = 27 + } + + got := call(tc.f, r) + want := !negDx && !negDy + if got != want { + t.Errorf("New%s: negDx=%t, negDy=%t: got %t, want %t", + tc.name, negDx, negDy, got, want) + } + } + } + + // Passing a Rectangle whose width and height is MaxInt should also fail + // (panic), due to overflow. + { + zeroAsUint := uint(0) + maxUint := zeroAsUint - 1 + maxInt := int(maxUint / 2) + got := call(tc.f, Rectangle{ + Min: Point{0, 0}, + Max: Point{maxInt, maxInt}, + }) + if got { + t.Errorf("New%s: overflow: got ok, want !ok", tc.name) + } + } + } +} + +func Test16BitsPerColorChannel(t *testing.T) { + testColorModel := []color.Model{ + color.RGBA64Model, + color.NRGBA64Model, + color.Alpha16Model, + color.Gray16Model, + } + for _, cm := range testColorModel { + c := cm.Convert(color.RGBA64{0x1234, 0x1234, 0x1234, 0x1234}) // Premultiplied alpha. + r, _, _, _ := c.RGBA() + if r != 0x1234 { + t.Errorf("%T: want red value 0x%04x got 0x%04x", c, 0x1234, r) + continue + } + } + testImage := []image{ + NewRGBA64(Rect(0, 0, 10, 10)), + NewNRGBA64(Rect(0, 0, 10, 10)), + NewAlpha16(Rect(0, 0, 10, 10)), + NewGray16(Rect(0, 0, 10, 10)), + } + for _, m := range testImage { + m.Set(1, 2, color.NRGBA64{0xffff, 0xffff, 0xffff, 0x1357}) // Non-premultiplied alpha. + r, _, _, _ := m.At(1, 2).RGBA() + if r != 0x1357 { + t.Errorf("%T: want red value 0x%04x got 0x%04x", m, 0x1357, r) + continue + } + } +} + +func TestRGBA64Image(t *testing.T) { + // memset sets every element of s to v. + memset := func(s []byte, v byte) { + for i := range s { + s[i] = v + } + } + + r := Rect(0, 0, 3, 2) + testCases := []Image{ + NewAlpha(r), + NewAlpha16(r), + NewCMYK(r), + NewGray(r), + NewGray16(r), + NewNRGBA(r), + NewNRGBA64(r), + NewNYCbCrA(r, YCbCrSubsampleRatio444), + NewPaletted(r, palette.Plan9), + NewRGBA(r), + NewRGBA64(r), + NewUniform(color.RGBA64{}), + NewYCbCr(r, YCbCrSubsampleRatio444), + r, + } + for _, tc := range testCases { + switch tc := tc.(type) { + // Most of the concrete image types in the testCases implement the + // draw.RGBA64Image interface: they have a SetRGBA64 method. We use an + // interface literal here, instead of importing "image/draw", to avoid + // an import cycle. + // + // The YCbCr and NYCbCrA types are special-cased. Chroma subsampling + // means that setting one pixel can modify neighboring pixels. They + // don't have Set or SetRGBA64 methods because that side effect could + // be surprising. Here, we just memset the channel buffers instead. + // + // The Uniform and Rectangle types are also special-cased, as they + // don't have a Set or SetRGBA64 method. + case interface { + SetRGBA64(x, y int, c color.RGBA64) + }: + tc.SetRGBA64(1, 1, color.RGBA64{0x7FFF, 0x3FFF, 0x0000, 0x7FFF}) + + case *NYCbCrA: + memset(tc.YCbCr.Y, 0x77) + memset(tc.YCbCr.Cb, 0x88) + memset(tc.YCbCr.Cr, 0x99) + memset(tc.A, 0xAA) + + case *Uniform: + tc.C = color.RGBA64{0x7FFF, 0x3FFF, 0x0000, 0x7FFF} + + case *YCbCr: + memset(tc.Y, 0x77) + memset(tc.Cb, 0x88) + memset(tc.Cr, 0x99) + + case Rectangle: + // No-op. Rectangle pixels' colors are immutable. They're always + // color.Opaque. + + default: + t.Errorf("could not initialize pixels for %T", tc) + continue + } + + // Check that RGBA64At(x, y) is equivalent to At(x, y).RGBA(). + rgba64Image, ok := tc.(RGBA64Image) + if !ok { + t.Errorf("%T is not an RGBA64Image", tc) + continue + } + got := rgba64Image.RGBA64At(1, 1) + wantR, wantG, wantB, wantA := tc.At(1, 1).RGBA() + if (uint32(got.R) != wantR) || (uint32(got.G) != wantG) || + (uint32(got.B) != wantB) || (uint32(got.A) != wantA) { + t.Errorf("%T:\ngot (0x%04X, 0x%04X, 0x%04X, 0x%04X)\n"+ + "want (0x%04X, 0x%04X, 0x%04X, 0x%04X)", tc, + got.R, got.G, got.B, got.A, + wantR, wantG, wantB, wantA) + continue + } + } +} + +func BenchmarkAt(b *testing.B) { + for _, tc := range testImages { + b.Run(tc.name, func(b *testing.B) { + m := tc.image() + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.At(4, 5) + } + }) + } +} + +func BenchmarkSet(b *testing.B) { + c := color.Gray{0xff} + for _, tc := range testImages { + b.Run(tc.name, func(b *testing.B) { + m := tc.image() + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.Set(4, 5, c) + } + }) + } +} + +func BenchmarkRGBAAt(b *testing.B) { + m := NewRGBA(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.RGBAAt(4, 5) + } +} + +func BenchmarkRGBASetRGBA(b *testing.B) { + m := NewRGBA(Rect(0, 0, 10, 10)) + c := color.RGBA{0xff, 0xff, 0xff, 0x13} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetRGBA(4, 5, c) + } +} + +func BenchmarkRGBA64At(b *testing.B) { + m := NewRGBA64(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.RGBA64At(4, 5) + } +} + +func BenchmarkRGBA64SetRGBA64(b *testing.B) { + m := NewRGBA64(Rect(0, 0, 10, 10)) + c := color.RGBA64{0xffff, 0xffff, 0xffff, 0x1357} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetRGBA64(4, 5, c) + } +} + +func BenchmarkNRGBAAt(b *testing.B) { + m := NewNRGBA(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.NRGBAAt(4, 5) + } +} + +func BenchmarkNRGBASetNRGBA(b *testing.B) { + m := NewNRGBA(Rect(0, 0, 10, 10)) + c := color.NRGBA{0xff, 0xff, 0xff, 0x13} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetNRGBA(4, 5, c) + } +} + +func BenchmarkNRGBA64At(b *testing.B) { + m := NewNRGBA64(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.NRGBA64At(4, 5) + } +} + +func BenchmarkNRGBA64SetNRGBA64(b *testing.B) { + m := NewNRGBA64(Rect(0, 0, 10, 10)) + c := color.NRGBA64{0xffff, 0xffff, 0xffff, 0x1357} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetNRGBA64(4, 5, c) + } +} + +func BenchmarkAlphaAt(b *testing.B) { + m := NewAlpha(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.AlphaAt(4, 5) + } +} + +func BenchmarkAlphaSetAlpha(b *testing.B) { + m := NewAlpha(Rect(0, 0, 10, 10)) + c := color.Alpha{0x13} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetAlpha(4, 5, c) + } +} + +func BenchmarkAlpha16At(b *testing.B) { + m := NewAlpha16(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.Alpha16At(4, 5) + } +} + +func BenchmarkAlphaSetAlpha16(b *testing.B) { + m := NewAlpha16(Rect(0, 0, 10, 10)) + c := color.Alpha16{0x13} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetAlpha16(4, 5, c) + } +} + +func BenchmarkGrayAt(b *testing.B) { + m := NewGray(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.GrayAt(4, 5) + } +} + +func BenchmarkGraySetGray(b *testing.B) { + m := NewGray(Rect(0, 0, 10, 10)) + c := color.Gray{0x13} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetGray(4, 5, c) + } +} + +func BenchmarkGray16At(b *testing.B) { + m := NewGray16(Rect(0, 0, 10, 10)) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.Gray16At(4, 5) + } +} + +func BenchmarkGraySetGray16(b *testing.B) { + m := NewGray16(Rect(0, 0, 10, 10)) + c := color.Gray16{0x13} + b.ResetTimer() + + for i := 0; i < b.N; i++ { + m.SetGray16(4, 5, c) + } +} diff --git a/go/src/image/names.go b/go/src/image/names.go new file mode 100644 index 0000000000000000000000000000000000000000..a2968fabe27d275c60d336801deb1f6b26d2cd66 --- /dev/null +++ b/go/src/image/names.go @@ -0,0 +1,58 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "image/color" +) + +var ( + // Black is an opaque black uniform image. + Black = NewUniform(color.Black) + // White is an opaque white uniform image. + White = NewUniform(color.White) + // Transparent is a fully transparent uniform image. + Transparent = NewUniform(color.Transparent) + // Opaque is a fully opaque uniform image. + Opaque = NewUniform(color.Opaque) +) + +// Uniform is an infinite-sized [Image] of uniform color. +// It implements the [color.Color], [color.Model], and [Image] interfaces. +type Uniform struct { + C color.Color +} + +func (c *Uniform) RGBA() (r, g, b, a uint32) { + return c.C.RGBA() +} + +func (c *Uniform) ColorModel() color.Model { + return c +} + +func (c *Uniform) Convert(color.Color) color.Color { + return c.C +} + +func (c *Uniform) Bounds() Rectangle { return Rectangle{Point{-1e9, -1e9}, Point{1e9, 1e9}} } + +func (c *Uniform) At(x, y int) color.Color { return c.C } + +func (c *Uniform) RGBA64At(x, y int) color.RGBA64 { + r, g, b, a := c.C.RGBA() + return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (c *Uniform) Opaque() bool { + _, _, _, a := c.C.RGBA() + return a == 0xffff +} + +// NewUniform returns a new [Uniform] image of the given color. +func NewUniform(c color.Color) *Uniform { + return &Uniform{c} +} diff --git a/go/src/image/ycbcr.go b/go/src/image/ycbcr.go new file mode 100644 index 0000000000000000000000000000000000000000..54333119431d0f756e80b8e9aaa2443fa6c62d97 --- /dev/null +++ b/go/src/image/ycbcr.go @@ -0,0 +1,329 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "image/color" +) + +// YCbCrSubsampleRatio is the chroma subsample ratio used in a YCbCr image. +type YCbCrSubsampleRatio int + +const ( + YCbCrSubsampleRatio444 YCbCrSubsampleRatio = iota + YCbCrSubsampleRatio422 + YCbCrSubsampleRatio420 + YCbCrSubsampleRatio440 + YCbCrSubsampleRatio411 + YCbCrSubsampleRatio410 +) + +func (s YCbCrSubsampleRatio) String() string { + switch s { + case YCbCrSubsampleRatio444: + return "YCbCrSubsampleRatio444" + case YCbCrSubsampleRatio422: + return "YCbCrSubsampleRatio422" + case YCbCrSubsampleRatio420: + return "YCbCrSubsampleRatio420" + case YCbCrSubsampleRatio440: + return "YCbCrSubsampleRatio440" + case YCbCrSubsampleRatio411: + return "YCbCrSubsampleRatio411" + case YCbCrSubsampleRatio410: + return "YCbCrSubsampleRatio410" + } + return "YCbCrSubsampleRatioUnknown" +} + +// YCbCr is an in-memory image of Y'CbCr colors. There is one Y sample per +// pixel, but each Cb and Cr sample can span one or more pixels. +// YStride is the Y slice index delta between vertically adjacent pixels. +// CStride is the Cb and Cr slice index delta between vertically adjacent pixels +// that map to separate chroma samples. +// It is not an absolute requirement, but YStride and len(Y) are typically +// multiples of 8, and: +// +// For 4:4:4, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/1. +// For 4:2:2, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/2. +// For 4:2:0, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/4. +// For 4:4:0, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/2. +// For 4:1:1, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/4. +// For 4:1:0, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/8. +type YCbCr struct { + Y, Cb, Cr []uint8 + YStride int + CStride int + SubsampleRatio YCbCrSubsampleRatio + Rect Rectangle +} + +func (p *YCbCr) ColorModel() color.Model { + return color.YCbCrModel +} + +func (p *YCbCr) Bounds() Rectangle { + return p.Rect +} + +func (p *YCbCr) At(x, y int) color.Color { + return p.YCbCrAt(x, y) +} + +func (p *YCbCr) RGBA64At(x, y int) color.RGBA64 { + r, g, b, a := p.YCbCrAt(x, y).RGBA() + return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} +} + +func (p *YCbCr) YCbCrAt(x, y int) color.YCbCr { + if !(Point{x, y}.In(p.Rect)) { + return color.YCbCr{} + } + yi := p.YOffset(x, y) + ci := p.COffset(x, y) + return color.YCbCr{ + p.Y[yi], + p.Cb[ci], + p.Cr[ci], + } +} + +// YOffset returns the index of the first element of Y that corresponds to +// the pixel at (x, y). +func (p *YCbCr) YOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.YStride + (x - p.Rect.Min.X) +} + +// COffset returns the index of the first element of Cb or Cr that corresponds +// to the pixel at (x, y). +func (p *YCbCr) COffset(x, y int) int { + switch p.SubsampleRatio { + case YCbCrSubsampleRatio422: + return (y-p.Rect.Min.Y)*p.CStride + (x/2 - p.Rect.Min.X/2) + case YCbCrSubsampleRatio420: + return (y/2-p.Rect.Min.Y/2)*p.CStride + (x/2 - p.Rect.Min.X/2) + case YCbCrSubsampleRatio440: + return (y/2-p.Rect.Min.Y/2)*p.CStride + (x - p.Rect.Min.X) + case YCbCrSubsampleRatio411: + return (y-p.Rect.Min.Y)*p.CStride + (x/4 - p.Rect.Min.X/4) + case YCbCrSubsampleRatio410: + return (y/2-p.Rect.Min.Y/2)*p.CStride + (x/4 - p.Rect.Min.X/4) + } + // Default to 4:4:4 subsampling. + return (y-p.Rect.Min.Y)*p.CStride + (x - p.Rect.Min.X) +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *YCbCr) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &YCbCr{ + SubsampleRatio: p.SubsampleRatio, + } + } + yi := p.YOffset(r.Min.X, r.Min.Y) + ci := p.COffset(r.Min.X, r.Min.Y) + return &YCbCr{ + Y: p.Y[yi:], + Cb: p.Cb[ci:], + Cr: p.Cr[ci:], + SubsampleRatio: p.SubsampleRatio, + YStride: p.YStride, + CStride: p.CStride, + Rect: r, + } +} + +func (p *YCbCr) Opaque() bool { + return true +} + +func yCbCrSize(r Rectangle, subsampleRatio YCbCrSubsampleRatio) (w, h, cw, ch int) { + w, h = r.Dx(), r.Dy() + switch subsampleRatio { + case YCbCrSubsampleRatio422: + cw = (r.Max.X+1)/2 - r.Min.X/2 + ch = h + case YCbCrSubsampleRatio420: + cw = (r.Max.X+1)/2 - r.Min.X/2 + ch = (r.Max.Y+1)/2 - r.Min.Y/2 + case YCbCrSubsampleRatio440: + cw = w + ch = (r.Max.Y+1)/2 - r.Min.Y/2 + case YCbCrSubsampleRatio411: + cw = (r.Max.X+3)/4 - r.Min.X/4 + ch = h + case YCbCrSubsampleRatio410: + cw = (r.Max.X+3)/4 - r.Min.X/4 + ch = (r.Max.Y+1)/2 - r.Min.Y/2 + default: + // Default to 4:4:4 subsampling. + cw = w + ch = h + } + return +} + +// NewYCbCr returns a new YCbCr image with the given bounds and subsample +// ratio. +func NewYCbCr(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *YCbCr { + w, h, cw, ch := yCbCrSize(r, subsampleRatio) + + // totalLength should be the same as i2, below, for a valid Rectangle r. + totalLength := add2NonNeg( + mul3NonNeg(1, w, h), + mul3NonNeg(2, cw, ch), + ) + if totalLength < 0 { + panic("image: NewYCbCr Rectangle has huge or negative dimensions") + } + + i0 := w*h + 0*cw*ch + i1 := w*h + 1*cw*ch + i2 := w*h + 2*cw*ch + b := make([]byte, i2) + return &YCbCr{ + Y: b[:i0:i0], + Cb: b[i0:i1:i1], + Cr: b[i1:i2:i2], + SubsampleRatio: subsampleRatio, + YStride: w, + CStride: cw, + Rect: r, + } +} + +// NYCbCrA is an in-memory image of non-alpha-premultiplied Y'CbCr-with-alpha +// colors. A and AStride are analogous to the Y and YStride fields of the +// embedded YCbCr. +type NYCbCrA struct { + YCbCr + A []uint8 + AStride int +} + +func (p *NYCbCrA) ColorModel() color.Model { + return color.NYCbCrAModel +} + +func (p *NYCbCrA) At(x, y int) color.Color { + return p.NYCbCrAAt(x, y) +} + +func (p *NYCbCrA) RGBA64At(x, y int) color.RGBA64 { + r, g, b, a := p.NYCbCrAAt(x, y).RGBA() + return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} +} + +func (p *NYCbCrA) NYCbCrAAt(x, y int) color.NYCbCrA { + if !(Point{X: x, Y: y}.In(p.Rect)) { + return color.NYCbCrA{} + } + yi := p.YOffset(x, y) + ci := p.COffset(x, y) + ai := p.AOffset(x, y) + return color.NYCbCrA{ + color.YCbCr{ + Y: p.Y[yi], + Cb: p.Cb[ci], + Cr: p.Cr[ci], + }, + p.A[ai], + } +} + +// AOffset returns the index of the first element of A that corresponds to the +// pixel at (x, y). +func (p *NYCbCrA) AOffset(x, y int) int { + return (y-p.Rect.Min.Y)*p.AStride + (x - p.Rect.Min.X) +} + +// SubImage returns an image representing the portion of the image p visible +// through r. The returned value shares pixels with the original image. +func (p *NYCbCrA) SubImage(r Rectangle) Image { + r = r.Intersect(p.Rect) + // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside + // either r1 or r2 if the intersection is empty. Without explicitly checking for + // this, the Pix[i:] expression below can panic. + if r.Empty() { + return &NYCbCrA{ + YCbCr: YCbCr{ + SubsampleRatio: p.SubsampleRatio, + }, + } + } + yi := p.YOffset(r.Min.X, r.Min.Y) + ci := p.COffset(r.Min.X, r.Min.Y) + ai := p.AOffset(r.Min.X, r.Min.Y) + return &NYCbCrA{ + YCbCr: YCbCr{ + Y: p.Y[yi:], + Cb: p.Cb[ci:], + Cr: p.Cr[ci:], + SubsampleRatio: p.SubsampleRatio, + YStride: p.YStride, + CStride: p.CStride, + Rect: r, + }, + A: p.A[ai:], + AStride: p.AStride, + } +} + +// Opaque scans the entire image and reports whether it is fully opaque. +func (p *NYCbCrA) Opaque() bool { + if p.Rect.Empty() { + return true + } + i0, i1 := 0, p.Rect.Dx() + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, a := range p.A[i0:i1] { + if a != 0xff { + return false + } + } + i0 += p.AStride + i1 += p.AStride + } + return true +} + +// NewNYCbCrA returns a new [NYCbCrA] image with the given bounds and subsample +// ratio. +func NewNYCbCrA(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *NYCbCrA { + w, h, cw, ch := yCbCrSize(r, subsampleRatio) + + // totalLength should be the same as i3, below, for a valid Rectangle r. + totalLength := add2NonNeg( + mul3NonNeg(2, w, h), + mul3NonNeg(2, cw, ch), + ) + if totalLength < 0 { + panic("image: NewNYCbCrA Rectangle has huge or negative dimension") + } + + i0 := 1*w*h + 0*cw*ch + i1 := 1*w*h + 1*cw*ch + i2 := 1*w*h + 2*cw*ch + i3 := 2*w*h + 2*cw*ch + b := make([]byte, i3) + return &NYCbCrA{ + YCbCr: YCbCr{ + Y: b[:i0:i0], + Cb: b[i0:i1:i1], + Cr: b[i1:i2:i2], + SubsampleRatio: subsampleRatio, + YStride: w, + CStride: cw, + Rect: r, + }, + A: b[i2:], + AStride: w, + } +} diff --git a/go/src/image/ycbcr_test.go b/go/src/image/ycbcr_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4996bc8dcaeeb1d67b5adbdcbf58aa4723179c6e --- /dev/null +++ b/go/src/image/ycbcr_test.go @@ -0,0 +1,133 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "image/color" + "testing" +) + +func TestYCbCr(t *testing.T) { + rects := []Rectangle{ + Rect(0, 0, 16, 16), + Rect(1, 0, 16, 16), + Rect(0, 1, 16, 16), + Rect(1, 1, 16, 16), + Rect(1, 1, 15, 16), + Rect(1, 1, 16, 15), + Rect(1, 1, 15, 15), + Rect(2, 3, 14, 15), + Rect(7, 0, 7, 16), + Rect(0, 8, 16, 8), + Rect(0, 0, 10, 11), + Rect(5, 6, 16, 16), + Rect(7, 7, 8, 8), + Rect(7, 8, 8, 9), + Rect(8, 7, 9, 8), + Rect(8, 8, 9, 9), + Rect(7, 7, 17, 17), + Rect(8, 8, 17, 17), + Rect(9, 9, 17, 17), + Rect(10, 10, 17, 17), + } + subsampleRatios := []YCbCrSubsampleRatio{ + YCbCrSubsampleRatio444, + YCbCrSubsampleRatio422, + YCbCrSubsampleRatio420, + YCbCrSubsampleRatio440, + YCbCrSubsampleRatio411, + YCbCrSubsampleRatio410, + } + deltas := []Point{ + Pt(0, 0), + Pt(1000, 1001), + Pt(5001, -400), + Pt(-701, -801), + } + for _, r := range rects { + for _, subsampleRatio := range subsampleRatios { + for _, delta := range deltas { + testYCbCr(t, r, subsampleRatio, delta) + } + } + if testing.Short() { + break + } + } +} + +func testYCbCr(t *testing.T, r Rectangle, subsampleRatio YCbCrSubsampleRatio, delta Point) { + // Create a YCbCr image m, whose bounds are r translated by (delta.X, delta.Y). + r1 := r.Add(delta) + m := NewYCbCr(r1, subsampleRatio) + + // Test that the image buffer is reasonably small even if (delta.X, delta.Y) is far from the origin. + if len(m.Y) > 100*100 { + t.Errorf("r=%v, subsampleRatio=%v, delta=%v: image buffer is too large", + r, subsampleRatio, delta) + return + } + + // Initialize m's pixels. For 422 and 420 subsampling, some of the Cb and Cr elements + // will be set multiple times. That's OK. We just want to avoid a uniform image. + for y := r1.Min.Y; y < r1.Max.Y; y++ { + for x := r1.Min.X; x < r1.Max.X; x++ { + yi := m.YOffset(x, y) + ci := m.COffset(x, y) + m.Y[yi] = uint8(16*y + x) + m.Cb[ci] = uint8(y + 16*x) + m.Cr[ci] = uint8(y + 16*x) + } + } + + // Make various sub-images of m. + for y0 := delta.Y + 3; y0 < delta.Y+7; y0++ { + for y1 := delta.Y + 8; y1 < delta.Y+13; y1++ { + for x0 := delta.X + 3; x0 < delta.X+7; x0++ { + for x1 := delta.X + 8; x1 < delta.X+13; x1++ { + subRect := Rect(x0, y0, x1, y1) + sub := m.SubImage(subRect).(*YCbCr) + + // For each point in the sub-image's bounds, check that m.At(x, y) equals sub.At(x, y). + for y := sub.Rect.Min.Y; y < sub.Rect.Max.Y; y++ { + for x := sub.Rect.Min.X; x < sub.Rect.Max.X; x++ { + color0 := m.At(x, y).(color.YCbCr) + color1 := sub.At(x, y).(color.YCbCr) + if color0 != color1 { + t.Errorf("r=%v, subsampleRatio=%v, delta=%v, x=%d, y=%d, color0=%v, color1=%v", + r, subsampleRatio, delta, x, y, color0, color1) + return + } + } + } + } + } + } + } +} + +func TestYCbCrSlicesDontOverlap(t *testing.T) { + m := NewYCbCr(Rect(0, 0, 8, 8), YCbCrSubsampleRatio420) + names := []string{"Y", "Cb", "Cr"} + slices := [][]byte{ + m.Y[:cap(m.Y)], + m.Cb[:cap(m.Cb)], + m.Cr[:cap(m.Cr)], + } + for i, slice := range slices { + want := uint8(10 + i) + for j := range slice { + slice[j] = want + } + } + for i, slice := range slices { + want := uint8(10 + i) + for j, got := range slice { + if got != want { + t.Fatalf("m.%s[%d]: got %d, want %d", names[i], j, got, want) + } + } + } +} diff --git a/go/src/io/example_test.go b/go/src/io/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..818020e9dec6dd1b11456d996f123403b8b9bcdf --- /dev/null +++ b/go/src/io/example_test.go @@ -0,0 +1,284 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package io_test + +import ( + "fmt" + "io" + "log" + "os" + "strings" +) + +func ExampleCopy() { + r := strings.NewReader("some io.Reader stream to be read\n") + + if _, err := io.Copy(os.Stdout, r); err != nil { + log.Fatal(err) + } + + // Output: + // some io.Reader stream to be read +} + +func ExampleCopyBuffer() { + r1 := strings.NewReader("first reader\n") + r2 := strings.NewReader("second reader\n") + buf := make([]byte, 8) + + // buf is used here... + if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil { + log.Fatal(err) + } + + // ... reused here also. No need to allocate an extra buffer. + if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil { + log.Fatal(err) + } + + // Output: + // first reader + // second reader +} + +func ExampleCopyN() { + r := strings.NewReader("some io.Reader stream to be read") + + if _, err := io.CopyN(os.Stdout, r, 4); err != nil { + log.Fatal(err) + } + + // Output: + // some +} + +func ExampleReadAtLeast() { + r := strings.NewReader("some io.Reader stream to be read\n") + + buf := make([]byte, 14) + if _, err := io.ReadAtLeast(r, buf, 4); err != nil { + log.Fatal(err) + } + fmt.Printf("%s\n", buf) + + // buffer smaller than minimal read size. + shortBuf := make([]byte, 3) + if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil { + fmt.Println("error:", err) + } + + // minimal read size bigger than io.Reader stream + longBuf := make([]byte, 64) + if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil { + fmt.Println("error:", err) + } + + // Output: + // some io.Reader + // error: short buffer + // error: unexpected EOF +} + +func ExampleReadFull() { + r := strings.NewReader("some io.Reader stream to be read\n") + + buf := make([]byte, 4) + if _, err := io.ReadFull(r, buf); err != nil { + log.Fatal(err) + } + fmt.Printf("%s\n", buf) + + // minimal read size bigger than io.Reader stream + longBuf := make([]byte, 64) + if _, err := io.ReadFull(r, longBuf); err != nil { + fmt.Println("error:", err) + } + + // Output: + // some + // error: unexpected EOF +} + +func ExampleWriteString() { + if _, err := io.WriteString(os.Stdout, "Hello World"); err != nil { + log.Fatal(err) + } + + // Output: Hello World +} + +func ExampleLimitReader() { + r := strings.NewReader("some io.Reader stream to be read\n") + lr := io.LimitReader(r, 4) + + if _, err := io.Copy(os.Stdout, lr); err != nil { + log.Fatal(err) + } + + // Output: + // some +} + +func ExampleMultiReader() { + r1 := strings.NewReader("first reader ") + r2 := strings.NewReader("second reader ") + r3 := strings.NewReader("third reader\n") + r := io.MultiReader(r1, r2, r3) + + if _, err := io.Copy(os.Stdout, r); err != nil { + log.Fatal(err) + } + + // Output: + // first reader second reader third reader +} + +func ExampleTeeReader() { + var r io.Reader = strings.NewReader("some io.Reader stream to be read\n") + + r = io.TeeReader(r, os.Stdout) + + // Everything read from r will be copied to stdout. + if _, err := io.ReadAll(r); err != nil { + log.Fatal(err) + } + + // Output: + // some io.Reader stream to be read +} + +func ExampleSectionReader() { + r := strings.NewReader("some io.Reader stream to be read\n") + s := io.NewSectionReader(r, 5, 17) + + if _, err := io.Copy(os.Stdout, s); err != nil { + log.Fatal(err) + } + + // Output: + // io.Reader stream +} + +func ExampleSectionReader_Read() { + r := strings.NewReader("some io.Reader stream to be read\n") + s := io.NewSectionReader(r, 5, 17) + + buf := make([]byte, 9) + if _, err := s.Read(buf); err != nil { + log.Fatal(err) + } + + fmt.Printf("%s\n", buf) + + // Output: + // io.Reader +} + +func ExampleSectionReader_ReadAt() { + r := strings.NewReader("some io.Reader stream to be read\n") + s := io.NewSectionReader(r, 5, 17) + + buf := make([]byte, 6) + if _, err := s.ReadAt(buf, 10); err != nil { + log.Fatal(err) + } + + fmt.Printf("%s\n", buf) + + // Output: + // stream +} + +func ExampleSectionReader_Seek() { + r := strings.NewReader("some io.Reader stream to be read\n") + s := io.NewSectionReader(r, 5, 17) + + if _, err := s.Seek(10, io.SeekStart); err != nil { + log.Fatal(err) + } + + if _, err := io.Copy(os.Stdout, s); err != nil { + log.Fatal(err) + } + + // Output: + // stream +} + +func ExampleSectionReader_Size() { + r := strings.NewReader("some io.Reader stream to be read\n") + s := io.NewSectionReader(r, 5, 17) + + fmt.Println(s.Size()) + + // Output: + // 17 +} + +func ExampleSeeker_Seek() { + r := strings.NewReader("some io.Reader stream to be read\n") + + r.Seek(5, io.SeekStart) // move to the 5th char from the start + if _, err := io.Copy(os.Stdout, r); err != nil { + log.Fatal(err) + } + + r.Seek(-5, io.SeekEnd) + if _, err := io.Copy(os.Stdout, r); err != nil { + log.Fatal(err) + } + + // Output: + // io.Reader stream to be read + // read +} + +func ExampleMultiWriter() { + r := strings.NewReader("some io.Reader stream to be read\n") + + var buf1, buf2 strings.Builder + w := io.MultiWriter(&buf1, &buf2) + + if _, err := io.Copy(w, r); err != nil { + log.Fatal(err) + } + + fmt.Print(buf1.String()) + fmt.Print(buf2.String()) + + // Output: + // some io.Reader stream to be read + // some io.Reader stream to be read +} + +func ExamplePipe() { + r, w := io.Pipe() + + go func() { + fmt.Fprint(w, "some io.Reader stream to be read\n") + w.Close() + }() + + if _, err := io.Copy(os.Stdout, r); err != nil { + log.Fatal(err) + } + + // Output: + // some io.Reader stream to be read +} + +func ExampleReadAll() { + r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.") + + b, err := io.ReadAll(r) + if err != nil { + log.Fatal(err) + } + + fmt.Printf("%s", b) + + // Output: + // Go is a general-purpose language designed with systems programming in mind. +} diff --git a/go/src/io/export_test.go b/go/src/io/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..06853f975f577f15c3b3a2f532a195ce8b4679e6 --- /dev/null +++ b/go/src/io/export_test.go @@ -0,0 +1,10 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package io + +// exported for test +var ErrInvalidWrite = errInvalidWrite +var ErrWhence = errWhence +var ErrOffset = errOffset diff --git a/go/src/io/io.go b/go/src/io/io.go new file mode 100644 index 0000000000000000000000000000000000000000..5b039e985789b77ddfdbbd75e9962b1c29293b86 --- /dev/null +++ b/go/src/io/io.go @@ -0,0 +1,750 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package io provides basic interfaces to I/O primitives. +// Its primary job is to wrap existing implementations of such primitives, +// such as those in package os, into shared public interfaces that +// abstract the functionality, plus some other related primitives. +// +// Because these interfaces and primitives wrap lower-level operations with +// various implementations, unless otherwise informed clients should not +// assume they are safe for parallel execution. +package io + +import ( + "errors" + "sync" +) + +// Seek whence values. +const ( + SeekStart = 0 // seek relative to the origin of the file + SeekCurrent = 1 // seek relative to the current offset + SeekEnd = 2 // seek relative to the end +) + +// ErrShortWrite means that a write accepted fewer bytes than requested +// but failed to return an explicit error. +var ErrShortWrite = errors.New("short write") + +// errInvalidWrite means that a write returned an impossible count. +var errInvalidWrite = errors.New("invalid write result") + +// ErrShortBuffer means that a read required a longer buffer than was provided. +var ErrShortBuffer = errors.New("short buffer") + +// EOF is the error returned by Read when no more input is available. +// (Read must return EOF itself, not an error wrapping EOF, +// because callers will test for EOF using ==.) +// Functions should return EOF only to signal a graceful end of input. +// If the EOF occurs unexpectedly in a structured data stream, +// the appropriate error is either [ErrUnexpectedEOF] or some other error +// giving more detail. +var EOF = errors.New("EOF") + +// ErrUnexpectedEOF means that EOF was encountered in the +// middle of reading a fixed-size block or data structure. +var ErrUnexpectedEOF = errors.New("unexpected EOF") + +// ErrNoProgress is returned by some clients of a [Reader] when +// many calls to Read have failed to return any data or error, +// usually the sign of a broken [Reader] implementation. +var ErrNoProgress = errors.New("multiple Read calls return no data or error") + +// Reader is the interface that wraps the basic Read method. +// +// Read reads up to len(p) bytes into p. It returns the number of bytes +// read (0 <= n <= len(p)) and any error encountered. Even if Read +// returns n < len(p), it may use all of p as scratch space during the call. +// If some data is available but not len(p) bytes, Read conventionally +// returns what is available instead of waiting for more. +// +// When Read encounters an error or end-of-file condition after +// successfully reading n > 0 bytes, it returns the number of +// bytes read. It may return the (non-nil) error from the same call +// or return the error (and n == 0) from a subsequent call. +// An instance of this general case is that a Reader returning +// a non-zero number of bytes at the end of the input stream may +// return either err == EOF or err == nil. The next Read should +// return 0, EOF. +// +// Callers should always process the n > 0 bytes returned before +// considering the error err. Doing so correctly handles I/O errors +// that happen after reading some bytes and also both of the +// allowed EOF behaviors. +// +// If len(p) == 0, Read should always return n == 0. It may return a +// non-nil error if some error condition is known, such as EOF. +// +// Implementations of Read are discouraged from returning a +// zero byte count with a nil error, except when len(p) == 0. +// Callers should treat a return of 0 and nil as indicating that +// nothing happened; in particular it does not indicate EOF. +// +// Implementations must not retain p. +type Reader interface { + Read(p []byte) (n int, err error) +} + +// Writer is the interface that wraps the basic Write method. +// +// Write writes len(p) bytes from p to the underlying data stream. +// It returns the number of bytes written from p (0 <= n <= len(p)) +// and any error encountered that caused the write to stop early. +// Write must return a non-nil error if it returns n < len(p). +// Write must not modify the slice data, even temporarily. +// +// Implementations must not retain p. +type Writer interface { + Write(p []byte) (n int, err error) +} + +// Closer is the interface that wraps the basic Close method. +// +// The behavior of Close after the first call is undefined. +// Specific implementations may document their own behavior. +type Closer interface { + Close() error +} + +// Seeker is the interface that wraps the basic Seek method. +// +// Seek sets the offset for the next Read or Write to offset, +// interpreted according to whence: +// [SeekStart] means relative to the start of the file, +// [SeekCurrent] means relative to the current offset, and +// [SeekEnd] means relative to the end +// (for example, offset = -2 specifies the penultimate byte of the file). +// Seek returns the new offset relative to the start of the +// file or an error, if any. +// +// Seeking to an offset before the start of the file is an error. +// Seeking to any positive offset may be allowed, but if the new offset exceeds +// the size of the underlying object the behavior of subsequent I/O operations +// is implementation-dependent. +type Seeker interface { + Seek(offset int64, whence int) (int64, error) +} + +// ReadWriter is the interface that groups the basic Read and Write methods. +type ReadWriter interface { + Reader + Writer +} + +// ReadCloser is the interface that groups the basic Read and Close methods. +type ReadCloser interface { + Reader + Closer +} + +// WriteCloser is the interface that groups the basic Write and Close methods. +type WriteCloser interface { + Writer + Closer +} + +// ReadWriteCloser is the interface that groups the basic Read, Write and Close methods. +type ReadWriteCloser interface { + Reader + Writer + Closer +} + +// ReadSeeker is the interface that groups the basic Read and Seek methods. +type ReadSeeker interface { + Reader + Seeker +} + +// ReadSeekCloser is the interface that groups the basic Read, Seek and Close +// methods. +type ReadSeekCloser interface { + Reader + Seeker + Closer +} + +// WriteSeeker is the interface that groups the basic Write and Seek methods. +type WriteSeeker interface { + Writer + Seeker +} + +// ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods. +type ReadWriteSeeker interface { + Reader + Writer + Seeker +} + +// ReaderFrom is the interface that wraps the ReadFrom method. +// +// ReadFrom reads data from r until EOF or error. +// The return value n is the number of bytes read. +// Any error except EOF encountered during the read is also returned. +// +// The [Copy] function uses [ReaderFrom] if available. +type ReaderFrom interface { + ReadFrom(r Reader) (n int64, err error) +} + +// WriterTo is the interface that wraps the WriteTo method. +// +// WriteTo writes data to w until there's no more data to write or +// when an error occurs. The return value n is the number of bytes +// written. Any error encountered during the write is also returned. +// +// The Copy function uses WriterTo if available. +type WriterTo interface { + WriteTo(w Writer) (n int64, err error) +} + +// ReaderAt is the interface that wraps the basic ReadAt method. +// +// ReadAt reads len(p) bytes into p starting at offset off in the +// underlying input source. It returns the number of bytes +// read (0 <= n <= len(p)) and any error encountered. +// +// When ReadAt returns n < len(p), it returns a non-nil error +// explaining why more bytes were not returned. In this respect, +// ReadAt is stricter than Read. +// +// Even if ReadAt returns n < len(p), it may use all of p as scratch +// space during the call. If some data is available but not len(p) bytes, +// ReadAt blocks until either all the data is available or an error occurs. +// In this respect ReadAt is different from Read. +// +// If the n = len(p) bytes returned by ReadAt are at the end of the +// input source, ReadAt may return either err == EOF or err == nil. +// +// If ReadAt is reading from an input source with a seek offset, +// ReadAt should not affect nor be affected by the underlying +// seek offset. +// +// Clients of ReadAt can execute parallel ReadAt calls on the +// same input source. +// +// Implementations must not retain p. +type ReaderAt interface { + ReadAt(p []byte, off int64) (n int, err error) +} + +// WriterAt is the interface that wraps the basic WriteAt method. +// +// WriteAt writes len(p) bytes from p to the underlying data stream +// at offset off. It returns the number of bytes written from p (0 <= n <= len(p)) +// and any error encountered that caused the write to stop early. +// WriteAt must return a non-nil error if it returns n < len(p). +// +// If WriteAt is writing to a destination with a seek offset, +// WriteAt should not affect nor be affected by the underlying +// seek offset. +// +// Clients of WriteAt can execute parallel WriteAt calls on the same +// destination if the ranges do not overlap. +// +// Implementations must not retain p. +type WriterAt interface { + WriteAt(p []byte, off int64) (n int, err error) +} + +// ByteReader is the interface that wraps the ReadByte method. +// +// ReadByte reads and returns the next byte from the input or +// any error encountered. If ReadByte returns an error, no input +// byte was consumed, and the returned byte value is undefined. +// +// ReadByte provides an efficient interface for byte-at-time +// processing. A [Reader] that does not implement ByteReader +// can be wrapped using bufio.NewReader to add this method. +type ByteReader interface { + ReadByte() (byte, error) +} + +// ByteScanner is the interface that adds the UnreadByte method to the +// basic ReadByte method. +// +// UnreadByte causes the next call to ReadByte to return the last byte read. +// If the last operation was not a successful call to ReadByte, UnreadByte may +// return an error, unread the last byte read (or the byte prior to the +// last-unread byte), or (in implementations that support the [Seeker] interface) +// seek to one byte before the current offset. +type ByteScanner interface { + ByteReader + UnreadByte() error +} + +// ByteWriter is the interface that wraps the WriteByte method. +type ByteWriter interface { + WriteByte(c byte) error +} + +// RuneReader is the interface that wraps the ReadRune method. +// +// ReadRune reads a single encoded Unicode character +// and returns the rune and its size in bytes. If no character is +// available, err will be set. +type RuneReader interface { + ReadRune() (r rune, size int, err error) +} + +// RuneScanner is the interface that adds the UnreadRune method to the +// basic ReadRune method. +// +// UnreadRune causes the next call to ReadRune to return the last rune read. +// If the last operation was not a successful call to ReadRune, UnreadRune may +// return an error, unread the last rune read (or the rune prior to the +// last-unread rune), or (in implementations that support the [Seeker] interface) +// seek to the start of the rune before the current offset. +type RuneScanner interface { + RuneReader + UnreadRune() error +} + +// StringWriter is the interface that wraps the WriteString method. +type StringWriter interface { + WriteString(s string) (n int, err error) +} + +// WriteString writes the contents of the string s to w, which accepts a slice of bytes. +// If w implements [StringWriter], [StringWriter.WriteString] is invoked directly. +// Otherwise, [Writer.Write] is called exactly once. +func WriteString(w Writer, s string) (n int, err error) { + if sw, ok := w.(StringWriter); ok { + return sw.WriteString(s) + } + return w.Write([]byte(s)) +} + +// ReadAtLeast reads from r into buf until it has read at least min bytes. +// It returns the number of bytes copied and an error if fewer bytes were read. +// The error is EOF only if no bytes were read. +// If an EOF happens after reading fewer than min bytes, +// ReadAtLeast returns [ErrUnexpectedEOF]. +// If min is greater than the length of buf, ReadAtLeast returns [ErrShortBuffer]. +// On return, n >= min if and only if err == nil. +// If r returns an error having read at least min bytes, the error is dropped. +func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) { + if len(buf) < min { + return 0, ErrShortBuffer + } + for n < min && err == nil { + var nn int + nn, err = r.Read(buf[n:]) + n += nn + } + if n >= min { + err = nil + } else if n > 0 && err == EOF { + err = ErrUnexpectedEOF + } + return +} + +// ReadFull reads exactly len(buf) bytes from r into buf. +// It returns the number of bytes copied and an error if fewer bytes were read. +// The error is EOF only if no bytes were read. +// If an EOF happens after reading some but not all the bytes, +// ReadFull returns [ErrUnexpectedEOF]. +// On return, n == len(buf) if and only if err == nil. +// If r returns an error having read at least len(buf) bytes, the error is dropped. +func ReadFull(r Reader, buf []byte) (n int, err error) { + return ReadAtLeast(r, buf, len(buf)) +} + +// CopyN copies n bytes (or until an error) from src to dst. +// It returns the number of bytes copied and the earliest +// error encountered while copying. +// On return, written == n if and only if err == nil. +// +// If dst implements [ReaderFrom], the copy is implemented using it. +func CopyN(dst Writer, src Reader, n int64) (written int64, err error) { + written, err = Copy(dst, LimitReader(src, n)) + if written == n { + return n, nil + } + if written < n && err == nil { + // src stopped early; must have been EOF. + err = EOF + } + return +} + +// Copy copies from src to dst until either EOF is reached +// on src or an error occurs. It returns the number of bytes +// copied and the first error encountered while copying, if any. +// +// A successful Copy returns err == nil, not err == EOF. +// Because Copy is defined to read from src until EOF, it does +// not treat an EOF from Read as an error to be reported. +// +// If src implements [WriterTo], +// the copy is implemented by calling src.WriteTo(dst). +// Otherwise, if dst implements [ReaderFrom], +// the copy is implemented by calling dst.ReadFrom(src). +func Copy(dst Writer, src Reader) (written int64, err error) { + return copyBuffer(dst, src, nil) +} + +// CopyBuffer is identical to Copy except that it stages through the +// provided buffer (if one is required) rather than allocating a +// temporary one. If buf is nil, one is allocated; otherwise if it has +// zero length, CopyBuffer panics. +// +// If either src implements [WriterTo] or dst implements [ReaderFrom], +// buf will not be used to perform the copy. +func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) { + if buf != nil && len(buf) == 0 { + panic("empty buffer in CopyBuffer") + } + return copyBuffer(dst, src, buf) +} + +// copyBuffer is the actual implementation of Copy and CopyBuffer. +// if buf is nil, one is allocated. +func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) { + // If the reader has a WriteTo method, use it to do the copy. + // Avoids an allocation and a copy. + if wt, ok := src.(WriterTo); ok { + return wt.WriteTo(dst) + } + // Similarly, if the writer has a ReadFrom method, use it to do the copy. + if rf, ok := dst.(ReaderFrom); ok { + return rf.ReadFrom(src) + } + if buf == nil { + size := 32 * 1024 + if l, ok := src.(*LimitedReader); ok && int64(size) > l.N { + if l.N < 1 { + size = 1 + } else { + size = int(l.N) + } + } + buf = make([]byte, size) + } + for { + nr, er := src.Read(buf) + if nr > 0 { + nw, ew := dst.Write(buf[0:nr]) + if nw < 0 || nr < nw { + nw = 0 + if ew == nil { + ew = errInvalidWrite + } + } + written += int64(nw) + if ew != nil { + err = ew + break + } + if nr != nw { + err = ErrShortWrite + break + } + } + if er != nil { + if er != EOF { + err = er + } + break + } + } + return written, err +} + +// LimitReader returns a Reader that reads from r +// but stops with EOF after n bytes. +// The underlying implementation is a *LimitedReader. +func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} } + +// A LimitedReader reads from R but limits the amount of +// data returned to just N bytes. Each call to Read +// updates N to reflect the new amount remaining. +// Read returns EOF when N <= 0 or when the underlying R returns EOF. +type LimitedReader struct { + R Reader // underlying reader + N int64 // max bytes remaining +} + +func (l *LimitedReader) Read(p []byte) (n int, err error) { + if l.N <= 0 { + return 0, EOF + } + if int64(len(p)) > l.N { + p = p[0:l.N] + } + n, err = l.R.Read(p) + l.N -= int64(n) + return +} + +// NewSectionReader returns a [SectionReader] that reads from r +// starting at offset off and stops with EOF after n bytes. +func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader { + var remaining int64 + const maxint64 = 1<<63 - 1 + if off <= maxint64-n { + remaining = n + off + } else { + // Overflow, with no way to return error. + // Assume we can read up to an offset of 1<<63 - 1. + remaining = maxint64 + } + return &SectionReader{r, off, off, remaining, n} +} + +// SectionReader implements Read, Seek, and ReadAt on a section +// of an underlying [ReaderAt]. +type SectionReader struct { + r ReaderAt // constant after creation + base int64 // constant after creation + off int64 + limit int64 // constant after creation + n int64 // constant after creation +} + +func (s *SectionReader) Read(p []byte) (n int, err error) { + if s.off >= s.limit { + return 0, EOF + } + if max := s.limit - s.off; int64(len(p)) > max { + p = p[0:max] + } + n, err = s.r.ReadAt(p, s.off) + s.off += int64(n) + return +} + +var errWhence = errors.New("Seek: invalid whence") +var errOffset = errors.New("Seek: invalid offset") + +func (s *SectionReader) Seek(offset int64, whence int) (int64, error) { + switch whence { + default: + return 0, errWhence + case SeekStart: + offset += s.base + case SeekCurrent: + offset += s.off + case SeekEnd: + offset += s.limit + } + if offset < s.base { + return 0, errOffset + } + s.off = offset + return offset - s.base, nil +} + +func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) { + if off < 0 || off >= s.Size() { + return 0, EOF + } + off += s.base + if max := s.limit - off; int64(len(p)) > max { + p = p[0:max] + n, err = s.r.ReadAt(p, off) + if err == nil { + err = EOF + } + return n, err + } + return s.r.ReadAt(p, off) +} + +// Size returns the size of the section in bytes. +func (s *SectionReader) Size() int64 { return s.limit - s.base } + +// Outer returns the underlying [ReaderAt] and offsets for the section. +// +// The returned values are the same that were passed to [NewSectionReader] +// when the [SectionReader] was created. +func (s *SectionReader) Outer() (r ReaderAt, off int64, n int64) { + return s.r, s.base, s.n +} + +// An OffsetWriter maps writes at offset base to offset base+off in the underlying writer. +type OffsetWriter struct { + w WriterAt + base int64 // the original offset + off int64 // the current offset +} + +// NewOffsetWriter returns an [OffsetWriter] that writes to w +// starting at offset off. +func NewOffsetWriter(w WriterAt, off int64) *OffsetWriter { + return &OffsetWriter{w, off, off} +} + +func (o *OffsetWriter) Write(p []byte) (n int, err error) { + n, err = o.w.WriteAt(p, o.off) + o.off += int64(n) + return +} + +func (o *OffsetWriter) WriteAt(p []byte, off int64) (n int, err error) { + if off < 0 { + return 0, errOffset + } + + off += o.base + return o.w.WriteAt(p, off) +} + +func (o *OffsetWriter) Seek(offset int64, whence int) (int64, error) { + switch whence { + default: + return 0, errWhence + case SeekStart: + offset += o.base + case SeekCurrent: + offset += o.off + } + if offset < o.base { + return 0, errOffset + } + o.off = offset + return offset - o.base, nil +} + +// TeeReader returns a [Reader] that writes to w what it reads from r. +// All reads from r performed through it are matched with +// corresponding writes to w. There is no internal buffering - +// the write must complete before the read completes. +// Any error encountered while writing is reported as a read error. +func TeeReader(r Reader, w Writer) Reader { + return &teeReader{r, w} +} + +type teeReader struct { + r Reader + w Writer +} + +func (t *teeReader) Read(p []byte) (n int, err error) { + n, err = t.r.Read(p) + if n > 0 { + if n, err := t.w.Write(p[:n]); err != nil { + return n, err + } + } + return +} + +// Discard is a [Writer] on which all Write calls succeed +// without doing anything. +var Discard Writer = discard{} + +type discard struct{} + +// discard implements ReaderFrom as an optimization so Copy to +// io.Discard can avoid doing unnecessary work. +var _ ReaderFrom = discard{} + +func (discard) Write(p []byte) (int, error) { + return len(p), nil +} + +func (discard) WriteString(s string) (int, error) { + return len(s), nil +} + +var blackHolePool = sync.Pool{ + New: func() any { + b := make([]byte, 8192) + return &b + }, +} + +func (discard) ReadFrom(r Reader) (n int64, err error) { + bufp := blackHolePool.Get().(*[]byte) + readSize := 0 + for { + readSize, err = r.Read(*bufp) + n += int64(readSize) + if err != nil { + blackHolePool.Put(bufp) + if err == EOF { + return n, nil + } + return + } + } +} + +// NopCloser returns a [ReadCloser] with a no-op Close method wrapping +// the provided [Reader] r. +// If r implements [WriterTo], the returned [ReadCloser] will implement [WriterTo] +// by forwarding calls to r. +func NopCloser(r Reader) ReadCloser { + if _, ok := r.(WriterTo); ok { + return nopCloserWriterTo{r} + } + return nopCloser{r} +} + +type nopCloser struct { + Reader +} + +func (nopCloser) Close() error { return nil } + +type nopCloserWriterTo struct { + Reader +} + +func (nopCloserWriterTo) Close() error { return nil } + +func (c nopCloserWriterTo) WriteTo(w Writer) (n int64, err error) { + return c.Reader.(WriterTo).WriteTo(w) +} + +// ReadAll reads from r until an error or EOF and returns the data it read. +// A successful call returns err == nil, not err == EOF. Because ReadAll is +// defined to read from src until EOF, it does not treat an EOF from Read +// as an error to be reported. +func ReadAll(r Reader) ([]byte, error) { + // Build slices of exponentially growing size, + // then copy into a perfectly-sized slice at the end. + b := make([]byte, 0, 512) + // Starting with next equal to 256 (instead of say 512 or 1024) + // allows less memory usage for small inputs that finish in the + // early growth stages, but we grow the read sizes quickly such that + // it does not materially impact medium or large inputs. + next := 256 + chunks := make([][]byte, 0, 4) + // Invariant: finalSize = sum(len(c) for c in chunks) + var finalSize int + for { + n, err := r.Read(b[len(b):cap(b)]) + b = b[:len(b)+n] + if err != nil { + if err == EOF { + err = nil + } + if len(chunks) == 0 { + return b, err + } + + // Build our final right-sized slice. + finalSize += len(b) + final := append([]byte(nil), make([]byte, finalSize)...)[:0] + for _, chunk := range chunks { + final = append(final, chunk...) + } + final = append(final, b...) + return final, err + } + + if cap(b)-len(b) < cap(b)/16 { + // Move to the next intermediate slice. + chunks = append(chunks, b) + finalSize += len(b) + b = append([]byte(nil), make([]byte, next)...)[:0] + next += next / 2 + } + } +} diff --git a/go/src/io/io_test.go b/go/src/io/io_test.go new file mode 100644 index 0000000000000000000000000000000000000000..38bec8243e7baa5e76a6fb128ba204785b082cab --- /dev/null +++ b/go/src/io/io_test.go @@ -0,0 +1,694 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package io_test + +import ( + "bytes" + "errors" + "fmt" + . "io" + "os" + "strings" + "sync" + "sync/atomic" + "testing" +) + +// A version of bytes.Buffer without ReadFrom and WriteTo +type Buffer struct { + bytes.Buffer + ReaderFrom // conflicts with and hides bytes.Buffer's ReaderFrom. + WriterTo // conflicts with and hides bytes.Buffer's WriterTo. +} + +// Simple tests, primarily to verify the ReadFrom and WriteTo callouts inside Copy, CopyBuffer and CopyN. + +func TestCopy(t *testing.T) { + rb := new(Buffer) + wb := new(Buffer) + rb.WriteString("hello, world.") + Copy(wb, rb) + if wb.String() != "hello, world." { + t.Errorf("Copy did not work properly") + } +} + +func TestCopyNegative(t *testing.T) { + rb := new(Buffer) + wb := new(Buffer) + rb.WriteString("hello") + Copy(wb, &LimitedReader{R: rb, N: -1}) + if wb.String() != "" { + t.Errorf("Copy on LimitedReader with N<0 copied data") + } + + CopyN(wb, rb, -1) + if wb.String() != "" { + t.Errorf("CopyN with N<0 copied data") + } +} + +func TestCopyBuffer(t *testing.T) { + rb := new(Buffer) + wb := new(Buffer) + rb.WriteString("hello, world.") + CopyBuffer(wb, rb, make([]byte, 1)) // Tiny buffer to keep it honest. + if wb.String() != "hello, world." { + t.Errorf("CopyBuffer did not work properly") + } +} + +func TestCopyBufferNil(t *testing.T) { + rb := new(Buffer) + wb := new(Buffer) + rb.WriteString("hello, world.") + CopyBuffer(wb, rb, nil) // Should allocate a buffer. + if wb.String() != "hello, world." { + t.Errorf("CopyBuffer did not work properly") + } +} + +func TestCopyReadFrom(t *testing.T) { + rb := new(Buffer) + wb := new(bytes.Buffer) // implements ReadFrom. + rb.WriteString("hello, world.") + Copy(wb, rb) + if wb.String() != "hello, world." { + t.Errorf("Copy did not work properly") + } +} + +func TestCopyWriteTo(t *testing.T) { + rb := new(bytes.Buffer) // implements WriteTo. + wb := new(Buffer) + rb.WriteString("hello, world.") + Copy(wb, rb) + if wb.String() != "hello, world." { + t.Errorf("Copy did not work properly") + } +} + +// Version of bytes.Buffer that checks whether WriteTo was called or not +type writeToChecker struct { + bytes.Buffer + writeToCalled bool +} + +func (wt *writeToChecker) WriteTo(w Writer) (int64, error) { + wt.writeToCalled = true + return wt.Buffer.WriteTo(w) +} + +// It's preferable to choose WriterTo over ReaderFrom, since a WriterTo can issue one large write, +// while the ReaderFrom must read until EOF, potentially allocating when running out of buffer. +// Make sure that we choose WriterTo when both are implemented. +func TestCopyPriority(t *testing.T) { + rb := new(writeToChecker) + wb := new(bytes.Buffer) + rb.WriteString("hello, world.") + Copy(wb, rb) + if wb.String() != "hello, world." { + t.Errorf("Copy did not work properly") + } else if !rb.writeToCalled { + t.Errorf("WriteTo was not prioritized over ReadFrom") + } +} + +type zeroErrReader struct { + err error +} + +func (r zeroErrReader) Read(p []byte) (int, error) { + return copy(p, []byte{0}), r.err +} + +type errWriter struct { + err error +} + +func (w errWriter) Write([]byte) (int, error) { + return 0, w.err +} + +// In case a Read results in an error with non-zero bytes read, and +// the subsequent Write also results in an error, the error from Write +// is returned, as it is the one that prevented progressing further. +func TestCopyReadErrWriteErr(t *testing.T) { + er, ew := errors.New("readError"), errors.New("writeError") + r, w := zeroErrReader{err: er}, errWriter{err: ew} + n, err := Copy(w, r) + if n != 0 || err != ew { + t.Errorf("Copy(zeroErrReader, errWriter) = %d, %v; want 0, writeError", n, err) + } +} + +func TestCopyN(t *testing.T) { + rb := new(Buffer) + wb := new(Buffer) + rb.WriteString("hello, world.") + CopyN(wb, rb, 5) + if wb.String() != "hello" { + t.Errorf("CopyN did not work properly") + } +} + +func TestCopyNReadFrom(t *testing.T) { + rb := new(Buffer) + wb := new(bytes.Buffer) // implements ReadFrom. + rb.WriteString("hello") + CopyN(wb, rb, 5) + if wb.String() != "hello" { + t.Errorf("CopyN did not work properly") + } +} + +func TestCopyNWriteTo(t *testing.T) { + rb := new(bytes.Buffer) // implements WriteTo. + wb := new(Buffer) + rb.WriteString("hello, world.") + CopyN(wb, rb, 5) + if wb.String() != "hello" { + t.Errorf("CopyN did not work properly") + } +} + +func BenchmarkCopyNSmall(b *testing.B) { + bs := bytes.Repeat([]byte{0}, 512+1) + rd := bytes.NewReader(bs) + buf := new(Buffer) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + CopyN(buf, rd, 512) + rd.Reset(bs) + } +} + +func BenchmarkCopyNLarge(b *testing.B) { + bs := bytes.Repeat([]byte{0}, (32*1024)+1) + rd := bytes.NewReader(bs) + buf := new(Buffer) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + CopyN(buf, rd, 32*1024) + rd.Reset(bs) + } +} + +type noReadFrom struct { + w Writer +} + +func (w *noReadFrom) Write(p []byte) (n int, err error) { + return w.w.Write(p) +} + +type wantedAndErrReader struct{} + +func (wantedAndErrReader) Read(p []byte) (int, error) { + return len(p), errors.New("wantedAndErrReader error") +} + +func TestCopyNEOF(t *testing.T) { + // Test that EOF behavior is the same regardless of whether + // argument to CopyN has ReadFrom. + + b := new(bytes.Buffer) + + n, err := CopyN(&noReadFrom{b}, strings.NewReader("foo"), 3) + if n != 3 || err != nil { + t.Errorf("CopyN(noReadFrom, foo, 3) = %d, %v; want 3, nil", n, err) + } + + n, err = CopyN(&noReadFrom{b}, strings.NewReader("foo"), 4) + if n != 3 || err != EOF { + t.Errorf("CopyN(noReadFrom, foo, 4) = %d, %v; want 3, EOF", n, err) + } + + n, err = CopyN(b, strings.NewReader("foo"), 3) // b has read from + if n != 3 || err != nil { + t.Errorf("CopyN(bytes.Buffer, foo, 3) = %d, %v; want 3, nil", n, err) + } + + n, err = CopyN(b, strings.NewReader("foo"), 4) // b has read from + if n != 3 || err != EOF { + t.Errorf("CopyN(bytes.Buffer, foo, 4) = %d, %v; want 3, EOF", n, err) + } + + n, err = CopyN(b, wantedAndErrReader{}, 5) + if n != 5 || err != nil { + t.Errorf("CopyN(bytes.Buffer, wantedAndErrReader, 5) = %d, %v; want 5, nil", n, err) + } + + n, err = CopyN(&noReadFrom{b}, wantedAndErrReader{}, 5) + if n != 5 || err != nil { + t.Errorf("CopyN(noReadFrom, wantedAndErrReader, 5) = %d, %v; want 5, nil", n, err) + } +} + +func TestReadAtLeast(t *testing.T) { + var rb bytes.Buffer + testReadAtLeast(t, &rb) +} + +// A version of bytes.Buffer that returns n > 0, err on Read +// when the input is exhausted. +type dataAndErrorBuffer struct { + err error + bytes.Buffer +} + +func (r *dataAndErrorBuffer) Read(p []byte) (n int, err error) { + n, err = r.Buffer.Read(p) + if n > 0 && r.Buffer.Len() == 0 && err == nil { + err = r.err + } + return +} + +func TestReadAtLeastWithDataAndEOF(t *testing.T) { + var rb dataAndErrorBuffer + rb.err = EOF + testReadAtLeast(t, &rb) +} + +func TestReadAtLeastWithDataAndError(t *testing.T) { + var rb dataAndErrorBuffer + rb.err = fmt.Errorf("fake error") + testReadAtLeast(t, &rb) +} + +func testReadAtLeast(t *testing.T, rb ReadWriter) { + rb.Write([]byte("0123")) + buf := make([]byte, 2) + n, err := ReadAtLeast(rb, buf, 2) + if err != nil { + t.Error(err) + } + if n != 2 { + t.Errorf("expected to have read 2 bytes, got %v", n) + } + n, err = ReadAtLeast(rb, buf, 4) + if err != ErrShortBuffer { + t.Errorf("expected ErrShortBuffer got %v", err) + } + if n != 0 { + t.Errorf("expected to have read 0 bytes, got %v", n) + } + n, err = ReadAtLeast(rb, buf, 1) + if err != nil { + t.Error(err) + } + if n != 2 { + t.Errorf("expected to have read 2 bytes, got %v", n) + } + n, err = ReadAtLeast(rb, buf, 2) + if err != EOF { + t.Errorf("expected EOF, got %v", err) + } + if n != 0 { + t.Errorf("expected to have read 0 bytes, got %v", n) + } + rb.Write([]byte("4")) + n, err = ReadAtLeast(rb, buf, 2) + want := ErrUnexpectedEOF + if rb, ok := rb.(*dataAndErrorBuffer); ok && rb.err != EOF { + want = rb.err + } + if err != want { + t.Errorf("expected %v, got %v", want, err) + } + if n != 1 { + t.Errorf("expected to have read 1 bytes, got %v", n) + } +} + +func TestTeeReader(t *testing.T) { + src := []byte("hello, world") + dst := make([]byte, len(src)) + rb := bytes.NewBuffer(src) + wb := new(bytes.Buffer) + r := TeeReader(rb, wb) + if n, err := ReadFull(r, dst); err != nil || n != len(src) { + t.Fatalf("ReadFull(r, dst) = %d, %v; want %d, nil", n, err, len(src)) + } + if !bytes.Equal(dst, src) { + t.Errorf("bytes read = %q want %q", dst, src) + } + if !bytes.Equal(wb.Bytes(), src) { + t.Errorf("bytes written = %q want %q", wb.Bytes(), src) + } + if n, err := r.Read(dst); n != 0 || err != EOF { + t.Errorf("r.Read at EOF = %d, %v want 0, EOF", n, err) + } + rb = bytes.NewBuffer(src) + pr, pw := Pipe() + pr.Close() + r = TeeReader(rb, pw) + if n, err := ReadFull(r, dst); n != 0 || err != ErrClosedPipe { + t.Errorf("closed tee: ReadFull(r, dst) = %d, %v; want 0, EPIPE", n, err) + } +} + +func TestSectionReader_ReadAt(t *testing.T) { + dat := "a long sample data, 1234567890" + tests := []struct { + data string + off int + n int + bufLen int + at int + exp string + err error + }{ + {data: "", off: 0, n: 10, bufLen: 2, at: 0, exp: "", err: EOF}, + {data: dat, off: 0, n: len(dat), bufLen: 0, at: 0, exp: "", err: nil}, + {data: dat, off: len(dat), n: 1, bufLen: 1, at: 0, exp: "", err: EOF}, + {data: dat, off: 0, n: len(dat) + 2, bufLen: len(dat), at: 0, exp: dat, err: nil}, + {data: dat, off: 0, n: len(dat), bufLen: len(dat) / 2, at: 0, exp: dat[:len(dat)/2], err: nil}, + {data: dat, off: 0, n: len(dat), bufLen: len(dat), at: 0, exp: dat, err: nil}, + {data: dat, off: 0, n: len(dat), bufLen: len(dat) / 2, at: 2, exp: dat[2 : 2+len(dat)/2], err: nil}, + {data: dat, off: 3, n: len(dat), bufLen: len(dat) / 2, at: 2, exp: dat[5 : 5+len(dat)/2], err: nil}, + {data: dat, off: 3, n: len(dat) / 2, bufLen: len(dat)/2 - 2, at: 2, exp: dat[5 : 5+len(dat)/2-2], err: nil}, + {data: dat, off: 3, n: len(dat) / 2, bufLen: len(dat)/2 + 2, at: 2, exp: dat[5 : 5+len(dat)/2-2], err: EOF}, + {data: dat, off: 0, n: 0, bufLen: 0, at: -1, exp: "", err: EOF}, + {data: dat, off: 0, n: 0, bufLen: 0, at: 1, exp: "", err: EOF}, + } + for i, tt := range tests { + r := strings.NewReader(tt.data) + s := NewSectionReader(r, int64(tt.off), int64(tt.n)) + buf := make([]byte, tt.bufLen) + if n, err := s.ReadAt(buf, int64(tt.at)); n != len(tt.exp) || string(buf[:n]) != tt.exp || err != tt.err { + t.Fatalf("%d: ReadAt(%d) = %q, %v; expected %q, %v", i, tt.at, buf[:n], err, tt.exp, tt.err) + } + if _r, off, n := s.Outer(); _r != r || off != int64(tt.off) || n != int64(tt.n) { + t.Fatalf("%d: Outer() = %v, %d, %d; expected %v, %d, %d", i, _r, off, n, r, tt.off, tt.n) + } + } +} + +func TestSectionReader_Seek(t *testing.T) { + // Verifies that NewSectionReader's Seeker behaves like bytes.NewReader (which is like strings.NewReader) + br := bytes.NewReader([]byte("foo")) + sr := NewSectionReader(br, 0, int64(len("foo"))) + + for _, whence := range []int{SeekStart, SeekCurrent, SeekEnd} { + for offset := int64(-3); offset <= 4; offset++ { + brOff, brErr := br.Seek(offset, whence) + srOff, srErr := sr.Seek(offset, whence) + if (brErr != nil) != (srErr != nil) || brOff != srOff { + t.Errorf("For whence %d, offset %d: bytes.Reader.Seek = (%v, %v) != SectionReader.Seek = (%v, %v)", + whence, offset, brOff, brErr, srErr, srOff) + } + } + } + + // And verify we can just seek past the end and get an EOF + got, err := sr.Seek(100, SeekStart) + if err != nil || got != 100 { + t.Errorf("Seek = %v, %v; want 100, nil", got, err) + } + + n, err := sr.Read(make([]byte, 10)) + if n != 0 || err != EOF { + t.Errorf("Read = %v, %v; want 0, EOF", n, err) + } +} + +func TestSectionReader_Size(t *testing.T) { + tests := []struct { + data string + want int64 + }{ + {"a long sample data, 1234567890", 30}, + {"", 0}, + } + + for _, tt := range tests { + r := strings.NewReader(tt.data) + sr := NewSectionReader(r, 0, int64(len(tt.data))) + if got := sr.Size(); got != tt.want { + t.Errorf("Size = %v; want %v", got, tt.want) + } + } +} + +func TestSectionReader_Max(t *testing.T) { + r := strings.NewReader("abcdef") + const maxint64 = 1<<63 - 1 + sr := NewSectionReader(r, 3, maxint64) + n, err := sr.Read(make([]byte, 3)) + if n != 3 || err != nil { + t.Errorf("Read = %v %v, want 3, nil", n, err) + } + n, err = sr.Read(make([]byte, 3)) + if n != 0 || err != EOF { + t.Errorf("Read = %v, %v, want 0, EOF", n, err) + } + if _r, off, n := sr.Outer(); _r != r || off != 3 || n != maxint64 { + t.Fatalf("Outer = %v, %d, %d; expected %v, %d, %d", _r, off, n, r, 3, int64(maxint64)) + } +} + +// largeWriter returns an invalid count that is larger than the number +// of bytes provided (issue 39978). +type largeWriter struct { + err error +} + +func (w largeWriter) Write(p []byte) (int, error) { + return len(p) + 1, w.err +} + +func TestCopyLargeWriter(t *testing.T) { + want := ErrInvalidWrite + rb := new(Buffer) + wb := largeWriter{} + rb.WriteString("hello, world.") + if _, err := Copy(wb, rb); err != want { + t.Errorf("Copy error: got %v, want %v", err, want) + } + + want = errors.New("largeWriterError") + rb = new(Buffer) + wb = largeWriter{err: want} + rb.WriteString("hello, world.") + if _, err := Copy(wb, rb); err != want { + t.Errorf("Copy error: got %v, want %v", err, want) + } +} + +func TestNopCloserWriterToForwarding(t *testing.T) { + for _, tc := range [...]struct { + Name string + r Reader + }{ + {"not a WriterTo", Reader(nil)}, + {"a WriterTo", struct { + Reader + WriterTo + }{}}, + } { + nc := NopCloser(tc.r) + + _, expected := tc.r.(WriterTo) + _, got := nc.(WriterTo) + if expected != got { + t.Errorf("NopCloser incorrectly forwards WriterTo for %s, got %t want %t", tc.Name, got, expected) + } + } +} + +func TestOffsetWriter_Seek(t *testing.T) { + tmpfilename := "TestOffsetWriter_Seek" + tmpfile, err := os.CreateTemp(t.TempDir(), tmpfilename) + if err != nil { + t.Fatalf("CreateTemp(%s) failed: %v", tmpfilename, err) + } + defer tmpfile.Close() + w := NewOffsetWriter(tmpfile, 0) + + // Should throw error errWhence if whence is not valid + t.Run("errWhence", func(t *testing.T) { + for _, whence := range []int{-3, -2, -1, 3, 4, 5} { + var offset int64 = 0 + gotOff, gotErr := w.Seek(offset, whence) + if gotOff != 0 || gotErr != ErrWhence { + t.Errorf("For whence %d, offset %d, OffsetWriter.Seek got: (%d, %v), want: (%d, %v)", + whence, offset, gotOff, gotErr, 0, ErrWhence) + } + } + }) + + // Should throw error errOffset if offset is negative + t.Run("errOffset", func(t *testing.T) { + for _, whence := range []int{SeekStart, SeekCurrent} { + for offset := int64(-3); offset < 0; offset++ { + gotOff, gotErr := w.Seek(offset, whence) + if gotOff != 0 || gotErr != ErrOffset { + t.Errorf("For whence %d, offset %d, OffsetWriter.Seek got: (%d, %v), want: (%d, %v)", + whence, offset, gotOff, gotErr, 0, ErrOffset) + } + } + } + }) + + // Normal tests + t.Run("normal", func(t *testing.T) { + tests := []struct { + offset int64 + whence int + returnOff int64 + }{ + // keep in order + {whence: SeekStart, offset: 1, returnOff: 1}, + {whence: SeekStart, offset: 2, returnOff: 2}, + {whence: SeekStart, offset: 3, returnOff: 3}, + {whence: SeekCurrent, offset: 1, returnOff: 4}, + {whence: SeekCurrent, offset: 2, returnOff: 6}, + {whence: SeekCurrent, offset: 3, returnOff: 9}, + } + for idx, tt := range tests { + gotOff, gotErr := w.Seek(tt.offset, tt.whence) + if gotOff != tt.returnOff || gotErr != nil { + t.Errorf("%d:: For whence %d, offset %d, OffsetWriter.Seek got: (%d, %v), want: (%d, )", + idx+1, tt.whence, tt.offset, gotOff, gotErr, tt.returnOff) + } + } + }) +} + +func TestOffsetWriter_WriteAt(t *testing.T) { + const content = "0123456789ABCDEF" + contentSize := int64(len(content)) + tmpdir := t.TempDir() + + work := func(off, at int64) { + position := fmt.Sprintf("off_%d_at_%d", off, at) + tmpfile, err := os.CreateTemp(tmpdir, position) + if err != nil { + t.Fatalf("CreateTemp(%s) failed: %v", position, err) + } + defer tmpfile.Close() + + var writeN int64 + var wg sync.WaitGroup + // Concurrent writes, one byte at a time + for step, value := range []byte(content) { + wg.Add(1) + go func(wg *sync.WaitGroup, tmpfile *os.File, value byte, off, at int64, step int) { + defer wg.Done() + + w := NewOffsetWriter(tmpfile, off) + n, e := w.WriteAt([]byte{value}, at+int64(step)) + if e != nil { + t.Errorf("WriteAt failed. off: %d, at: %d, step: %d\n error: %v", off, at, step, e) + } + atomic.AddInt64(&writeN, int64(n)) + }(&wg, tmpfile, value, off, at, step) + } + wg.Wait() + + // Read one more byte to reach EOF + buf := make([]byte, contentSize+1) + readN, err := tmpfile.ReadAt(buf, off+at) + if err != EOF { + t.Fatalf("ReadAt failed: %v", err) + } + readContent := string(buf[:contentSize]) + if writeN != int64(readN) || writeN != contentSize || readContent != content { + t.Fatalf("%s:: WriteAt(%s, %d) error. \ngot n: %v, content: %s \nexpected n: %v, content: %v", + position, content, at, readN, readContent, contentSize, content) + } + } + for off := int64(0); off < 2; off++ { + for at := int64(0); at < 2; at++ { + work(off, at) + } + } +} + +func TestWriteAt_PositionPriorToBase(t *testing.T) { + tmpdir := t.TempDir() + tmpfilename := "TestOffsetWriter_WriteAt" + tmpfile, err := os.CreateTemp(tmpdir, tmpfilename) + if err != nil { + t.Fatalf("CreateTemp(%s) failed: %v", tmpfilename, err) + } + defer tmpfile.Close() + + // start writing position in OffsetWriter + offset := int64(10) + // position we want to write to the tmpfile + at := int64(-1) + w := NewOffsetWriter(tmpfile, offset) + _, e := w.WriteAt([]byte("hello"), at) + if e == nil { + t.Errorf("error expected to be not nil") + } +} + +func TestOffsetWriter_Write(t *testing.T) { + const content = "0123456789ABCDEF" + contentSize := len(content) + tmpdir := t.TempDir() + + makeOffsetWriter := func(name string) (*OffsetWriter, *os.File) { + tmpfilename := "TestOffsetWriter_Write_" + name + tmpfile, err := os.CreateTemp(tmpdir, tmpfilename) + if err != nil { + t.Fatalf("CreateTemp(%s) failed: %v", tmpfilename, err) + } + return NewOffsetWriter(tmpfile, 0), tmpfile + } + checkContent := func(name string, f *os.File) { + // Read one more byte to reach EOF + buf := make([]byte, contentSize+1) + readN, err := f.ReadAt(buf, 0) + if err != EOF { + t.Fatalf("ReadAt failed, err: %v", err) + } + readContent := string(buf[:contentSize]) + if readN != contentSize || readContent != content { + t.Fatalf("%s error. \ngot n: %v, content: %s \nexpected n: %v, content: %v", + name, readN, readContent, contentSize, content) + } + } + + var name string + name = "Write" + t.Run(name, func(t *testing.T) { + // Write directly (off: 0, at: 0) + // Write content to file + w, f := makeOffsetWriter(name) + defer f.Close() + for _, value := range []byte(content) { + n, err := w.Write([]byte{value}) + if err != nil { + t.Fatalf("Write failed, n: %d, err: %v", n, err) + } + } + checkContent(name, f) + + // Copy -> Write + // Copy file f to file f2 + name = "Copy" + w2, f2 := makeOffsetWriter(name) + defer f2.Close() + Copy(w2, f) + checkContent(name, f2) + }) + + // Copy -> WriteTo -> Write + // Note: strings.Reader implements the io.WriterTo interface. + name = "Write_Of_Copy_WriteTo" + t.Run(name, func(t *testing.T) { + w, f := makeOffsetWriter(name) + defer f.Close() + Copy(w, strings.NewReader(content)) + checkContent(name, f) + }) +} diff --git a/go/src/io/multi.go b/go/src/io/multi.go new file mode 100644 index 0000000000000000000000000000000000000000..07a9afffda38272d264a47af01afb37b827236c7 --- /dev/null +++ b/go/src/io/multi.go @@ -0,0 +1,137 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package io + +type eofReader struct{} + +func (eofReader) Read([]byte) (int, error) { + return 0, EOF +} + +type multiReader struct { + readers []Reader +} + +func (mr *multiReader) Read(p []byte) (n int, err error) { + for len(mr.readers) > 0 { + // Optimization to flatten nested multiReaders (Issue 13558). + if len(mr.readers) == 1 { + if r, ok := mr.readers[0].(*multiReader); ok { + mr.readers = r.readers + continue + } + } + n, err = mr.readers[0].Read(p) + if err == EOF { + // Use eofReader instead of nil to avoid nil panic + // after performing flatten (Issue 18232). + mr.readers[0] = eofReader{} // permit earlier GC + mr.readers = mr.readers[1:] + } + if n > 0 || err != EOF { + if err == EOF && len(mr.readers) > 0 { + // Don't return EOF yet. More readers remain. + err = nil + } + return + } + } + return 0, EOF +} + +func (mr *multiReader) WriteTo(w Writer) (sum int64, err error) { + return mr.writeToWithBuffer(w, make([]byte, 1024*32)) +} + +func (mr *multiReader) writeToWithBuffer(w Writer, buf []byte) (sum int64, err error) { + for i, r := range mr.readers { + var n int64 + if subMr, ok := r.(*multiReader); ok { // reuse buffer with nested multiReaders + n, err = subMr.writeToWithBuffer(w, buf) + } else { + n, err = copyBuffer(w, r, buf) + } + sum += n + if err != nil { + mr.readers = mr.readers[i:] // permit resume / retry after error + return sum, err + } + mr.readers[i] = nil // permit early GC + } + mr.readers = nil + return sum, nil +} + +var _ WriterTo = (*multiReader)(nil) + +// MultiReader returns a Reader that's the logical concatenation of +// the provided input readers. They're read sequentially. Once all +// inputs have returned EOF, Read will return EOF. If any of the readers +// return a non-nil, non-EOF error, Read will return that error. +func MultiReader(readers ...Reader) Reader { + r := make([]Reader, len(readers)) + copy(r, readers) + return &multiReader{r} +} + +type multiWriter struct { + writers []Writer +} + +func (t *multiWriter) Write(p []byte) (n int, err error) { + for _, w := range t.writers { + n, err = w.Write(p) + if err != nil { + return + } + if n != len(p) { + err = ErrShortWrite + return + } + } + return len(p), nil +} + +var _ StringWriter = (*multiWriter)(nil) + +func (t *multiWriter) WriteString(s string) (n int, err error) { + var p []byte // lazily initialized if/when needed + for _, w := range t.writers { + if sw, ok := w.(StringWriter); ok { + n, err = sw.WriteString(s) + } else { + if p == nil { + p = []byte(s) + } + n, err = w.Write(p) + } + if err != nil { + return + } + if n != len(s) { + err = ErrShortWrite + return + } + } + return len(s), nil +} + +// MultiWriter creates a writer that duplicates its writes to all the +// provided writers, similar to the Unix tee(1) command. +// +// Each write is written to each listed writer, one at a time. +// If a listed writer returns an error, that overall write operation +// stops and returns the error; it does not continue down the list. +func MultiWriter(writers ...Writer) Writer { + allWriters := make([]Writer, 0, len(writers)) + for _, w := range writers { + if mw, ok := w.(*multiWriter); ok { + allWriters = append(allWriters, mw.writers...) + } else { + allWriters = append(allWriters, w) + } + } + return &multiWriter{allWriters} +} diff --git a/go/src/io/multi_test.go b/go/src/io/multi_test.go new file mode 100644 index 0000000000000000000000000000000000000000..934a6ec785fda4eddcc6d0308f523317207819f1 --- /dev/null +++ b/go/src/io/multi_test.go @@ -0,0 +1,377 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package io_test + +import ( + "bytes" + "crypto/sha1" + "errors" + "fmt" + . "io" + "runtime" + "strings" + "testing" + "time" +) + +func TestMultiReader(t *testing.T) { + var mr Reader + var buf []byte + nread := 0 + withFooBar := func(tests func()) { + r1 := strings.NewReader("foo ") + r2 := strings.NewReader("") + r3 := strings.NewReader("bar") + mr = MultiReader(r1, r2, r3) + buf = make([]byte, 20) + tests() + } + expectRead := func(size int, expected string, eerr error) { + nread++ + n, gerr := mr.Read(buf[0:size]) + if n != len(expected) { + t.Errorf("#%d, expected %d bytes; got %d", + nread, len(expected), n) + } + got := string(buf[0:n]) + if got != expected { + t.Errorf("#%d, expected %q; got %q", + nread, expected, got) + } + if gerr != eerr { + t.Errorf("#%d, expected error %v; got %v", + nread, eerr, gerr) + } + buf = buf[n:] + } + withFooBar(func() { + expectRead(2, "fo", nil) + expectRead(5, "o ", nil) + expectRead(5, "bar", nil) + expectRead(5, "", EOF) + }) + withFooBar(func() { + expectRead(4, "foo ", nil) + expectRead(1, "b", nil) + expectRead(3, "ar", nil) + expectRead(1, "", EOF) + }) + withFooBar(func() { + expectRead(5, "foo ", nil) + }) +} + +func TestMultiReaderAsWriterTo(t *testing.T) { + mr := MultiReader( + strings.NewReader("foo "), + MultiReader( // Tickle the buffer reusing codepath + strings.NewReader(""), + strings.NewReader("bar"), + ), + ) + mrAsWriterTo, ok := mr.(WriterTo) + if !ok { + t.Fatalf("expected cast to WriterTo to succeed") + } + sink := &strings.Builder{} + n, err := mrAsWriterTo.WriteTo(sink) + if err != nil { + t.Fatalf("expected no error; got %v", err) + } + if n != 7 { + t.Errorf("expected read 7 bytes; got %d", n) + } + if result := sink.String(); result != "foo bar" { + t.Errorf(`expected "foo bar"; got %q`, result) + } +} + +func TestMultiWriter(t *testing.T) { + sink := new(bytes.Buffer) + // Hide bytes.Buffer's WriteString method: + testMultiWriter(t, struct { + Writer + fmt.Stringer + }{sink, sink}) +} + +func TestMultiWriter_String(t *testing.T) { + testMultiWriter(t, new(bytes.Buffer)) +} + +// Test that a multiWriter.WriteString calls results in at most 1 allocation, +// even if multiple targets don't support WriteString. +func TestMultiWriter_WriteStringSingleAlloc(t *testing.T) { + var sink1, sink2 bytes.Buffer + type simpleWriter struct { // hide bytes.Buffer's WriteString + Writer + } + mw := MultiWriter(simpleWriter{&sink1}, simpleWriter{&sink2}) + allocs := int(testing.AllocsPerRun(1000, func() { + WriteString(mw, "foo") + })) + if allocs != 1 { + t.Errorf("num allocations = %d; want 1", allocs) + } +} + +type writeStringChecker struct{ called bool } + +func (c *writeStringChecker) WriteString(s string) (n int, err error) { + c.called = true + return len(s), nil +} + +func (c *writeStringChecker) Write(p []byte) (n int, err error) { + return len(p), nil +} + +func TestMultiWriter_StringCheckCall(t *testing.T) { + var c writeStringChecker + mw := MultiWriter(&c) + WriteString(mw, "foo") + if !c.called { + t.Error("did not see WriteString call to writeStringChecker") + } +} + +func testMultiWriter(t *testing.T, sink interface { + Writer + fmt.Stringer +}) { + sha1 := sha1.New() + mw := MultiWriter(sha1, sink) + + sourceString := "My input text." + source := strings.NewReader(sourceString) + written, err := Copy(mw, source) + + if written != int64(len(sourceString)) { + t.Errorf("short write of %d, not %d", written, len(sourceString)) + } + + if err != nil { + t.Errorf("unexpected error: %v", err) + } + + sha1hex := fmt.Sprintf("%x", sha1.Sum(nil)) + if sha1hex != "01cb303fa8c30a64123067c5aa6284ba7ec2d31b" { + t.Error("incorrect sha1 value") + } + + if sink.String() != sourceString { + t.Errorf("expected %q; got %q", sourceString, sink.String()) + } +} + +// writerFunc is a Writer implemented by the underlying func. +type writerFunc func(p []byte) (int, error) + +func (f writerFunc) Write(p []byte) (int, error) { + return f(p) +} + +// Test that MultiWriter properly flattens chained multiWriters. +func TestMultiWriterSingleChainFlatten(t *testing.T) { + pc := make([]uintptr, 1000) // 1000 should fit the full stack + n := runtime.Callers(0, pc) + var myDepth = callDepth(pc[:n]) + var writeDepth int // will contain the depth from which writerFunc.Writer was called + var w Writer = MultiWriter(writerFunc(func(p []byte) (int, error) { + n := runtime.Callers(1, pc) + writeDepth += callDepth(pc[:n]) + return 0, nil + })) + + mw := w + // chain a bunch of multiWriters + for i := 0; i < 100; i++ { + mw = MultiWriter(w) + } + + mw = MultiWriter(w, mw, w, mw) + mw.Write(nil) // don't care about errors, just want to check the call-depth for Write + + if writeDepth != 4*(myDepth+2) { // 2 should be multiWriter.Write and writerFunc.Write + t.Errorf("multiWriter did not flatten chained multiWriters: expected writeDepth %d, got %d", + 4*(myDepth+2), writeDepth) + } +} + +func TestMultiWriterError(t *testing.T) { + f1 := writerFunc(func(p []byte) (int, error) { + return len(p) / 2, ErrShortWrite + }) + f2 := writerFunc(func(p []byte) (int, error) { + t.Errorf("MultiWriter called f2.Write") + return len(p), nil + }) + w := MultiWriter(f1, f2) + n, err := w.Write(make([]byte, 100)) + if n != 50 || err != ErrShortWrite { + t.Errorf("Write = %d, %v, want 50, ErrShortWrite", n, err) + } +} + +// Test that MultiReader copies the input slice and is insulated from future modification. +func TestMultiReaderCopy(t *testing.T) { + slice := []Reader{strings.NewReader("hello world")} + r := MultiReader(slice...) + slice[0] = nil + data, err := ReadAll(r) + if err != nil || string(data) != "hello world" { + t.Errorf("ReadAll() = %q, %v, want %q, nil", data, err, "hello world") + } +} + +// Test that MultiWriter copies the input slice and is insulated from future modification. +func TestMultiWriterCopy(t *testing.T) { + var buf strings.Builder + slice := []Writer{&buf} + w := MultiWriter(slice...) + slice[0] = nil + n, err := w.Write([]byte("hello world")) + if err != nil || n != 11 { + t.Errorf("Write(`hello world`) = %d, %v, want 11, nil", n, err) + } + if buf.String() != "hello world" { + t.Errorf("buf.String() = %q, want %q", buf.String(), "hello world") + } +} + +// readerFunc is a Reader implemented by the underlying func. +type readerFunc func(p []byte) (int, error) + +func (f readerFunc) Read(p []byte) (int, error) { + return f(p) +} + +// callDepth returns the logical call depth for the given PCs. +func callDepth(callers []uintptr) (depth int) { + frames := runtime.CallersFrames(callers) + more := true + for more { + _, more = frames.Next() + depth++ + } + return +} + +// Test that MultiReader properly flattens chained multiReaders when Read is called +func TestMultiReaderFlatten(t *testing.T) { + pc := make([]uintptr, 1000) // 1000 should fit the full stack + n := runtime.Callers(0, pc) + var myDepth = callDepth(pc[:n]) + var readDepth int // will contain the depth from which fakeReader.Read was called + var r Reader = MultiReader(readerFunc(func(p []byte) (int, error) { + n := runtime.Callers(1, pc) + readDepth = callDepth(pc[:n]) + return 0, errors.New("irrelevant") + })) + + // chain a bunch of multiReaders + for i := 0; i < 100; i++ { + r = MultiReader(r) + } + + r.Read(nil) // don't care about errors, just want to check the call-depth for Read + + if readDepth != myDepth+2 { // 2 should be multiReader.Read and fakeReader.Read + t.Errorf("multiReader did not flatten chained multiReaders: expected readDepth %d, got %d", + myDepth+2, readDepth) + } +} + +// byteAndEOFReader is a Reader which reads one byte (the underlying +// byte) and EOF at once in its Read call. +type byteAndEOFReader byte + +func (b byteAndEOFReader) Read(p []byte) (n int, err error) { + if len(p) == 0 { + // Read(0 bytes) is useless. We expect no such useless + // calls in this test. + panic("unexpected call") + } + p[0] = byte(b) + return 1, EOF +} + +// This used to yield bytes forever; issue 16795. +func TestMultiReaderSingleByteWithEOF(t *testing.T) { + got, err := ReadAll(LimitReader(MultiReader(byteAndEOFReader('a'), byteAndEOFReader('b')), 10)) + if err != nil { + t.Fatal(err) + } + const want = "ab" + if string(got) != want { + t.Errorf("got %q; want %q", got, want) + } +} + +// Test that a reader returning (n, EOF) at the end of a MultiReader +// chain continues to return EOF on its final read, rather than +// yielding a (0, EOF). +func TestMultiReaderFinalEOF(t *testing.T) { + r := MultiReader(bytes.NewReader(nil), byteAndEOFReader('a')) + buf := make([]byte, 2) + n, err := r.Read(buf) + if n != 1 || err != EOF { + t.Errorf("got %v, %v; want 1, EOF", n, err) + } +} + +func TestMultiReaderFreesExhaustedReaders(t *testing.T) { + var mr Reader + closed := make(chan struct{}) + // The closure ensures that we don't have a live reference to buf1 + // on our stack after MultiReader is inlined (Issue 18819). This + // is a work around for a limitation in liveness analysis. + func() { + buf1 := bytes.NewReader([]byte("foo")) + buf2 := bytes.NewReader([]byte("bar")) + mr = MultiReader(buf1, buf2) + runtime.AddCleanup(buf1, func(ch chan struct{}) { close(ch) }, closed) + }() + + buf := make([]byte, 4) + if n, err := ReadFull(mr, buf); err != nil || string(buf) != "foob" { + t.Fatalf(`ReadFull = %d (%q), %v; want 3, "foo", nil`, n, buf[:n], err) + } + + runtime.GC() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatal("timeout waiting for collection of buf1") + } + + if n, err := ReadFull(mr, buf[:2]); err != nil || string(buf[:2]) != "ar" { + t.Fatalf(`ReadFull = %d (%q), %v; want 2, "ar", nil`, n, buf[:n], err) + } +} + +func TestInterleavedMultiReader(t *testing.T) { + r1 := strings.NewReader("123") + r2 := strings.NewReader("45678") + + mr1 := MultiReader(r1, r2) + mr2 := MultiReader(mr1) + + buf := make([]byte, 4) + + // Have mr2 use mr1's []Readers. + // Consume r1 (and clear it for GC to handle) and consume part of r2. + n, err := ReadFull(mr2, buf) + if got := string(buf[:n]); got != "1234" || err != nil { + t.Errorf(`ReadFull(mr2) = (%q, %v), want ("1234", nil)`, got, err) + } + + // Consume the rest of r2 via mr1. + // This should not panic even though mr2 cleared r1. + n, err = ReadFull(mr1, buf) + if got := string(buf[:n]); got != "5678" || err != nil { + t.Errorf(`ReadFull(mr1) = (%q, %v), want ("5678", nil)`, got, err) + } +} diff --git a/go/src/io/pipe.go b/go/src/io/pipe.go new file mode 100644 index 0000000000000000000000000000000000000000..f34cf25e9de5bdf1a4843b39ceccb45cc4d74950 --- /dev/null +++ b/go/src/io/pipe.go @@ -0,0 +1,202 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Pipe adapter to connect code expecting an io.Reader +// with code expecting an io.Writer. + +package io + +import ( + "errors" + "sync" +) + +// onceError is an object that will only store an error once. +type onceError struct { + sync.Mutex // guards following + err error +} + +func (a *onceError) Store(err error) { + a.Lock() + defer a.Unlock() + if a.err != nil { + return + } + a.err = err +} +func (a *onceError) Load() error { + a.Lock() + defer a.Unlock() + return a.err +} + +// ErrClosedPipe is the error used for read or write operations on a closed pipe. +var ErrClosedPipe = errors.New("io: read/write on closed pipe") + +// A pipe is the shared pipe structure underlying PipeReader and PipeWriter. +type pipe struct { + wrMu sync.Mutex // Serializes Write operations + wrCh chan []byte + rdCh chan int + + once sync.Once // Protects closing done + done chan struct{} + rerr onceError + werr onceError +} + +func (p *pipe) read(b []byte) (n int, err error) { + select { + case <-p.done: + return 0, p.readCloseError() + default: + } + + select { + case bw := <-p.wrCh: + nr := copy(b, bw) + p.rdCh <- nr + return nr, nil + case <-p.done: + return 0, p.readCloseError() + } +} + +func (p *pipe) closeRead(err error) error { + if err == nil { + err = ErrClosedPipe + } + p.rerr.Store(err) + p.once.Do(func() { close(p.done) }) + return nil +} + +func (p *pipe) write(b []byte) (n int, err error) { + select { + case <-p.done: + return 0, p.writeCloseError() + default: + p.wrMu.Lock() + defer p.wrMu.Unlock() + } + + for once := true; once || len(b) > 0; once = false { + select { + case p.wrCh <- b: + nw := <-p.rdCh + b = b[nw:] + n += nw + case <-p.done: + return n, p.writeCloseError() + } + } + return n, nil +} + +func (p *pipe) closeWrite(err error) error { + if err == nil { + err = EOF + } + p.werr.Store(err) + p.once.Do(func() { close(p.done) }) + return nil +} + +// readCloseError is considered internal to the pipe type. +func (p *pipe) readCloseError() error { + rerr := p.rerr.Load() + if werr := p.werr.Load(); rerr == nil && werr != nil { + return werr + } + return ErrClosedPipe +} + +// writeCloseError is considered internal to the pipe type. +func (p *pipe) writeCloseError() error { + werr := p.werr.Load() + if rerr := p.rerr.Load(); werr == nil && rerr != nil { + return rerr + } + return ErrClosedPipe +} + +// A PipeReader is the read half of a pipe. +type PipeReader struct{ pipe } + +// Read implements the standard Read interface: +// it reads data from the pipe, blocking until a writer +// arrives or the write end is closed. +// If the write end is closed with an error, that error is +// returned as err; otherwise err is EOF. +func (r *PipeReader) Read(data []byte) (n int, err error) { + return r.pipe.read(data) +} + +// Close closes the reader; subsequent writes to the +// write half of the pipe will return the error [ErrClosedPipe]. +func (r *PipeReader) Close() error { + return r.CloseWithError(nil) +} + +// CloseWithError closes the reader; subsequent writes +// to the write half of the pipe will return the error err. +// +// CloseWithError never overwrites the previous error if it exists +// and always returns nil. +func (r *PipeReader) CloseWithError(err error) error { + return r.pipe.closeRead(err) +} + +// A PipeWriter is the write half of a pipe. +type PipeWriter struct{ r PipeReader } + +// Write implements the standard Write interface: +// it writes data to the pipe, blocking until one or more readers +// have consumed all the data or the read end is closed. +// If the read end is closed with an error, that err is +// returned as err; otherwise err is [ErrClosedPipe]. +func (w *PipeWriter) Write(data []byte) (n int, err error) { + return w.r.pipe.write(data) +} + +// Close closes the writer; subsequent reads from the +// read half of the pipe will return no bytes and EOF. +func (w *PipeWriter) Close() error { + return w.CloseWithError(nil) +} + +// CloseWithError closes the writer; subsequent reads from the +// read half of the pipe will return no bytes and the error err, +// or EOF if err is nil. +// +// CloseWithError never overwrites the previous error if it exists +// and always returns nil. +func (w *PipeWriter) CloseWithError(err error) error { + return w.r.pipe.closeWrite(err) +} + +// Pipe creates a synchronous in-memory pipe. +// It can be used to connect code expecting an [io.Reader] +// with code expecting an [io.Writer]. +// +// Reads and Writes on the pipe are matched one to one +// except when multiple Reads are needed to consume a single Write. +// That is, each Write to the [PipeWriter] blocks until it has satisfied +// one or more Reads from the [PipeReader] that fully consume +// the written data. +// The data is copied directly from the Write to the corresponding +// Read (or Reads); there is no internal buffering. +// +// It is safe to call Read and Write in parallel with each other or with Close. +// Parallel calls to Read and parallel calls to Write are also safe: +// the individual calls will be gated sequentially. +func Pipe() (*PipeReader, *PipeWriter) { + pw := &PipeWriter{r: PipeReader{pipe: pipe{ + wrCh: make(chan []byte), + rdCh: make(chan int), + done: make(chan struct{}), + }}} + return &pw.r, pw +} diff --git a/go/src/io/pipe_test.go b/go/src/io/pipe_test.go new file mode 100644 index 0000000000000000000000000000000000000000..fcf94d52d21bcd4234c3492e6f39910fa2abf582 --- /dev/null +++ b/go/src/io/pipe_test.go @@ -0,0 +1,441 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package io_test + +import ( + "bytes" + "fmt" + . "io" + "slices" + "strings" + "testing" + "time" +) + +func checkWrite(t *testing.T, w Writer, data []byte, c chan int) { + n, err := w.Write(data) + if err != nil { + t.Errorf("write: %v", err) + } + if n != len(data) { + t.Errorf("short write: %d != %d", n, len(data)) + } + c <- 0 +} + +// Test a single read/write pair. +func TestPipe1(t *testing.T) { + c := make(chan int) + r, w := Pipe() + var buf = make([]byte, 64) + go checkWrite(t, w, []byte("hello, world"), c) + n, err := r.Read(buf) + if err != nil { + t.Errorf("read: %v", err) + } else if n != 12 || string(buf[0:12]) != "hello, world" { + t.Errorf("bad read: got %q", buf[0:n]) + } + <-c + r.Close() + w.Close() +} + +func reader(t *testing.T, r Reader, c chan int) { + var buf = make([]byte, 64) + for { + n, err := r.Read(buf) + if err == EOF { + c <- 0 + break + } + if err != nil { + t.Errorf("read: %v", err) + } + c <- n + } +} + +// Test a sequence of read/write pairs. +func TestPipe2(t *testing.T) { + c := make(chan int) + r, w := Pipe() + go reader(t, r, c) + var buf = make([]byte, 64) + for i := 0; i < 5; i++ { + p := buf[0 : 5+i*10] + n, err := w.Write(p) + if n != len(p) { + t.Errorf("wrote %d, got %d", len(p), n) + } + if err != nil { + t.Errorf("write: %v", err) + } + nn := <-c + if nn != n { + t.Errorf("wrote %d, read got %d", n, nn) + } + } + w.Close() + nn := <-c + if nn != 0 { + t.Errorf("final read got %d", nn) + } +} + +type pipeReturn struct { + n int + err error +} + +// Test a large write that requires multiple reads to satisfy. +func writer(w WriteCloser, buf []byte, c chan pipeReturn) { + n, err := w.Write(buf) + w.Close() + c <- pipeReturn{n, err} +} + +func TestPipe3(t *testing.T) { + c := make(chan pipeReturn) + r, w := Pipe() + var wdat = make([]byte, 128) + for i := 0; i < len(wdat); i++ { + wdat[i] = byte(i) + } + go writer(w, wdat, c) + var rdat = make([]byte, 1024) + tot := 0 + for n := 1; n <= 256; n *= 2 { + nn, err := r.Read(rdat[tot : tot+n]) + if err != nil && err != EOF { + t.Fatalf("read: %v", err) + } + + // only final two reads should be short - 1 byte, then 0 + expect := n + if n == 128 { + expect = 1 + } else if n == 256 { + expect = 0 + if err != EOF { + t.Fatalf("read at end: %v", err) + } + } + if nn != expect { + t.Fatalf("read %d, expected %d, got %d", n, expect, nn) + } + tot += nn + } + pr := <-c + if pr.n != 128 || pr.err != nil { + t.Fatalf("write 128: %d, %v", pr.n, pr.err) + } + if tot != 128 { + t.Fatalf("total read %d != 128", tot) + } + for i := 0; i < 128; i++ { + if rdat[i] != byte(i) { + t.Fatalf("rdat[%d] = %d", i, rdat[i]) + } + } +} + +// Test read after/before writer close. + +type closer interface { + CloseWithError(error) error + Close() error +} + +type pipeTest struct { + async bool + err error + closeWithError bool +} + +func (p pipeTest) String() string { + return fmt.Sprintf("async=%v err=%v closeWithError=%v", p.async, p.err, p.closeWithError) +} + +var pipeTests = []pipeTest{ + {true, nil, false}, + {true, nil, true}, + {true, ErrShortWrite, true}, + {false, nil, false}, + {false, nil, true}, + {false, ErrShortWrite, true}, +} + +func delayClose(t *testing.T, cl closer, ch chan int, tt pipeTest) { + time.Sleep(1 * time.Millisecond) + var err error + if tt.closeWithError { + err = cl.CloseWithError(tt.err) + } else { + err = cl.Close() + } + if err != nil { + t.Errorf("delayClose: %v", err) + } + ch <- 0 +} + +func TestPipeReadClose(t *testing.T) { + for _, tt := range pipeTests { + c := make(chan int, 1) + r, w := Pipe() + if tt.async { + go delayClose(t, w, c, tt) + } else { + delayClose(t, w, c, tt) + } + var buf = make([]byte, 64) + n, err := r.Read(buf) + <-c + want := tt.err + if want == nil { + want = EOF + } + if err != want { + t.Errorf("read from closed pipe: %v want %v", err, want) + } + if n != 0 { + t.Errorf("read on closed pipe returned %d", n) + } + if err = r.Close(); err != nil { + t.Errorf("r.Close: %v", err) + } + } +} + +// Test close on Read side during Read. +func TestPipeReadClose2(t *testing.T) { + c := make(chan int, 1) + r, _ := Pipe() + go delayClose(t, r, c, pipeTest{}) + n, err := r.Read(make([]byte, 64)) + <-c + if n != 0 || err != ErrClosedPipe { + t.Errorf("read from closed pipe: %v, %v want %v, %v", n, err, 0, ErrClosedPipe) + } +} + +// Test write after/before reader close. + +func TestPipeWriteClose(t *testing.T) { + for _, tt := range pipeTests { + c := make(chan int, 1) + r, w := Pipe() + if tt.async { + go delayClose(t, r, c, tt) + } else { + delayClose(t, r, c, tt) + } + n, err := WriteString(w, "hello, world") + <-c + expect := tt.err + if expect == nil { + expect = ErrClosedPipe + } + if err != expect { + t.Errorf("write on closed pipe: %v want %v", err, expect) + } + if n != 0 { + t.Errorf("write on closed pipe returned %d", n) + } + if err = w.Close(); err != nil { + t.Errorf("w.Close: %v", err) + } + } +} + +// Test close on Write side during Write. +func TestPipeWriteClose2(t *testing.T) { + c := make(chan int, 1) + _, w := Pipe() + go delayClose(t, w, c, pipeTest{}) + n, err := w.Write(make([]byte, 64)) + <-c + if n != 0 || err != ErrClosedPipe { + t.Errorf("write to closed pipe: %v, %v want %v, %v", n, err, 0, ErrClosedPipe) + } +} + +func TestWriteEmpty(t *testing.T) { + r, w := Pipe() + go func() { + w.Write([]byte{}) + w.Close() + }() + var b [2]byte + ReadFull(r, b[0:2]) + r.Close() +} + +func TestWriteNil(t *testing.T) { + r, w := Pipe() + go func() { + w.Write(nil) + w.Close() + }() + var b [2]byte + ReadFull(r, b[0:2]) + r.Close() +} + +func TestWriteAfterWriterClose(t *testing.T) { + r, w := Pipe() + defer r.Close() + done := make(chan bool) + var writeErr error + go func() { + _, err := w.Write([]byte("hello")) + if err != nil { + t.Errorf("got error: %q; expected none", err) + } + w.Close() + _, writeErr = w.Write([]byte("world")) + done <- true + }() + + buf := make([]byte, 100) + var result string + n, err := ReadFull(r, buf) + if err != nil && err != ErrUnexpectedEOF { + t.Fatalf("got: %q; want: %q", err, ErrUnexpectedEOF) + } + result = string(buf[0:n]) + <-done + + if result != "hello" { + t.Errorf("got: %q; want: %q", result, "hello") + } + if writeErr != ErrClosedPipe { + t.Errorf("got: %q; want: %q", writeErr, ErrClosedPipe) + } +} + +func TestPipeCloseError(t *testing.T) { + type testError1 struct{ error } + type testError2 struct{ error } + + r, w := Pipe() + r.CloseWithError(testError1{}) + if _, err := w.Write(nil); err != (testError1{}) { + t.Errorf("Write error: got %T, want testError1", err) + } + r.CloseWithError(testError2{}) + if _, err := w.Write(nil); err != (testError1{}) { + t.Errorf("Write error: got %T, want testError1", err) + } + + r, w = Pipe() + w.CloseWithError(testError1{}) + if _, err := r.Read(nil); err != (testError1{}) { + t.Errorf("Read error: got %T, want testError1", err) + } + w.CloseWithError(testError2{}) + if _, err := r.Read(nil); err != (testError1{}) { + t.Errorf("Read error: got %T, want testError1", err) + } +} + +func TestPipeConcurrent(t *testing.T) { + const ( + input = "0123456789abcdef" + count = 8 + readSize = 2 + ) + + t.Run("Write", func(t *testing.T) { + r, w := Pipe() + + for i := 0; i < count; i++ { + go func() { + time.Sleep(time.Millisecond) // Increase probability of race + if n, err := w.Write([]byte(input)); n != len(input) || err != nil { + t.Errorf("Write() = (%d, %v); want (%d, nil)", n, err, len(input)) + } + }() + } + + buf := make([]byte, count*len(input)) + for i := 0; i < len(buf); i += readSize { + if n, err := r.Read(buf[i : i+readSize]); n != readSize || err != nil { + t.Errorf("Read() = (%d, %v); want (%d, nil)", n, err, readSize) + } + } + + // Since each Write is fully gated, if multiple Read calls were needed, + // the contents of Write should still appear together in the output. + got := string(buf) + want := strings.Repeat(input, count) + if got != want { + t.Errorf("got: %q; want: %q", got, want) + } + }) + + t.Run("Read", func(t *testing.T) { + r, w := Pipe() + + c := make(chan []byte, count*len(input)/readSize) + for i := 0; i < cap(c); i++ { + go func() { + time.Sleep(time.Millisecond) // Increase probability of race + buf := make([]byte, readSize) + if n, err := r.Read(buf); n != readSize || err != nil { + t.Errorf("Read() = (%d, %v); want (%d, nil)", n, err, readSize) + } + c <- buf + }() + } + + for i := 0; i < count; i++ { + if n, err := w.Write([]byte(input)); n != len(input) || err != nil { + t.Errorf("Write() = (%d, %v); want (%d, nil)", n, err, len(input)) + } + } + + // Since each read is independent, the only guarantee about the output + // is that it is a permutation of the input in readSized groups. + got := make([]byte, 0, count*len(input)) + for i := 0; i < cap(c); i++ { + got = append(got, (<-c)...) + } + got = sortBytesInGroups(got, readSize) + want := bytes.Repeat([]byte(input), count) + want = sortBytesInGroups(want, readSize) + if string(got) != string(want) { + t.Errorf("got: %q; want: %q", got, want) + } + }) +} + +func sortBytesInGroups(b []byte, n int) []byte { + var groups [][]byte + for len(b) > 0 { + groups = append(groups, b[:n]) + b = b[n:] + } + slices.SortFunc(groups, bytes.Compare) + return bytes.Join(groups, nil) +} + +var ( + rSink *PipeReader + wSink *PipeWriter +) + +func TestPipeAllocations(t *testing.T) { + numAllocs := testing.AllocsPerRun(10, func() { + rSink, wSink = Pipe() + }) + + // go.dev/cl/473535 claimed Pipe() should only do 2 allocations, + // plus the 2 escaping to heap for simulating real world usages. + expectedAllocs := 4 + if int(numAllocs) > expectedAllocs { + t.Fatalf("too many allocations for io.Pipe() call: %f", numAllocs) + } +} diff --git a/go/src/iter/iter.go b/go/src/iter/iter.go new file mode 100644 index 0000000000000000000000000000000000000000..f119eae995199546c2674135aca141e086876ff8 --- /dev/null +++ b/go/src/iter/iter.go @@ -0,0 +1,473 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package iter provides basic definitions and operations related to +iterators over sequences. + +# Iterators + +An iterator is a function that passes successive elements of a +sequence to a callback function, conventionally named yield. +The function stops either when the sequence is finished or +when yield returns false, indicating to stop the iteration early. +This package defines [Seq] and [Seq2] +(pronounced like seek—the first syllable of sequence) +as shorthands for iterators that pass 1 or 2 values per sequence element +to yield: + + type ( + Seq[V any] func(yield func(V) bool) + Seq2[K, V any] func(yield func(K, V) bool) + ) + +Seq2 represents a sequence of paired values, conventionally key-value +or index-value pairs. + +Yield returns true if the iterator should continue with the next +element in the sequence, false if it should stop. + +Yield panics if called after it returns false. + +For instance, [maps.Keys] returns an iterator that produces the sequence +of keys of the map m, implemented as follows: + + func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] { + return func(yield func(K) bool) { + for k := range m { + if !yield(k) { + return + } + } + } + } + +Further examples can be found in [The Go Blog: Range Over Function Types]. + +Iterator functions are most often called by a [range loop], as in: + + func PrintAll[V any](seq iter.Seq[V]) { + for v := range seq { + fmt.Println(v) + } + } + +# Naming Conventions + +Iterator functions and methods are named for the sequence being walked: + + // All returns an iterator over all elements in s. + func (s *Set[V]) All() iter.Seq[V] + +The iterator method on a collection type is conventionally named All, +because it iterates a sequence of all the values in the collection. + +For a type containing multiple possible sequences, the iterator's name +can indicate which sequence is being provided: + + // Cities returns an iterator over the major cities in the country. + func (c *Country) Cities() iter.Seq[*City] + + // Languages returns an iterator over the official spoken languages of the country. + func (c *Country) Languages() iter.Seq[string] + +If an iterator requires additional configuration, the constructor function +can take additional configuration arguments: + + // Scan returns an iterator over key-value pairs with min ≤ key ≤ max. + func (m *Map[K, V]) Scan(min, max K) iter.Seq2[K, V] + + // Split returns an iterator over the (possibly-empty) substrings of s + // separated by sep. + func Split(s, sep string) iter.Seq[string] + +When there are multiple possible iteration orders, the method name may +indicate that order: + + // All returns an iterator over the list from head to tail. + func (l *List[V]) All() iter.Seq[V] + + // Backward returns an iterator over the list from tail to head. + func (l *List[V]) Backward() iter.Seq[V] + + // Preorder returns an iterator over all nodes of the syntax tree + // beneath (and including) the specified root, in depth-first preorder, + // visiting a parent node before its children. + func Preorder(root Node) iter.Seq[Node] + +# Single-Use Iterators + +Most iterators provide the ability to walk an entire sequence: +when called, the iterator does any setup necessary to start the +sequence, then calls yield on successive elements of the sequence, +and then cleans up before returning. Calling the iterator again +walks the sequence again. + +Some iterators break that convention, providing the ability to walk a +sequence only once. These “single-use iterators” typically report values +from a data stream that cannot be rewound to start over. +Calling the iterator again after stopping early may continue the +stream, but calling it again after the sequence is finished will yield +no values at all. Doc comments for functions or methods that return +single-use iterators should document this fact: + + // Lines returns an iterator over lines read from r. + // It returns a single-use iterator. + func (r *Reader) Lines() iter.Seq[string] + +# Pulling Values + +Functions and methods that accept or return iterators +should use the standard [Seq] or [Seq2] types, to ensure +compatibility with range loops and other iterator adapters. +The standard iterators can be thought of as “push iterators”, which +push values to the yield function. + +Sometimes a range loop is not the most natural way to consume values +of the sequence. In this case, [Pull] converts a standard push iterator +to a “pull iterator”, which can be called to pull one value at a time +from the sequence. [Pull] starts an iterator and returns a pair +of functions—next and stop—which return the next value from the iterator +and stop it, respectively. + +For example: + + // Pairs returns an iterator over successive pairs of values from seq. + func Pairs[V any](seq iter.Seq[V]) iter.Seq2[V, V] { + return func(yield func(V, V) bool) { + next, stop := iter.Pull(seq) + defer stop() + for { + v1, ok1 := next() + if !ok1 { + return + } + v2, ok2 := next() + // If ok2 is false, v2 should be the + // zero value; yield one last pair. + if !yield(v1, v2) { + return + } + if !ok2 { + return + } + } + } + } + +If clients do not consume the sequence to completion, they must call stop, +which allows the iterator function to finish and return. As shown in +the example, the conventional way to ensure this is to use defer. + +# Standard Library Usage + +A few packages in the standard library provide iterator-based APIs, +most notably the [maps] and [slices] packages. +For example, [maps.Keys] returns an iterator over the keys of a map, +while [slices.Sorted] collects the values of an iterator into a slice, +sorts them, and returns the slice, so to iterate over the sorted keys of a map: + + for _, key := range slices.Sorted(maps.Keys(m)) { + ... + } + +# Mutation + +Iterators provide only the values of the sequence, not any direct way +to modify it. If an iterator wishes to provide a mechanism for modifying +a sequence during iteration, the usual approach is to define a position type +with the extra operations and then provide an iterator over positions. + +For example, a tree implementation might provide: + + // Positions returns an iterator over positions in the sequence. + func (t *Tree[V]) Positions() iter.Seq[*Pos[V]] + + // A Pos represents a position in the sequence. + // It is only valid during the yield call it is passed to. + type Pos[V any] struct { ... } + + // Value returns the value at the cursor. + func (p *Pos[V]) Value() V + + // Delete deletes the value at this point in the iteration. + func (p *Pos[V]) Delete() + + // Set changes the value v at the cursor. + func (p *Pos[V]) Set(v V) + +And then a client could delete boring values from the tree using: + + for p := range t.Positions() { + if boring(p.Value()) { + p.Delete() + } + } + +[The Go Blog: Range Over Function Types]: https://go.dev/blog/range-functions +[range loop]: https://go.dev/ref/spec#For_range +*/ +package iter + +import ( + "internal/race" + "runtime" + "unsafe" +) + +// Seq is an iterator over sequences of individual values. +// When called as seq(yield), seq calls yield(v) for each value v in the sequence, +// stopping early if yield returns false. +// See the [iter] package documentation for more details. +type Seq[V any] func(yield func(V) bool) + +// Seq2 is an iterator over sequences of pairs of values, most commonly key-value pairs. +// When called as seq(yield), seq calls yield(k, v) for each pair (k, v) in the sequence, +// stopping early if yield returns false. +// See the [iter] package documentation for more details. +type Seq2[K, V any] func(yield func(K, V) bool) + +type coro struct{} + +//go:linkname newcoro runtime.newcoro +func newcoro(func(*coro)) *coro + +//go:linkname coroswitch runtime.coroswitch +func coroswitch(*coro) + +// Pull converts the “push-style” iterator sequence seq +// into a “pull-style” iterator accessed by the two functions +// next and stop. +// +// Next returns the next value in the sequence +// and a boolean indicating whether the value is valid. +// When the sequence is over, next returns the zero V and false. +// It is valid to call next after reaching the end of the sequence +// or after calling stop. These calls will continue +// to return the zero V and false. +// +// Stop ends the iteration. It must be called when the caller is +// no longer interested in next values and next has not yet +// signaled that the sequence is over (with a false boolean return). +// It is valid to call stop multiple times and when next has +// already returned false. Typically, callers should “defer stop()”. +// +// It is an error to call next or stop from multiple goroutines +// simultaneously. +// +// If the iterator panics during a call to next (or stop), +// then next (or stop) itself panics with the same value. +func Pull[V any](seq Seq[V]) (next func() (V, bool), stop func()) { + var pull struct { + v V + ok bool + done bool + yieldNext bool + seqDone bool // to detect Goexit + racer int + panicValue any + } + c := newcoro(func(c *coro) { + race.Acquire(unsafe.Pointer(&pull.racer)) + if pull.done { + race.Release(unsafe.Pointer(&pull.racer)) + return + } + yield := func(v1 V) bool { + if pull.done { + return false + } + if !pull.yieldNext { + panic("iter.Pull: yield called again before next") + } + pull.yieldNext = false + pull.v, pull.ok = v1, true + race.Release(unsafe.Pointer(&pull.racer)) + coroswitch(c) + race.Acquire(unsafe.Pointer(&pull.racer)) + return !pull.done + } + // Recover and propagate panics from seq. + defer func() { + if p := recover(); p != nil { + pull.panicValue = p + } else if !pull.seqDone { + pull.panicValue = goexitPanicValue + } + pull.done = true // Invalidate iterator + race.Release(unsafe.Pointer(&pull.racer)) + }() + seq(yield) + var v0 V + pull.v, pull.ok = v0, false + pull.seqDone = true + }) + next = func() (v1 V, ok1 bool) { + race.Write(unsafe.Pointer(&pull.racer)) // detect races + + if pull.done { + return + } + if pull.yieldNext { + panic("iter.Pull: next called again before yield") + } + pull.yieldNext = true + race.Release(unsafe.Pointer(&pull.racer)) + coroswitch(c) + race.Acquire(unsafe.Pointer(&pull.racer)) + + // Propagate panics and goexits from seq. + if pull.panicValue != nil { + if pull.panicValue == goexitPanicValue { + // Propagate runtime.Goexit from seq. + runtime.Goexit() + } else { + panic(pull.panicValue) + } + } + return pull.v, pull.ok + } + stop = func() { + race.Write(unsafe.Pointer(&pull.racer)) // detect races + + if !pull.done { + pull.done = true + race.Release(unsafe.Pointer(&pull.racer)) + coroswitch(c) + race.Acquire(unsafe.Pointer(&pull.racer)) + + // Propagate panics and goexits from seq. + if pull.panicValue != nil { + if pull.panicValue == goexitPanicValue { + // Propagate runtime.Goexit from seq. + runtime.Goexit() + } else { + panic(pull.panicValue) + } + } + } + } + return next, stop +} + +// Pull2 converts the “push-style” iterator sequence seq +// into a “pull-style” iterator accessed by the two functions +// next and stop. +// +// Next returns the next pair in the sequence +// and a boolean indicating whether the pair is valid. +// When the sequence is over, next returns a pair of zero values and false. +// It is valid to call next after reaching the end of the sequence +// or after calling stop. These calls will continue +// to return a pair of zero values and false. +// +// Stop ends the iteration. It must be called when the caller is +// no longer interested in next values and next has not yet +// signaled that the sequence is over (with a false boolean return). +// It is valid to call stop multiple times and when next has +// already returned false. Typically, callers should “defer stop()”. +// +// It is an error to call next or stop from multiple goroutines +// simultaneously. +// +// If the iterator panics during a call to next (or stop), +// then next (or stop) itself panics with the same value. +func Pull2[K, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func()) { + var pull struct { + k K + v V + ok bool + done bool + yieldNext bool + seqDone bool + racer int + panicValue any + } + c := newcoro(func(c *coro) { + race.Acquire(unsafe.Pointer(&pull.racer)) + if pull.done { + race.Release(unsafe.Pointer(&pull.racer)) + return + } + yield := func(k1 K, v1 V) bool { + if pull.done { + return false + } + if !pull.yieldNext { + panic("iter.Pull2: yield called again before next") + } + pull.yieldNext = false + pull.k, pull.v, pull.ok = k1, v1, true + race.Release(unsafe.Pointer(&pull.racer)) + coroswitch(c) + race.Acquire(unsafe.Pointer(&pull.racer)) + return !pull.done + } + // Recover and propagate panics from seq. + defer func() { + if p := recover(); p != nil { + pull.panicValue = p + } else if !pull.seqDone { + pull.panicValue = goexitPanicValue + } + pull.done = true // Invalidate iterator. + race.Release(unsafe.Pointer(&pull.racer)) + }() + seq(yield) + var k0 K + var v0 V + pull.k, pull.v, pull.ok = k0, v0, false + pull.seqDone = true + }) + next = func() (k1 K, v1 V, ok1 bool) { + race.Write(unsafe.Pointer(&pull.racer)) // detect races + + if pull.done { + return + } + if pull.yieldNext { + panic("iter.Pull2: next called again before yield") + } + pull.yieldNext = true + race.Release(unsafe.Pointer(&pull.racer)) + coroswitch(c) + race.Acquire(unsafe.Pointer(&pull.racer)) + + // Propagate panics and goexits from seq. + if pull.panicValue != nil { + if pull.panicValue == goexitPanicValue { + // Propagate runtime.Goexit from seq. + runtime.Goexit() + } else { + panic(pull.panicValue) + } + } + return pull.k, pull.v, pull.ok + } + stop = func() { + race.Write(unsafe.Pointer(&pull.racer)) // detect races + + if !pull.done { + pull.done = true + race.Release(unsafe.Pointer(&pull.racer)) + coroswitch(c) + race.Acquire(unsafe.Pointer(&pull.racer)) + + // Propagate panics and goexits from seq. + if pull.panicValue != nil { + if pull.panicValue == goexitPanicValue { + // Propagate runtime.Goexit from seq. + runtime.Goexit() + } else { + panic(pull.panicValue) + } + } + } + } + return next, stop +} + +// goexitPanicValue is a sentinel value indicating that an iterator +// exited via runtime.Goexit. +var goexitPanicValue any = new(int) diff --git a/go/src/iter/pull_test.go b/go/src/iter/pull_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c66e20897bd8af05596c08448e8214bad7c64407 --- /dev/null +++ b/go/src/iter/pull_test.go @@ -0,0 +1,509 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package iter_test + +import ( + "fmt" + . "iter" + "runtime" + "testing" +) + +func count(n int) Seq[int] { + return func(yield func(int) bool) { + for i := range n { + if !yield(i) { + break + } + } + } +} + +func squares(n int) Seq2[int, int64] { + return func(yield func(int, int64) bool) { + for i := range n { + if !yield(i, int64(i)*int64(i)) { + break + } + } + } +} + +func TestPull(t *testing.T) { + for end := 0; end <= 3; end++ { + t.Run(fmt.Sprint(end), func(t *testing.T) { + ng := stableNumGoroutine() + wantNG := func(want int) { + if xg := runtime.NumGoroutine() - ng; xg != want { + t.Helper() + t.Errorf("have %d extra goroutines, want %d", xg, want) + } + } + wantNG(0) + next, stop := Pull(count(3)) + wantNG(1) + for i := range end { + v, ok := next() + if v != i || ok != true { + t.Fatalf("next() = %d, %v, want %d, %v", v, ok, i, true) + } + wantNG(1) + } + wantNG(1) + if end < 3 { + stop() + wantNG(0) + } + for range 2 { + v, ok := next() + if v != 0 || ok != false { + t.Fatalf("next() = %d, %v, want %d, %v", v, ok, 0, false) + } + wantNG(0) + } + wantNG(0) + + stop() + stop() + stop() + wantNG(0) + }) + } +} + +func TestPull2(t *testing.T) { + for end := 0; end <= 3; end++ { + t.Run(fmt.Sprint(end), func(t *testing.T) { + ng := stableNumGoroutine() + wantNG := func(want int) { + if xg := runtime.NumGoroutine() - ng; xg != want { + t.Helper() + t.Errorf("have %d extra goroutines, want %d", xg, want) + } + } + wantNG(0) + next, stop := Pull2(squares(3)) + wantNG(1) + for i := range end { + k, v, ok := next() + if k != i || v != int64(i*i) || ok != true { + t.Fatalf("next() = %d, %d, %v, want %d, %d, %v", k, v, ok, i, i*i, true) + } + wantNG(1) + } + wantNG(1) + if end < 3 { + stop() + wantNG(0) + } + for range 2 { + k, v, ok := next() + if v != 0 || ok != false { + t.Fatalf("next() = %d, %d, %v, want %d, %d, %v", k, v, ok, 0, 0, false) + } + wantNG(0) + } + wantNG(0) + + stop() + stop() + stop() + wantNG(0) + }) + } +} + +// stableNumGoroutine is like NumGoroutine but tries to ensure stability of +// the value by letting any exiting goroutines finish exiting. +func stableNumGoroutine() int { + // The idea behind stablizing the value of NumGoroutine is to + // see the same value enough times in a row in between calls to + // runtime.Gosched. With GOMAXPROCS=1, we're trying to make sure + // that other goroutines run, so that they reach a stable point. + // It's not guaranteed, because it is still possible for a goroutine + // to Gosched back into itself, so we require NumGoroutine to be + // the same 100 times in a row. This should be more than enough to + // ensure all goroutines get a chance to run to completion (or to + // some block point) for a small group of test goroutines. + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) + + c := 0 + ng := runtime.NumGoroutine() + for i := 0; i < 1000; i++ { + nng := runtime.NumGoroutine() + if nng == ng { + c++ + } else { + c = 0 + ng = nng + } + if c >= 100 { + // The same value 100 times in a row is good enough. + return ng + } + runtime.Gosched() + } + panic("failed to stabilize NumGoroutine after 1000 iterations") +} + +func TestPullDoubleNext(t *testing.T) { + next, _ := Pull(doDoubleNext()) + nextSlot = next + next() + if nextSlot != nil { + t.Fatal("double next did not fail") + } +} + +var nextSlot func() (int, bool) + +func doDoubleNext() Seq[int] { + return func(_ func(int) bool) { + defer func() { + if recover() != nil { + nextSlot = nil + } + }() + nextSlot() + } +} + +func TestPullDoubleNext2(t *testing.T) { + next, _ := Pull2(doDoubleNext2()) + nextSlot2 = next + next() + if nextSlot2 != nil { + t.Fatal("double next did not fail") + } +} + +var nextSlot2 func() (int, int, bool) + +func doDoubleNext2() Seq2[int, int] { + return func(_ func(int, int) bool) { + defer func() { + if recover() != nil { + nextSlot2 = nil + } + }() + nextSlot2() + } +} + +func TestPullDoubleYield(t *testing.T) { + next, stop := Pull(storeYield()) + next() + if yieldSlot == nil { + t.Fatal("yield failed") + } + defer func() { + if recover() != nil { + yieldSlot = nil + } + stop() + }() + yieldSlot(5) + if yieldSlot != nil { + t.Fatal("double yield did not fail") + } +} + +func storeYield() Seq[int] { + return func(yield func(int) bool) { + yieldSlot = yield + if !yield(5) { + return + } + } +} + +var yieldSlot func(int) bool + +func TestPullDoubleYield2(t *testing.T) { + next, stop := Pull2(storeYield2()) + next() + if yieldSlot2 == nil { + t.Fatal("yield failed") + } + defer func() { + if recover() != nil { + yieldSlot2 = nil + } + stop() + }() + yieldSlot2(23, 77) + if yieldSlot2 != nil { + t.Fatal("double yield did not fail") + } +} + +func storeYield2() Seq2[int, int] { + return func(yield func(int, int) bool) { + yieldSlot2 = yield + if !yield(23, 77) { + return + } + } +} + +var yieldSlot2 func(int, int) bool + +func TestPullPanic(t *testing.T) { + t.Run("next", func(t *testing.T) { + next, stop := Pull(panicSeq()) + if !panicsWith("boom", func() { next() }) { + t.Fatal("failed to propagate panic on first next") + } + // Make sure we don't panic again if we try to call next or stop. + if _, ok := next(); ok { + t.Fatal("next returned true after iterator panicked") + } + // Calling stop again should be a no-op. + stop() + }) + t.Run("stop", func(t *testing.T) { + next, stop := Pull(panicCleanupSeq()) + x, ok := next() + if !ok || x != 55 { + t.Fatalf("expected (55, true) from next, got (%d, %t)", x, ok) + } + if !panicsWith("boom", func() { stop() }) { + t.Fatal("failed to propagate panic on stop") + } + // Make sure we don't panic again if we try to call next or stop. + if _, ok := next(); ok { + t.Fatal("next returned true after iterator panicked") + } + // Calling stop again should be a no-op. + stop() + }) +} + +func panicSeq() Seq[int] { + return func(yield func(int) bool) { + panic("boom") + } +} + +func panicCleanupSeq() Seq[int] { + return func(yield func(int) bool) { + for { + if !yield(55) { + panic("boom") + } + } + } +} + +func TestPull2Panic(t *testing.T) { + t.Run("next", func(t *testing.T) { + next, stop := Pull2(panicSeq2()) + if !panicsWith("boom", func() { next() }) { + t.Fatal("failed to propagate panic on first next") + } + // Make sure we don't panic again if we try to call next or stop. + if _, _, ok := next(); ok { + t.Fatal("next returned true after iterator panicked") + } + // Calling stop again should be a no-op. + stop() + }) + t.Run("stop", func(t *testing.T) { + next, stop := Pull2(panicCleanupSeq2()) + x, y, ok := next() + if !ok || x != 55 || y != 100 { + t.Fatalf("expected (55, 100, true) from next, got (%d, %d, %t)", x, y, ok) + } + if !panicsWith("boom", func() { stop() }) { + t.Fatal("failed to propagate panic on stop") + } + // Make sure we don't panic again if we try to call next or stop. + if _, _, ok := next(); ok { + t.Fatal("next returned true after iterator panicked") + } + // Calling stop again should be a no-op. + stop() + }) +} + +func panicSeq2() Seq2[int, int] { + return func(yield func(int, int) bool) { + panic("boom") + } +} + +func panicCleanupSeq2() Seq2[int, int] { + return func(yield func(int, int) bool) { + for { + if !yield(55, 100) { + panic("boom") + } + } + } +} + +func panicsWith(v any, f func()) (panicked bool) { + defer func() { + if r := recover(); r != nil { + if r != v { + panic(r) + } + panicked = true + } + }() + f() + return +} + +func TestPullGoexit(t *testing.T) { + t.Run("next", func(t *testing.T) { + var next func() (int, bool) + var stop func() + if !goexits(t, func() { + next, stop = Pull(goexitSeq()) + next() + }) { + t.Fatal("failed to Goexit from next") + } + if x, ok := next(); x != 0 || ok { + t.Fatal("iterator returned valid value after iterator Goexited") + } + stop() + }) + t.Run("stop", func(t *testing.T) { + next, stop := Pull(goexitCleanupSeq()) + x, ok := next() + if !ok || x != 55 { + t.Fatalf("expected (55, true) from next, got (%d, %t)", x, ok) + } + if !goexits(t, func() { + stop() + }) { + t.Fatal("failed to Goexit from stop") + } + // Make sure we don't panic again if we try to call next or stop. + if x, ok := next(); x != 0 || ok { + t.Fatal("next returned true or non-zero value after iterator Goexited") + } + // Calling stop again should be a no-op. + stop() + }) +} + +func goexitSeq() Seq[int] { + return func(yield func(int) bool) { + runtime.Goexit() + } +} + +func goexitCleanupSeq() Seq[int] { + return func(yield func(int) bool) { + for { + if !yield(55) { + runtime.Goexit() + } + } + } +} + +func TestPull2Goexit(t *testing.T) { + t.Run("next", func(t *testing.T) { + var next func() (int, int, bool) + var stop func() + if !goexits(t, func() { + next, stop = Pull2(goexitSeq2()) + next() + }) { + t.Fatal("failed to Goexit from next") + } + if x, y, ok := next(); x != 0 || y != 0 || ok { + t.Fatal("iterator returned valid value after iterator Goexited") + } + stop() + }) + t.Run("stop", func(t *testing.T) { + next, stop := Pull2(goexitCleanupSeq2()) + x, y, ok := next() + if !ok || x != 55 || y != 100 { + t.Fatalf("expected (55, 100, true) from next, got (%d, %d, %t)", x, y, ok) + } + if !goexits(t, func() { + stop() + }) { + t.Fatal("failed to Goexit from stop") + } + // Make sure we don't panic again if we try to call next or stop. + if x, y, ok := next(); x != 0 || y != 0 || ok { + t.Fatal("next returned true or non-zero after iterator Goexited") + } + // Calling stop again should be a no-op. + stop() + }) +} + +func goexitSeq2() Seq2[int, int] { + return func(yield func(int, int) bool) { + runtime.Goexit() + } +} + +func goexitCleanupSeq2() Seq2[int, int] { + return func(yield func(int, int) bool) { + for { + if !yield(55, 100) { + runtime.Goexit() + } + } + } +} + +func goexits(t *testing.T, f func()) bool { + t.Helper() + + exit := make(chan bool) + go func() { + cleanExit := false + defer func() { + exit <- recover() == nil && !cleanExit + }() + f() + cleanExit = true + }() + return <-exit +} + +func TestPullImmediateStop(t *testing.T) { + next, stop := Pull(panicSeq()) + stop() + // Make sure we don't panic if we try to call next or stop. + if _, ok := next(); ok { + t.Fatal("next returned true after iterator was stopped") + } +} + +func TestPull2ImmediateStop(t *testing.T) { + next, stop := Pull2(panicSeq2()) + stop() + // Make sure we don't panic if we try to call next or stop. + if _, _, ok := next(); ok { + t.Fatal("next returned true after iterator was stopped") + } +} + +func BenchmarkPull(b *testing.B) { + seq := count(1) + for range b.N { + _, stop := Pull(seq) + stop() + } +} + +func BenchmarkPull2(b *testing.B) { + seq := squares(1) + for range b.N { + _, stop := Pull2(seq) + stop() + } +} diff --git a/go/src/log/example_test.go b/go/src/log/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..769d076e9d59870bc93cacee20dd5e57d08ebd70 --- /dev/null +++ b/go/src/log/example_test.go @@ -0,0 +1,41 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package log_test + +import ( + "bytes" + "fmt" + "log" +) + +func ExampleLogger() { + var ( + buf bytes.Buffer + logger = log.New(&buf, "logger: ", log.Lshortfile) + ) + + logger.Print("Hello, log file!") + + fmt.Print(&buf) + // Output: + // logger: example_test.go:19: Hello, log file! +} + +func ExampleLogger_Output() { + var ( + buf bytes.Buffer + logger = log.New(&buf, "INFO: ", log.Lshortfile) + + infof = func(info string) { + logger.Output(2, info) + } + ) + + infof("Hello world") + + fmt.Print(&buf) + // Output: + // INFO: example_test.go:36: Hello world +} diff --git a/go/src/log/log.go b/go/src/log/log.go new file mode 100644 index 0000000000000000000000000000000000000000..c79b3a9b7428db49387fbde49017194541f8dd18 --- /dev/null +++ b/go/src/log/log.go @@ -0,0 +1,483 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package log implements a simple logging package. It defines a type, [Logger], +// with methods for formatting output. It also has a predefined 'standard' +// Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and +// Panic[f|ln], which are easier to use than creating a Logger manually. +// That logger writes to standard error and prints the date and time +// of each logged message. +// Every log message is output on a separate line: if the message being +// printed does not end in a newline, the logger will add one. +// The Fatal functions call [os.Exit](1) after writing the log message. +// The Panic functions call panic after writing the log message. +package log + +import ( + "fmt" + "io" + "log/internal" + "os" + "runtime" + "sync" + "sync/atomic" + "time" +) + +// These flags define which text to prefix to each log entry generated by the [Logger]. +// Bits are or'ed together to control what's printed. +// With the exception of the Lmsgprefix flag, there is no +// control over the order they appear (the order listed here) +// or the format they present (as described in the comments). +// The prefix is followed by a colon only when Llongfile or Lshortfile +// is specified. +// For example, flags Ldate | Ltime (or LstdFlags) produce, +// +// 2009/01/23 01:23:23 message +// +// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce, +// +// 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message +const ( + Ldate = 1 << iota // the date in the local time zone: 2009/01/23 + Ltime // the time in the local time zone: 01:23:23 + Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime. + Llongfile // full file name and line number: /a/b/c/d.go:23 + Lshortfile // final file name element and line number: d.go:23. overrides Llongfile + LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone + Lmsgprefix // move the "prefix" from the beginning of the line to before the message + LstdFlags = Ldate | Ltime // initial values for the standard logger +) + +// A Logger represents an active logging object that generates lines of +// output to an [io.Writer]. Each logging operation makes a single call to +// the Writer's Write method. A Logger can be used simultaneously from +// multiple goroutines; it guarantees to serialize access to the Writer. +type Logger struct { + outMu sync.Mutex + out io.Writer // destination for output + + prefix atomic.Pointer[string] // prefix on each line to identify the logger (but see Lmsgprefix) + flag atomic.Int32 // properties + isDiscard atomic.Bool +} + +// New creates a new [Logger]. The out variable sets the +// destination to which log data will be written. +// The prefix appears at the beginning of each generated log line, or +// after the log header if the [Lmsgprefix] flag is provided. +// The flag argument defines the logging properties. +func New(out io.Writer, prefix string, flag int) *Logger { + l := new(Logger) + l.SetOutput(out) + l.SetPrefix(prefix) + l.SetFlags(flag) + return l +} + +// SetOutput sets the output destination for the logger. +func (l *Logger) SetOutput(w io.Writer) { + l.outMu.Lock() + defer l.outMu.Unlock() + l.out = w + l.isDiscard.Store(w == io.Discard) +} + +var std = New(os.Stderr, "", LstdFlags) + +// Default returns the standard logger used by the package-level output functions. +func Default() *Logger { return std } + +// Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding. +func itoa(buf *[]byte, i int, wid int) { + // Assemble decimal in reverse order. + var b [20]byte + bp := len(b) - 1 + for i >= 10 || wid > 1 { + wid-- + q := i / 10 + b[bp] = byte('0' + i - q*10) + bp-- + i = q + } + // i < 10 + b[bp] = byte('0' + i) + *buf = append(*buf, b[bp:]...) +} + +// formatHeader writes log header to buf in following order: +// - l.prefix (if it's not blank and Lmsgprefix is unset), +// - date and/or time (if corresponding flags are provided), +// - file and line number (if corresponding flags are provided), +// - l.prefix (if it's not blank and Lmsgprefix is set). +func formatHeader(buf *[]byte, t time.Time, prefix string, flag int, file string, line int) { + if flag&Lmsgprefix == 0 { + *buf = append(*buf, prefix...) + } + if flag&(Ldate|Ltime|Lmicroseconds) != 0 { + if flag&LUTC != 0 { + t = t.UTC() + } + if flag&Ldate != 0 { + year, month, day := t.Date() + itoa(buf, year, 4) + *buf = append(*buf, '/') + itoa(buf, int(month), 2) + *buf = append(*buf, '/') + itoa(buf, day, 2) + *buf = append(*buf, ' ') + } + if flag&(Ltime|Lmicroseconds) != 0 { + hour, min, sec := t.Clock() + itoa(buf, hour, 2) + *buf = append(*buf, ':') + itoa(buf, min, 2) + *buf = append(*buf, ':') + itoa(buf, sec, 2) + if flag&Lmicroseconds != 0 { + *buf = append(*buf, '.') + itoa(buf, t.Nanosecond()/1e3, 6) + } + *buf = append(*buf, ' ') + } + } + if flag&(Lshortfile|Llongfile) != 0 { + if flag&Lshortfile != 0 { + short := file + for i := len(file) - 1; i > 0; i-- { + if file[i] == '/' { + short = file[i+1:] + break + } + } + file = short + } + *buf = append(*buf, file...) + *buf = append(*buf, ':') + itoa(buf, line, -1) + *buf = append(*buf, ": "...) + } + if flag&Lmsgprefix != 0 { + *buf = append(*buf, prefix...) + } +} + +var bufferPool = sync.Pool{New: func() any { return new([]byte) }} + +func getBuffer() *[]byte { + p := bufferPool.Get().(*[]byte) + *p = (*p)[:0] + return p +} + +func putBuffer(p *[]byte) { + // Proper usage of a sync.Pool requires each entry to have approximately + // the same memory cost. To obtain this property when the stored type + // contains a variably-sized buffer, we add a hard limit on the maximum buffer + // to place back in the pool. + // + // See https://go.dev/issue/23199 + if cap(*p) > 64<<10 { + *p = nil + } + bufferPool.Put(p) +} + +// Output writes the output for a logging event. The string s contains +// the text to print after the prefix specified by the flags of the +// Logger. A newline is appended if the last character of s is not +// already a newline. Calldepth is used to recover the PC and is +// provided for generality, although at the moment on all pre-defined +// paths it will be 2. +func (l *Logger) Output(calldepth int, s string) error { + return l.output(0, calldepth+1, func(b []byte) []byte { // +1 for this frame. + return append(b, s...) + }) +} + +// output can take either a calldepth or a pc to get source line information. +// It uses the pc if it is non-zero. +func (l *Logger) output(pc uintptr, calldepth int, appendOutput func([]byte) []byte) error { + if l.isDiscard.Load() { + return nil + } + + now := time.Now() // get this early. + + // Load prefix and flag once so that their value is consistent within + // this call regardless of any concurrent changes to their value. + prefix := l.Prefix() + flag := l.Flags() + + var file string + var line int + if flag&(Lshortfile|Llongfile) != 0 { + if pc == 0 { + var ok bool + _, file, line, ok = runtime.Caller(calldepth) + if !ok { + file = "???" + line = 0 + } + } else { + fs := runtime.CallersFrames([]uintptr{pc}) + f, _ := fs.Next() + file = f.File + if file == "" { + file = "???" + } + line = f.Line + } + } + + buf := getBuffer() + defer putBuffer(buf) + formatHeader(buf, now, prefix, flag, file, line) + *buf = appendOutput(*buf) + if len(*buf) == 0 || (*buf)[len(*buf)-1] != '\n' { + *buf = append(*buf, '\n') + } + + l.outMu.Lock() + defer l.outMu.Unlock() + _, err := l.out.Write(*buf) + return err +} + +func init() { + internal.DefaultOutput = func(pc uintptr, data []byte) error { + return std.output(pc, 0, func(buf []byte) []byte { + return append(buf, data...) + }) + } +} + +// Print calls l.Output to print to the logger. +// Arguments are handled in the manner of [fmt.Print]. +func (l *Logger) Print(v ...any) { + l.output(0, 2, func(b []byte) []byte { + return fmt.Append(b, v...) + }) +} + +// Printf calls l.Output to print to the logger. +// Arguments are handled in the manner of [fmt.Printf]. +func (l *Logger) Printf(format string, v ...any) { + l.output(0, 2, func(b []byte) []byte { + return fmt.Appendf(b, format, v...) + }) +} + +// Println calls l.Output to print to the logger. +// Arguments are handled in the manner of [fmt.Println]. +func (l *Logger) Println(v ...any) { + l.output(0, 2, func(b []byte) []byte { + return fmt.Appendln(b, v...) + }) +} + +// Fatal is equivalent to l.Print() followed by a call to [os.Exit](1). +func (l *Logger) Fatal(v ...any) { + l.output(0, 2, func(b []byte) []byte { + return fmt.Append(b, v...) + }) + os.Exit(1) +} + +// Fatalf is equivalent to l.Printf() followed by a call to [os.Exit](1). +func (l *Logger) Fatalf(format string, v ...any) { + l.output(0, 2, func(b []byte) []byte { + return fmt.Appendf(b, format, v...) + }) + os.Exit(1) +} + +// Fatalln is equivalent to l.Println() followed by a call to [os.Exit](1). +func (l *Logger) Fatalln(v ...any) { + l.output(0, 2, func(b []byte) []byte { + return fmt.Appendln(b, v...) + }) + os.Exit(1) +} + +// Panic is equivalent to l.Print() followed by a call to panic(). +func (l *Logger) Panic(v ...any) { + s := fmt.Sprint(v...) + l.output(0, 2, func(b []byte) []byte { + return append(b, s...) + }) + panic(s) +} + +// Panicf is equivalent to l.Printf() followed by a call to panic(). +func (l *Logger) Panicf(format string, v ...any) { + s := fmt.Sprintf(format, v...) + l.output(0, 2, func(b []byte) []byte { + return append(b, s...) + }) + panic(s) +} + +// Panicln is equivalent to l.Println() followed by a call to panic(). +func (l *Logger) Panicln(v ...any) { + s := fmt.Sprintln(v...) + l.output(0, 2, func(b []byte) []byte { + return append(b, s...) + }) + panic(s) +} + +// Flags returns the output flags for the logger. +// The flag bits are [Ldate], [Ltime], and so on. +func (l *Logger) Flags() int { + return int(l.flag.Load()) +} + +// SetFlags sets the output flags for the logger. +// The flag bits are [Ldate], [Ltime], and so on. +func (l *Logger) SetFlags(flag int) { + l.flag.Store(int32(flag)) +} + +// Prefix returns the output prefix for the logger. +func (l *Logger) Prefix() string { + if p := l.prefix.Load(); p != nil { + return *p + } + return "" +} + +// SetPrefix sets the output prefix for the logger. +func (l *Logger) SetPrefix(prefix string) { + l.prefix.Store(&prefix) +} + +// Writer returns the output destination for the logger. +func (l *Logger) Writer() io.Writer { + l.outMu.Lock() + defer l.outMu.Unlock() + return l.out +} + +// SetOutput sets the output destination for the standard logger. +func SetOutput(w io.Writer) { + std.SetOutput(w) +} + +// Flags returns the output flags for the standard logger. +// The flag bits are [Ldate], [Ltime], and so on. +func Flags() int { + return std.Flags() +} + +// SetFlags sets the output flags for the standard logger. +// The flag bits are [Ldate], [Ltime], and so on. +func SetFlags(flag int) { + std.SetFlags(flag) +} + +// Prefix returns the output prefix for the standard logger. +func Prefix() string { + return std.Prefix() +} + +// SetPrefix sets the output prefix for the standard logger. +func SetPrefix(prefix string) { + std.SetPrefix(prefix) +} + +// Writer returns the output destination for the standard logger. +func Writer() io.Writer { + return std.Writer() +} + +// These functions write to the standard logger. + +// Print calls Output to print to the standard logger. +// Arguments are handled in the manner of [fmt.Print]. +func Print(v ...any) { + std.output(0, 2, func(b []byte) []byte { + return fmt.Append(b, v...) + }) +} + +// Printf calls Output to print to the standard logger. +// Arguments are handled in the manner of [fmt.Printf]. +func Printf(format string, v ...any) { + std.output(0, 2, func(b []byte) []byte { + return fmt.Appendf(b, format, v...) + }) +} + +// Println calls Output to print to the standard logger. +// Arguments are handled in the manner of [fmt.Println]. +func Println(v ...any) { + std.output(0, 2, func(b []byte) []byte { + return fmt.Appendln(b, v...) + }) +} + +// Fatal is equivalent to [Print] followed by a call to [os.Exit](1). +func Fatal(v ...any) { + std.output(0, 2, func(b []byte) []byte { + return fmt.Append(b, v...) + }) + os.Exit(1) +} + +// Fatalf is equivalent to [Printf] followed by a call to [os.Exit](1). +func Fatalf(format string, v ...any) { + std.output(0, 2, func(b []byte) []byte { + return fmt.Appendf(b, format, v...) + }) + os.Exit(1) +} + +// Fatalln is equivalent to [Println] followed by a call to [os.Exit](1). +func Fatalln(v ...any) { + std.output(0, 2, func(b []byte) []byte { + return fmt.Appendln(b, v...) + }) + os.Exit(1) +} + +// Panic is equivalent to [Print] followed by a call to panic(). +func Panic(v ...any) { + s := fmt.Sprint(v...) + std.output(0, 2, func(b []byte) []byte { + return append(b, s...) + }) + panic(s) +} + +// Panicf is equivalent to [Printf] followed by a call to panic(). +func Panicf(format string, v ...any) { + s := fmt.Sprintf(format, v...) + std.output(0, 2, func(b []byte) []byte { + return append(b, s...) + }) + panic(s) +} + +// Panicln is equivalent to [Println] followed by a call to panic(). +func Panicln(v ...any) { + s := fmt.Sprintln(v...) + std.output(0, 2, func(b []byte) []byte { + return append(b, s...) + }) + panic(s) +} + +// Output writes the output for a logging event. The string s contains +// the text to print after the prefix specified by the flags of the +// Logger. A newline is appended if the last character of s is not +// already a newline. Calldepth is the count of the number of +// frames to skip when computing the file name and line number +// if [Llongfile] or [Lshortfile] is set; a value of 1 will print the details +// for the caller of Output. +func Output(calldepth int, s string) error { + return std.output(0, calldepth+1, func(b []byte) []byte { // +1 for this frame. + return append(b, s...) + }) +} diff --git a/go/src/log/log_test.go b/go/src/log/log_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5d5d38cc10dbaea262ed15e0dd42fe2787a512f7 --- /dev/null +++ b/go/src/log/log_test.go @@ -0,0 +1,364 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package log + +// These tests are too simple. + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "internal/testenv" + "io" + "os" + "os/exec" + "regexp" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +const ( + Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]` + Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]` + Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]` + Rline = `(67|69):` // must update if the calls to l.Printf / l.Print below move + Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline + Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline +) + +type tester struct { + flag int + prefix string + pattern string // regexp that log output must match; we add ^ and expected_text$ always +} + +var tests = []tester{ + // individual pieces: + {0, "", ""}, + {0, "XXX", "XXX"}, + {Ldate, "", Rdate + " "}, + {Ltime, "", Rtime + " "}, + {Ltime | Lmsgprefix, "XXX", Rtime + " XXX"}, + {Ltime | Lmicroseconds, "", Rtime + Rmicroseconds + " "}, + {Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time + {Llongfile, "", Rlongfile + " "}, + {Lshortfile, "", Rshortfile + " "}, + {Llongfile | Lshortfile, "", Rshortfile + " "}, // shortfile overrides longfile + // everything at once: + {Ldate | Ltime | Lmicroseconds | Llongfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " "}, + {Ldate | Ltime | Lmicroseconds | Lshortfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " "}, + {Ldate | Ltime | Lmicroseconds | Llongfile | Lmsgprefix, "XXX", Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " XXX"}, + {Ldate | Ltime | Lmicroseconds | Lshortfile | Lmsgprefix, "XXX", Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " XXX"}, +} + +// Test using Println("hello", 23, "world") or using Printf("hello %d world", 23) +func testPrint(t *testing.T, flag int, prefix string, pattern string, useFormat bool) { + buf := new(strings.Builder) + SetOutput(buf) + SetFlags(flag) + SetPrefix(prefix) + if useFormat { + Printf("hello %d world", 23) + } else { + Println("hello", 23, "world") + } + line := buf.String() + line = line[0 : len(line)-1] + pattern = "^" + pattern + "hello 23 world$" + matched, err := regexp.MatchString(pattern, line) + if err != nil { + t.Fatal("pattern did not compile:", err) + } + if !matched { + t.Errorf("log output should match %q is %q", pattern, line) + } + SetOutput(os.Stderr) +} + +func TestDefault(t *testing.T) { + if got := Default(); got != std { + t.Errorf("Default [%p] should be std [%p]", got, std) + } +} + +func TestAll(t *testing.T) { + for _, testcase := range tests { + testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, false) + testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, true) + } +} + +func TestOutput(t *testing.T) { + const testString = "test" + var b strings.Builder + l := New(&b, "", 0) + l.Println(testString) + if expect := testString + "\n"; b.String() != expect { + t.Errorf("log output should match %q is %q", expect, b.String()) + } +} + +func TestNonNewLogger(t *testing.T) { + var l Logger + l.SetOutput(new(bytes.Buffer)) // minimal work to initialize a Logger + l.Print("hello") +} + +func TestOutputRace(t *testing.T) { + var b bytes.Buffer + l := New(&b, "", 0) + var wg sync.WaitGroup + wg.Add(100) + for i := 0; i < 100; i++ { + go func() { + defer wg.Done() + l.SetFlags(0) + l.Output(0, "") + }() + } + wg.Wait() +} + +func TestFlagAndPrefixSetting(t *testing.T) { + var b bytes.Buffer + l := New(&b, "Test:", LstdFlags) + f := l.Flags() + if f != LstdFlags { + t.Errorf("Flags 1: expected %x got %x", LstdFlags, f) + } + l.SetFlags(f | Lmicroseconds) + f = l.Flags() + if f != LstdFlags|Lmicroseconds { + t.Errorf("Flags 2: expected %x got %x", LstdFlags|Lmicroseconds, f) + } + p := l.Prefix() + if p != "Test:" { + t.Errorf(`Prefix: expected "Test:" got %q`, p) + } + l.SetPrefix("Reality:") + p = l.Prefix() + if p != "Reality:" { + t.Errorf(`Prefix: expected "Reality:" got %q`, p) + } + // Verify a log message looks right, with our prefix and microseconds present. + l.Print("hello") + pattern := "^Reality:" + Rdate + " " + Rtime + Rmicroseconds + " hello\n" + matched, err := regexp.Match(pattern, b.Bytes()) + if err != nil { + t.Fatalf("pattern %q did not compile: %s", pattern, err) + } + if !matched { + t.Error("message did not match pattern") + } + + // Ensure that a newline is added only if the buffer lacks a newline suffix. + b.Reset() + l.SetFlags(0) + l.SetPrefix("\n") + l.Output(0, "") + if got := b.String(); got != "\n" { + t.Errorf("message mismatch:\ngot %q\nwant %q", got, "\n") + } +} + +func TestUTCFlag(t *testing.T) { + var b strings.Builder + l := New(&b, "Test:", LstdFlags) + l.SetFlags(Ldate | Ltime | LUTC) + // Verify a log message looks right in the right time zone. Quantize to the second only. + now := time.Now().UTC() + l.Print("hello") + want := fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n", + now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) + got := b.String() + if got == want { + return + } + // It's possible we crossed a second boundary between getting now and logging, + // so add a second and try again. This should very nearly always work. + now = now.Add(time.Second) + want = fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n", + now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) + if got == want { + return + } + t.Errorf("got %q; want %q", got, want) +} + +func TestEmptyPrintCreatesLine(t *testing.T) { + var b strings.Builder + l := New(&b, "Header:", LstdFlags) + l.Print() + l.Println("non-empty") + output := b.String() + if n := strings.Count(output, "Header"); n != 2 { + t.Errorf("expected 2 headers, got %d", n) + } + if n := strings.Count(output, "\n"); n != 2 { + t.Errorf("expected 2 lines, got %d", n) + } +} + +func TestDiscard(t *testing.T) { + l := New(io.Discard, "", 0) + s := strings.Repeat("a", 102400) + c := testing.AllocsPerRun(100, func() { l.Printf("%s", s) }) + // One allocation for slice passed to Printf, + // but none for formatting of long string. + if c > 1 { + t.Errorf("got %v allocs, want at most 1", c) + } +} + +func TestCallDepth(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode") + } + + testenv.MustHaveExec(t) + ep, err := os.Executable() + if err != nil { + t.Fatalf("Executable failed: %v", err) + } + + tests := []struct { + name string + log func() + }{ + {"Fatal", func() { Fatal("Fatal") }}, + {"Fatalf", func() { Fatalf("Fatalf") }}, + {"Fatalln", func() { Fatalln("Fatalln") }}, + {"Output", func() { Output(1, "Output") }}, + {"Panic", func() { Panic("Panic") }}, + {"Panicf", func() { Panicf("Panicf") }}, + {"Panicln", func() { Panicf("Panicln") }}, + {"Default.Fatal", func() { Default().Fatal("Default.Fatal") }}, + {"Default.Fatalf", func() { Default().Fatalf("Default.Fatalf") }}, + {"Default.Fatalln", func() { Default().Fatalln("Default.Fatalln") }}, + {"Default.Output", func() { Default().Output(1, "Default.Output") }}, + {"Default.Panic", func() { Default().Panic("Default.Panic") }}, + {"Default.Panicf", func() { Default().Panicf("Default.Panicf") }}, + {"Default.Panicln", func() { Default().Panicf("Default.Panicln") }}, + } + + // calculate the line offset until the first test case + _, _, line, ok := runtime.Caller(0) + if !ok { + t.Fatalf("runtime.Caller failed") + } + line -= len(tests) + 3 + + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // some of these calls uses os.Exit() to spawn a command and capture output + const envVar = "LOGTEST_CALL_DEPTH" + if os.Getenv(envVar) == "1" { + SetFlags(Lshortfile) + tt.log() + os.Exit(1) + } + + // spawn test executable + cmd := testenv.Command(t, ep, + "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", + "-test.count=1", + ) + cmd.Env = append(cmd.Environ(), envVar+"=1") + + out, err := cmd.CombinedOutput() + if _, ok := errors.AsType[*exec.ExitError](err); !ok { + t.Fatalf("expected exec.ExitError: %v", err) + } + + _, firstLine, err := bufio.ScanLines(out, true) + if err != nil { + t.Fatalf("failed to split line: %v", err) + } + got := string(firstLine) + + want := fmt.Sprintf( + "log_test.go:%d: %s", + line+i, tt.name, + ) + if got != want { + t.Errorf( + "output from %s() mismatch:\n\t got: %s\n\twant: %s", + tt.name, got, want, + ) + } + }) + } +} + +func BenchmarkItoa(b *testing.B) { + dst := make([]byte, 0, 64) + for i := 0; i < b.N; i++ { + dst = dst[0:0] + itoa(&dst, 2015, 4) // year + itoa(&dst, 1, 2) // month + itoa(&dst, 30, 2) // day + itoa(&dst, 12, 2) // hour + itoa(&dst, 56, 2) // minute + itoa(&dst, 0, 2) // second + itoa(&dst, 987654, 6) // microsecond + } +} + +func BenchmarkPrintln(b *testing.B) { + const testString = "test" + var buf bytes.Buffer + l := New(&buf, "", LstdFlags) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + buf.Reset() + l.Println(testString) + } +} + +func BenchmarkPrintlnNoFlags(b *testing.B) { + const testString = "test" + var buf bytes.Buffer + l := New(&buf, "", 0) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + buf.Reset() + l.Println(testString) + } +} + +// discard is identical to io.Discard, +// but copied here to avoid the io.Discard optimization in Logger. +type discard struct{} + +func (discard) Write(p []byte) (int, error) { + return len(p), nil +} + +func BenchmarkConcurrent(b *testing.B) { + l := New(discard{}, "prefix: ", Ldate|Ltime|Lmicroseconds|Llongfile|Lmsgprefix) + var group sync.WaitGroup + for i := runtime.NumCPU(); i > 0; i-- { + group.Add(1) + go func() { + for i := 0; i < b.N; i++ { + l.Output(0, "hello, world!") + } + defer group.Done() + }() + } + group.Wait() +} + +func BenchmarkDiscard(b *testing.B) { + l := New(io.Discard, "", LstdFlags|Lshortfile) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + l.Printf("processing %d objects from bucket %q", 1234, "fizzbuzz") + } +} diff --git a/go/src/maps/example_test.go b/go/src/maps/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b4ccff6d45c2b57e158b538b87bb4c95fe352404 --- /dev/null +++ b/go/src/maps/example_test.go @@ -0,0 +1,193 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package maps_test + +import ( + "fmt" + "maps" + "slices" + "strings" +) + +func ExampleClone() { + m1 := map[string]int{ + "key": 1, + } + m2 := maps.Clone(m1) + m2["key"] = 100 + fmt.Println(m1["key"]) + fmt.Println(m2["key"]) + + m3 := map[string][]int{ + "key": {1, 2, 3}, + } + m4 := maps.Clone(m3) + fmt.Println(m4["key"][0]) + m4["key"][0] = 100 + fmt.Println(m3["key"][0]) + fmt.Println(m4["key"][0]) + + // Output: + // 1 + // 100 + // 1 + // 100 + // 100 +} + +func ExampleCopy() { + m1 := map[string]int{ + "one": 1, + "two": 2, + } + m2 := map[string]int{ + "one": 10, + } + + maps.Copy(m2, m1) + fmt.Println("m2 is:", m2) + + m2["one"] = 100 + fmt.Println("m1 is:", m1) + fmt.Println("m2 is:", m2) + + m3 := map[string][]int{ + "one": {1, 2, 3}, + "two": {4, 5, 6}, + } + m4 := map[string][]int{ + "one": {7, 8, 9}, + } + + maps.Copy(m4, m3) + fmt.Println("m4 is:", m4) + + m4["one"][0] = 100 + fmt.Println("m3 is:", m3) + fmt.Println("m4 is:", m4) + + // Output: + // m2 is: map[one:1 two:2] + // m1 is: map[one:1 two:2] + // m2 is: map[one:100 two:2] + // m4 is: map[one:[1 2 3] two:[4 5 6]] + // m3 is: map[one:[100 2 3] two:[4 5 6]] + // m4 is: map[one:[100 2 3] two:[4 5 6]] +} + +func ExampleDeleteFunc() { + m := map[string]int{ + "one": 1, + "two": 2, + "three": 3, + "four": 4, + } + maps.DeleteFunc(m, func(k string, v int) bool { + return v%2 != 0 // delete odd values + }) + fmt.Println(m) + // Output: + // map[four:4 two:2] +} + +func ExampleEqual() { + m1 := map[int]string{ + 1: "one", + 10: "Ten", + 1000: "THOUSAND", + } + m2 := map[int]string{ + 1: "one", + 10: "Ten", + 1000: "THOUSAND", + } + m3 := map[int]string{ + 1: "one", + 10: "ten", + 1000: "thousand", + } + + fmt.Println(maps.Equal(m1, m2)) + fmt.Println(maps.Equal(m1, m3)) + // Output: + // true + // false +} + +func ExampleEqualFunc() { + m1 := map[int]string{ + 1: "one", + 10: "Ten", + 1000: "THOUSAND", + } + m2 := map[int][]byte{ + 1: []byte("One"), + 10: []byte("Ten"), + 1000: []byte("Thousand"), + } + eq := maps.EqualFunc(m1, m2, func(v1 string, v2 []byte) bool { + return strings.EqualFold(v1, string(v2)) + }) + fmt.Println(eq) + // Output: + // true +} + +func ExampleAll() { + m1 := map[string]int{ + "one": 1, + "two": 2, + } + m2 := map[string]int{ + "one": 10, + } + maps.Insert(m2, maps.All(m1)) + fmt.Println("m2 is:", m2) + // Output: + // m2 is: map[one:1 two:2] +} + +func ExampleKeys() { + m1 := map[int]string{ + 1: "one", + 10: "Ten", + 1000: "THOUSAND", + } + keys := slices.Sorted(maps.Keys(m1)) + fmt.Println(keys) + // Output: + // [1 10 1000] +} + +func ExampleValues() { + m1 := map[int]string{ + 1: "one", + 10: "Ten", + 1000: "THOUSAND", + } + values := slices.Sorted(maps.Values(m1)) + fmt.Println(values) + // Output: + // [THOUSAND Ten one] +} + +func ExampleInsert() { + m1 := map[int]string{ + 1000: "THOUSAND", + } + s1 := []string{"zero", "one", "two", "three"} + maps.Insert(m1, slices.All(s1)) + fmt.Println("m1 is:", m1) + // Output: + // m1 is: map[0:zero 1:one 2:two 3:three 1000:THOUSAND] +} + +func ExampleCollect() { + s1 := []string{"zero", "one", "two", "three"} + m1 := maps.Collect(slices.All(s1)) + fmt.Println("m1 is:", m1) + // Output: + // m1 is: map[0:zero 1:one 2:two 3:three] +} diff --git a/go/src/maps/iter.go b/go/src/maps/iter.go new file mode 100644 index 0000000000000000000000000000000000000000..32f2d514c150b98027d92b0a54a6c1b00fb0ef3d --- /dev/null +++ b/go/src/maps/iter.go @@ -0,0 +1,62 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package maps + +import "iter" + +// All returns an iterator over key-value pairs from m. +// The iteration order is not specified and is not guaranteed +// to be the same from one call to the next. +func All[Map ~map[K]V, K comparable, V any](m Map) iter.Seq2[K, V] { + return func(yield func(K, V) bool) { + for k, v := range m { + if !yield(k, v) { + return + } + } + } +} + +// Keys returns an iterator over keys in m. +// The iteration order is not specified and is not guaranteed +// to be the same from one call to the next. +func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] { + return func(yield func(K) bool) { + for k := range m { + if !yield(k) { + return + } + } + } +} + +// Values returns an iterator over values in m. +// The iteration order is not specified and is not guaranteed +// to be the same from one call to the next. +func Values[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[V] { + return func(yield func(V) bool) { + for _, v := range m { + if !yield(v) { + return + } + } + } +} + +// Insert adds the key-value pairs from seq to m. +// If a key in seq already exists in m, its value will be overwritten. +func Insert[Map ~map[K]V, K comparable, V any](m Map, seq iter.Seq2[K, V]) { + for k, v := range seq { + m[k] = v + } +} + +// Collect collects key-value pairs from seq into a new map +// and returns it. +func Collect[K comparable, V any](seq iter.Seq2[K, V]) map[K]V { + m := make(map[K]V) + Insert(m, seq) + return m +} diff --git a/go/src/maps/iter_test.go b/go/src/maps/iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..64ea42aeaf6b7b4ab48995ccdbfaeee57e9f86a9 --- /dev/null +++ b/go/src/maps/iter_test.go @@ -0,0 +1,116 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package maps + +import ( + "slices" + "testing" +) + +func TestAll(t *testing.T) { + for size := 0; size < 10; size++ { + m := make(map[int]int) + for i := range size { + m[i] = i + } + cnt := 0 + for i, v := range All(m) { + v1, ok := m[i] + if !ok || v != v1 { + t.Errorf("at iteration %d got %d, %d want %d, %d", cnt, i, v, i, v1) + } + cnt++ + } + if cnt != size { + t.Errorf("read %d values expected %d", cnt, size) + } + } +} + +func TestKeys(t *testing.T) { + for size := 0; size < 10; size++ { + var want []int + m := make(map[int]int) + for i := range size { + m[i] = i + want = append(want, i) + } + + var got []int + for k := range Keys(m) { + got = append(got, k) + } + slices.Sort(got) + if !slices.Equal(got, want) { + t.Errorf("Keys(%v) = %v, want %v", m, got, want) + } + } +} + +func TestValues(t *testing.T) { + for size := 0; size < 10; size++ { + var want []int + m := make(map[int]int) + for i := range size { + m[i] = i + want = append(want, i) + } + + var got []int + for v := range Values(m) { + got = append(got, v) + } + slices.Sort(got) + if !slices.Equal(got, want) { + t.Errorf("Values(%v) = %v, want %v", m, got, want) + } + } +} + +func TestInsert(t *testing.T) { + got := map[int]int{ + 1: 1, + 2: 1, + } + Insert(got, func(yield func(int, int) bool) { + for i := 0; i < 10; i += 2 { + if !yield(i, i+1) { + return + } + } + }) + + want := map[int]int{ + 1: 1, + 2: 1, + } + for i, v := range map[int]int{ + 0: 1, + 2: 3, + 4: 5, + 6: 7, + 8: 9, + } { + want[i] = v + } + + if !Equal(got, want) { + t.Errorf("Insert got: %v, want: %v", got, want) + } +} + +func TestCollect(t *testing.T) { + m := map[int]int{ + 0: 1, + 2: 3, + 4: 5, + 6: 7, + 8: 9, + } + got := Collect(All(m)) + if !Equal(got, m) { + t.Errorf("Collect got: %v, want: %v", got, m) + } +} diff --git a/go/src/maps/maps.go b/go/src/maps/maps.go new file mode 100644 index 0000000000000000000000000000000000000000..b712dd3fe8ebaa26a4fac960cfa0eacd0adfa517 --- /dev/null +++ b/go/src/maps/maps.go @@ -0,0 +1,75 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package maps defines various functions useful with maps of any type. +// +// This package does not have any special handling for non-reflexive keys +// (keys k where k != k), such as floating-point NaNs. +package maps + +import ( + _ "unsafe" +) + +// Equal reports whether two maps contain the same key/value pairs. +// Values are compared using ==. +func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool { + if len(m1) != len(m2) { + return false + } + for k, v1 := range m1 { + if v2, ok := m2[k]; !ok || v1 != v2 { + return false + } + } + return true +} + +// EqualFunc is like Equal, but compares values using eq. +// Keys are still compared with ==. +func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool { + if len(m1) != len(m2) { + return false + } + for k, v1 := range m1 { + if v2, ok := m2[k]; !ok || !eq(v1, v2) { + return false + } + } + return true +} + +// clone is implemented in the runtime package. +// +//go:linkname clone maps.clone +func clone(m any) any + +// Clone returns a copy of m. This is a shallow clone: +// the new keys and values are set using ordinary assignment. +func Clone[M ~map[K]V, K comparable, V any](m M) M { + // Preserve nil in case it matters. + if m == nil { + return nil + } + return clone(m).(M) +} + +// Copy copies all key/value pairs in src adding them to dst. +// When a key in src is already present in dst, +// the value in dst will be overwritten by the value associated +// with the key in src. +func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) { + for k, v := range src { + dst[k] = v + } +} + +// DeleteFunc deletes any key/value pairs from m for which del returns true. +func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) { + for k, v := range m { + if del(k, v) { + delete(m, k) + } + } +} diff --git a/go/src/maps/maps_test.go b/go/src/maps/maps_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c8ee3cd0311f5ffe98a693ccb849ec50974eb77b --- /dev/null +++ b/go/src/maps/maps_test.go @@ -0,0 +1,242 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package maps + +import ( + "math" + "strconv" + "testing" +) + +var m1 = map[int]int{1: 2, 2: 4, 4: 8, 8: 16} +var m2 = map[int]string{1: "2", 2: "4", 4: "8", 8: "16"} + +func TestEqual(t *testing.T) { + if !Equal(m1, m1) { + t.Errorf("Equal(%v, %v) = false, want true", m1, m1) + } + if Equal(m1, (map[int]int)(nil)) { + t.Errorf("Equal(%v, nil) = true, want false", m1) + } + if Equal((map[int]int)(nil), m1) { + t.Errorf("Equal(nil, %v) = true, want false", m1) + } + if !Equal[map[int]int, map[int]int](nil, nil) { + t.Error("Equal(nil, nil) = false, want true") + } + if ms := map[int]int{1: 2}; Equal(m1, ms) { + t.Errorf("Equal(%v, %v) = true, want false", m1, ms) + } + + // Comparing NaN for equality is expected to fail. + mf := map[int]float64{1: 0, 2: math.NaN()} + if Equal(mf, mf) { + t.Errorf("Equal(%v, %v) = true, want false", mf, mf) + } +} + +// equal is simply ==. +func equal[T comparable](v1, v2 T) bool { + return v1 == v2 +} + +// equalNaN is like == except that all NaNs are equal. +func equalNaN[T comparable](v1, v2 T) bool { + isNaN := func(f T) bool { return f != f } + return v1 == v2 || (isNaN(v1) && isNaN(v2)) +} + +// equalIntStr compares ints and strings. +func equalIntStr(v1 int, v2 string) bool { + return strconv.Itoa(v1) == v2 +} + +func TestEqualFunc(t *testing.T) { + if !EqualFunc(m1, m1, equal[int]) { + t.Errorf("EqualFunc(%v, %v, equal) = false, want true", m1, m1) + } + if EqualFunc(m1, (map[int]int)(nil), equal[int]) { + t.Errorf("EqualFunc(%v, nil, equal) = true, want false", m1) + } + if EqualFunc((map[int]int)(nil), m1, equal[int]) { + t.Errorf("EqualFunc(nil, %v, equal) = true, want false", m1) + } + if !EqualFunc[map[int]int, map[int]int](nil, nil, equal[int]) { + t.Error("EqualFunc(nil, nil, equal) = false, want true") + } + if ms := map[int]int{1: 2}; EqualFunc(m1, ms, equal[int]) { + t.Errorf("EqualFunc(%v, %v, equal) = true, want false", m1, ms) + } + + // Comparing NaN for equality is expected to fail. + mf := map[int]float64{1: 0, 2: math.NaN()} + if EqualFunc(mf, mf, equal[float64]) { + t.Errorf("EqualFunc(%v, %v, equal) = true, want false", mf, mf) + } + // But it should succeed using equalNaN. + if !EqualFunc(mf, mf, equalNaN[float64]) { + t.Errorf("EqualFunc(%v, %v, equalNaN) = false, want true", mf, mf) + } + + if !EqualFunc(m1, m2, equalIntStr) { + t.Errorf("EqualFunc(%v, %v, equalIntStr) = false, want true", m1, m2) + } +} + +func TestClone(t *testing.T) { + mc := Clone(m1) + if !Equal(mc, m1) { + t.Errorf("Clone(%v) = %v, want %v", m1, mc, m1) + } + mc[16] = 32 + if Equal(mc, m1) { + t.Errorf("Equal(%v, %v) = true, want false", mc, m1) + } +} + +func TestCloneNil(t *testing.T) { + var m1 map[string]int + mc := Clone(m1) + if mc != nil { + t.Errorf("Clone(%v) = %v, want %v", m1, mc, m1) + } +} + +func TestCopy(t *testing.T) { + mc := Clone(m1) + Copy(mc, mc) + if !Equal(mc, m1) { + t.Errorf("Copy(%v, %v) = %v, want %v", m1, m1, mc, m1) + } + Copy(mc, map[int]int{16: 32}) + want := map[int]int{1: 2, 2: 4, 4: 8, 8: 16, 16: 32} + if !Equal(mc, want) { + t.Errorf("Copy result = %v, want %v", mc, want) + } + + type M1 map[int]bool + type M2 map[int]bool + Copy(make(M1), make(M2)) +} + +func TestDeleteFunc(t *testing.T) { + mc := Clone(m1) + DeleteFunc(mc, func(int, int) bool { return false }) + if !Equal(mc, m1) { + t.Errorf("DeleteFunc(%v, true) = %v, want %v", m1, mc, m1) + } + DeleteFunc(mc, func(k, v int) bool { return k > 3 }) + want := map[int]int{1: 2, 2: 4} + if !Equal(mc, want) { + t.Errorf("DeleteFunc result = %v, want %v", mc, want) + } +} + +var n map[int]int + +func BenchmarkMapClone(b *testing.B) { + var m = make(map[int]int) + for i := 0; i < 1000000; i++ { + m[i] = i + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + n = Clone(m) + } +} + +func TestCloneWithDelete(t *testing.T) { + var m = make(map[int]int) + for i := 0; i < 32; i++ { + m[i] = i + } + for i := 8; i < 32; i++ { + delete(m, i) + } + m2 := Clone(m) + if len(m2) != 8 { + t.Errorf("len2(m2) = %d, want %d", len(m2), 8) + } + for i := 0; i < 8; i++ { + if m2[i] != m[i] { + t.Errorf("m2[%d] = %d, want %d", i, m2[i], m[i]) + } + } +} + +func TestCloneWithMapAssign(t *testing.T) { + var m = make(map[int]int) + const N = 25 + for i := 0; i < N; i++ { + m[i] = i + } + m2 := Clone(m) + if len(m2) != N { + t.Errorf("len2(m2) = %d, want %d", len(m2), N) + } + for i := 0; i < N; i++ { + if m2[i] != m[i] { + t.Errorf("m2[%d] = %d, want %d", i, m2[i], m[i]) + } + } +} + +func TestCloneLarge(t *testing.T) { + // See issue 64474. + type K [17]float64 // > 128 bytes + type V [17]float64 + + var zero float64 + negZero := -zero + + for tst := 0; tst < 3; tst++ { + // Initialize m with a key and value. + m := map[K]V{} + var k1 K + var v1 V + m[k1] = v1 + + switch tst { + case 0: // nothing, just a 1-entry map + case 1: + // Add more entries to make it 2 buckets + // 1 entry already + // 7 more fill up 1 bucket + // 1 more to grow to 2 buckets + for i := 0; i < 7+1; i++ { + m[K{float64(i) + 1}] = V{} + } + case 2: + // Capture the map mid-grow + // 1 entry already + // 7 more fill up 1 bucket + // 5 more (13 total) fill up 2 buckets + // 13 more (26 total) fill up 4 buckets + // 1 more to start the 4->8 bucket grow + for i := 0; i < 7+5+13+1; i++ { + m[K{float64(i) + 1}] = V{} + } + } + + // Clone m, which should freeze the map's contents. + c := Clone(m) + + // Update m with new key and value. + k2, v2 := k1, v1 + k2[0] = negZero + v2[0] = 1.0 + m[k2] = v2 + + // Make sure c still has its old key and value. + for k, v := range c { + if math.Signbit(k[0]) { + t.Errorf("tst%d: sign bit of key changed; got %v want %v", tst, k, k1) + } + if v != v1 { + t.Errorf("tst%d: value changed; got %v want %v", tst, v, v1) + } + } + } +} diff --git a/go/src/math/abs.go b/go/src/math/abs.go new file mode 100644 index 0000000000000000000000000000000000000000..08be14548dd778c37411864ad119e859e8855151 --- /dev/null +++ b/go/src/math/abs.go @@ -0,0 +1,15 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Abs returns the absolute value of x. +// +// Special cases are: +// +// Abs(±Inf) = +Inf +// Abs(NaN) = NaN +func Abs(x float64) float64 { + return Float64frombits(Float64bits(x) &^ (1 << 63)) +} diff --git a/go/src/math/acos_s390x.s b/go/src/math/acos_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..4431b99e1cbd7e2e41f21ee69e1ff3db712821d6 --- /dev/null +++ b/go/src/math/acos_s390x.s @@ -0,0 +1,144 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·acosrodataL13<> + 0(SB)/8, $0.314159265358979323E+01 //pi +DATA ·acosrodataL13<> + 8(SB)/8, $-0.0 +DATA ·acosrodataL13<> + 16(SB)/8, $0x7ff8000000000000 //Nan +DATA ·acosrodataL13<> + 24(SB)/8, $-1.0 +DATA ·acosrodataL13<> + 32(SB)/8, $1.0 +DATA ·acosrodataL13<> + 40(SB)/8, $0.166666666666651626E+00 +DATA ·acosrodataL13<> + 48(SB)/8, $0.750000000042621169E-01 +DATA ·acosrodataL13<> + 56(SB)/8, $0.446428567178116477E-01 +DATA ·acosrodataL13<> + 64(SB)/8, $0.303819660378071894E-01 +DATA ·acosrodataL13<> + 72(SB)/8, $0.223715011892010405E-01 +DATA ·acosrodataL13<> + 80(SB)/8, $0.173659424522364952E-01 +DATA ·acosrodataL13<> + 88(SB)/8, $0.137810186504372266E-01 +DATA ·acosrodataL13<> + 96(SB)/8, $0.134066870961173521E-01 +DATA ·acosrodataL13<> + 104(SB)/8, $-.412335502831898721E-02 +DATA ·acosrodataL13<> + 112(SB)/8, $0.867383739532082719E-01 +DATA ·acosrodataL13<> + 120(SB)/8, $-.328765950607171649E+00 +DATA ·acosrodataL13<> + 128(SB)/8, $0.110401073869414626E+01 +DATA ·acosrodataL13<> + 136(SB)/8, $-.270694366992537307E+01 +DATA ·acosrodataL13<> + 144(SB)/8, $0.500196500770928669E+01 +DATA ·acosrodataL13<> + 152(SB)/8, $-.665866959108585165E+01 +DATA ·acosrodataL13<> + 160(SB)/8, $-.344895269334086578E+01 +DATA ·acosrodataL13<> + 168(SB)/8, $0.927437952918301659E+00 +DATA ·acosrodataL13<> + 176(SB)/8, $0.610487478874645653E+01 +DATA ·acosrodataL13<> + 184(SB)/8, $0.157079632679489656e+01 +DATA ·acosrodataL13<> + 192(SB)/8, $0.0 +GLOBL ·acosrodataL13<> + 0(SB), RODATA, $200 + +// Acos returns the arccosine, in radians, of the argument. +// +// Special case is: +// Acos(x) = NaN if x < -1 or x > 1 +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·acosAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·acosrodataL13<>+0(SB), R9 + LGDR F0, R12 + FMOVD F0, F10 + SRAD $32, R12 + WORD $0xC0293FE6 //iilf %r2,1072079005 + BYTE $0xA0 + BYTE $0x9D + WORD $0xB917001C //llgtr %r1,%r12 + CMPW R1,R2 + BGT L2 + FMOVD 192(R9), F8 + FMADD F0, F0, F8 + FMOVD 184(R9), F1 +L3: + WFMDB V8, V8, V2 + FMOVD 176(R9), F6 + FMOVD 168(R9), F0 + FMOVD 160(R9), F4 + WFMADB V2, V0, V6, V0 + FMOVD 152(R9), F6 + WFMADB V2, V4, V6, V4 + FMOVD 144(R9), F6 + WFMADB V2, V0, V6, V0 + FMOVD 136(R9), F6 + WFMADB V2, V4, V6, V4 + FMOVD 128(R9), F6 + WFMADB V2, V0, V6, V0 + FMOVD 120(R9), F6 + WFMADB V2, V4, V6, V4 + FMOVD 112(R9), F6 + WFMADB V2, V0, V6, V0 + FMOVD 104(R9), F6 + WFMADB V2, V4, V6, V4 + FMOVD 96(R9), F6 + WFMADB V2, V0, V6, V0 + FMOVD 88(R9), F6 + WFMADB V2, V4, V6, V4 + FMOVD 80(R9), F6 + WFMADB V2, V0, V6, V0 + FMOVD 72(R9), F6 + WFMADB V2, V4, V6, V4 + FMOVD 64(R9), F6 + WFMADB V2, V0, V6, V0 + FMOVD 56(R9), F6 + WFMADB V2, V4, V6, V4 + FMOVD 48(R9), F6 + WFMADB V2, V0, V6, V0 + FMOVD 40(R9), F6 + WFMADB V2, V4, V6, V2 + FMOVD 192(R9), F4 + WFMADB V8, V0, V2, V0 + WFMADB V10, V8, V4, V8 + FMADD F0, F8, F10 + WFSDB V10, V1, V10 +L1: + FMOVD F10, ret+8(FP) + RET + +L2: + WORD $0xC0293FEF //iilf %r2,1072693247 + BYTE $0xFF + BYTE $0xFF + CMPW R1, R2 + BLE L12 +L4: + WORD $0xED009020 //cdb %f0,.L34-.L13(%r9) + BYTE $0x00 + BYTE $0x19 + BEQ L8 + WORD $0xED009018 //cdb %f0,.L35-.L13(%r9) + BYTE $0x00 + BYTE $0x19 + BEQ L9 + WFCEDBS V10, V10, V0 + BVS L1 + FMOVD 16(R9), F10 + BR L1 +L12: + FMOVD 24(R9), F0 + FMADD F10, F10, F0 + LCDBR F0, F8 + WORD $0xED009008 //cdb %f0,.L37-.L13(%r9) + BYTE $0x00 + BYTE $0x19 + FSQRT F8, F10 +L5: + MOVW R12, R4 + CMPBLE R4, $0, L7 + LCDBR F10, F10 + FMOVD $0, F1 + BR L3 +L9: + FMOVD 0(R9), F10 + BR L1 +L8: + FMOVD $0, F0 + FMOVD F0, ret+8(FP) + RET +L7: + FMOVD 0(R9), F1 + BR L3 diff --git a/go/src/math/acosh.go b/go/src/math/acosh.go new file mode 100644 index 0000000000000000000000000000000000000000..a85d003d3eabe768995aaa7a6976b155dbfe6836 --- /dev/null +++ b/go/src/math/acosh.go @@ -0,0 +1,65 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/e_acosh.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// __ieee754_acosh(x) +// Method : +// Based on +// acosh(x) = log [ x + sqrt(x*x-1) ] +// we have +// acosh(x) := log(x)+ln2, if x is large; else +// acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else +// acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. +// +// Special cases: +// acosh(x) is NaN with signal if x<1. +// acosh(NaN) is NaN without signal. +// + +// Acosh returns the inverse hyperbolic cosine of x. +// +// Special cases are: +// +// Acosh(+Inf) = +Inf +// Acosh(x) = NaN if x < 1 +// Acosh(NaN) = NaN +func Acosh(x float64) float64 { + if haveArchAcosh { + return archAcosh(x) + } + return acosh(x) +} + +func acosh(x float64) float64 { + const Large = 1 << 28 // 2**28 + // first case is special case + switch { + case x < 1 || IsNaN(x): + return NaN() + case x == 1: + return 0 + case x >= Large: + return Log(x) + Ln2 // x > 2**28 + case x > 2: + return Log(2*x - 1/(x+Sqrt(x*x-1))) // 2**28 > x > 2 + } + t := x - 1 + return Log1p(t + Sqrt(2*t+t*t)) // 2 >= x > 1 +} diff --git a/go/src/math/acosh_s390x.s b/go/src/math/acosh_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..9294c48e6b92b3e8669d076ad4881bc7fa98aa82 --- /dev/null +++ b/go/src/math/acosh_s390x.s @@ -0,0 +1,158 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·acoshrodataL11<> + 0(SB)/8, $-1.0 +DATA ·acoshrodataL11<> + 8(SB)/8, $.41375273347623353626 +DATA ·acoshrodataL11<> + 16(SB)/8, $.51487302528619766235E+04 +DATA ·acoshrodataL11<> + 24(SB)/8, $-1.67526912689208984375 +DATA ·acoshrodataL11<> + 32(SB)/8, $0.181818181818181826E+00 +DATA ·acoshrodataL11<> + 40(SB)/8, $-.165289256198351540E-01 +DATA ·acoshrodataL11<> + 48(SB)/8, $0.200350613573012186E-02 +DATA ·acoshrodataL11<> + 56(SB)/8, $-.273205381970859341E-03 +DATA ·acoshrodataL11<> + 64(SB)/8, $0.397389654305194527E-04 +DATA ·acoshrodataL11<> + 72(SB)/8, $0.938370938292558173E-06 +DATA ·acoshrodataL11<> + 80(SB)/8, $-.602107458843052029E-05 +DATA ·acoshrodataL11<> + 88(SB)/8, $0.212881813645679599E-07 +DATA ·acoshrodataL11<> + 96(SB)/8, $-.148682720127920854E-06 +DATA ·acoshrodataL11<> + 104(SB)/8, $-5.5 +DATA ·acoshrodataL11<> + 112(SB)/8, $0x7ff8000000000000 //Nan +GLOBL ·acoshrodataL11<> + 0(SB), RODATA, $120 + +// Table of log correction terms +DATA ·acoshtab2068<> + 0(SB)/8, $0.585235384085551248E-01 +DATA ·acoshtab2068<> + 8(SB)/8, $0.412206153771168640E-01 +DATA ·acoshtab2068<> + 16(SB)/8, $0.273839003221648339E-01 +DATA ·acoshtab2068<> + 24(SB)/8, $0.166383778368856480E-01 +DATA ·acoshtab2068<> + 32(SB)/8, $0.866678223433169637E-02 +DATA ·acoshtab2068<> + 40(SB)/8, $0.319831684989627514E-02 +DATA ·acoshtab2068<> + 48(SB)/8, $0.0 +DATA ·acoshtab2068<> + 56(SB)/8, $-.113006378583725549E-02 +DATA ·acoshtab2068<> + 64(SB)/8, $-.367979419636602491E-03 +DATA ·acoshtab2068<> + 72(SB)/8, $0.213172484510484979E-02 +DATA ·acoshtab2068<> + 80(SB)/8, $0.623271047682013536E-02 +DATA ·acoshtab2068<> + 88(SB)/8, $0.118140812789696885E-01 +DATA ·acoshtab2068<> + 96(SB)/8, $0.187681358930914206E-01 +DATA ·acoshtab2068<> + 104(SB)/8, $0.269985148668178992E-01 +DATA ·acoshtab2068<> + 112(SB)/8, $0.364186619761331328E-01 +DATA ·acoshtab2068<> + 120(SB)/8, $0.469505379381388441E-01 +GLOBL ·acoshtab2068<> + 0(SB), RODATA, $128 + +// Acosh returns the inverse hyperbolic cosine of the argument. +// +// Special cases are: +// Acosh(+Inf) = +Inf +// Acosh(x) = NaN if x < 1 +// Acosh(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·acoshAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·acoshrodataL11<>+0(SB), R9 + LGDR F0, R1 + WORD $0xC0295FEF //iilf %r2,1609564159 + BYTE $0xFF + BYTE $0xFF + SRAD $32, R1 + CMPW R1, R2 + BGT L2 + WORD $0xC0293FEF //iilf %r2,1072693247 + BYTE $0xFF + BYTE $0xFF + CMPW R1, R2 + BGT L10 +L3: + WFCEDBS V0, V0, V2 + BVS L1 + FMOVD 112(R9), F0 +L1: + FMOVD F0, ret+8(FP) + RET +L2: + WORD $0xC0297FEF //iilf %r2,2146435071 + BYTE $0xFF + BYTE $0xFF + MOVW R1, R6 + MOVW R2, R7 + CMPBGT R6, R7, L1 + FMOVD F0, F8 + FMOVD $0, F0 + WFADB V0, V8, V0 + WORD $0xC0398006 //iilf %r3,2147909631 + BYTE $0x7F + BYTE $0xFF + LGDR F0, R5 + SRAD $32, R5 + MOVH $0x0, R1 + SUBW R5, R3 + FMOVD $0, F10 + RISBGZ $32, $47, $0, R3, R4 + RISBGZ $57, $60, $51, R3, R3 + BYTE $0x18 //lr %r2,%r4 + BYTE $0x24 + RISBGN $0, $31, $32, R4, R1 + SUBW $0x100000, R2 + SRAW $8, R2, R2 + ORW $0x45000000, R2 +L5: + LDGR R1, F0 + FMOVD 104(R9), F2 + FMADD F8, F0, F2 + FMOVD 96(R9), F4 + WFMADB V10, V0, V2, V0 + FMOVD 88(R9), F6 + FMOVD 80(R9), F2 + WFMADB V0, V6, V4, V6 + FMOVD 72(R9), F1 + WFMDB V0, V0, V4 + WFMADB V0, V1, V2, V1 + FMOVD 64(R9), F2 + WFMADB V6, V4, V1, V6 + FMOVD 56(R9), F1 + RISBGZ $57, $60, $0, R3, R3 + WFMADB V0, V2, V1, V2 + FMOVD 48(R9), F1 + WFMADB V4, V6, V2, V6 + FMOVD 40(R9), F2 + WFMADB V0, V1, V2, V1 + VLVGF $0, R2, V2 + WFMADB V4, V6, V1, V4 + LDEBR F2, F2 + FMOVD 32(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 24(R9), F1 + FMOVD 16(R9), F6 + MOVD $·acoshtab2068<>+0(SB), R1 + WFMADB V2, V1, V6, V2 + FMOVD 0(R3)(R1*1), F3 + WFMADB V0, V4, V3, V0 + FMOVD 8(R9), F4 + FMADD F4, F2, F0 + FMOVD F0, ret+8(FP) + RET +L10: + FMOVD F0, F8 + FMOVD 0(R9), F0 + FMADD F8, F8, F0 + LTDBR F0, F0 + FSQRT F0, F10 +L4: + WFADB V10, V8, V0 + WORD $0xC0398006 //iilf %r3,2147909631 + BYTE $0x7F + BYTE $0xFF + LGDR F0, R5 + SRAD $32, R5 + MOVH $0x0, R1 + SUBW R5, R3 + SRAW $8, R3, R2 + RISBGZ $32, $47, $0, R3, R4 + ANDW $0xFFFFFF00, R2 + RISBGZ $57, $60, $51, R3, R3 + ORW $0x45000000, R2 + RISBGN $0, $31, $32, R4, R1 + BR L5 diff --git a/go/src/math/all_test.go b/go/src/math/all_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4e5f4517629dd83565e18713c9d65bdca8597c04 --- /dev/null +++ b/go/src/math/all_test.go @@ -0,0 +1,3960 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math_test + +import ( + "fmt" + . "math" + "testing" + "unsafe" +) + +var vf = []float64{ + 4.9790119248836735e+00, + 7.7388724745781045e+00, + -2.7688005719200159e-01, + -5.0106036182710749e+00, + 9.6362937071984173e+00, + 2.9263772392439646e+00, + 5.2290834314593066e+00, + 2.7279399104360102e+00, + 1.8253080916808550e+00, + -8.6859247685756013e+00, +} + +// The expected results below were computed by the high precision calculators +// at https://keisan.casio.com/. More exact input values (array vf[], above) +// were obtained by printing them with "%.26f". The answers were calculated +// to 26 digits (by using the "Digit number" drop-down control of each +// calculator). +var acos = []float64{ + 1.0496193546107222142571536e+00, + 6.8584012813664425171660692e-01, + 1.5984878714577160325521819e+00, + 2.0956199361475859327461799e+00, + 2.7053008467824138592616927e-01, + 1.2738121680361776018155625e+00, + 1.0205369421140629186287407e+00, + 1.2945003481781246062157835e+00, + 1.3872364345374451433846657e+00, + 2.6231510803970463967294145e+00, +} +var acosh = []float64{ + 2.4743347004159012494457618e+00, + 2.8576385344292769649802701e+00, + 7.2796961502981066190593175e-01, + 2.4796794418831451156471977e+00, + 3.0552020742306061857212962e+00, + 2.044238592688586588942468e+00, + 2.5158701513104513595766636e+00, + 1.99050839282411638174299e+00, + 1.6988625798424034227205445e+00, + 2.9611454842470387925531875e+00, +} +var asin = []float64{ + 5.2117697218417440497416805e-01, + 8.8495619865825236751471477e-01, + -02.769154466281941332086016e-02, + -5.2482360935268931351485822e-01, + 1.3002662421166552333051524e+00, + 2.9698415875871901741575922e-01, + 5.5025938468083370060258102e-01, + 2.7629597861677201301553823e-01, + 1.83559892257451475846656e-01, + -1.0523547536021497774980928e+00, +} +var asinh = []float64{ + 2.3083139124923523427628243e+00, + 2.743551594301593620039021e+00, + -2.7345908534880091229413487e-01, + -2.3145157644718338650499085e+00, + 2.9613652154015058521951083e+00, + 1.7949041616585821933067568e+00, + 2.3564032905983506405561554e+00, + 1.7287118790768438878045346e+00, + 1.3626658083714826013073193e+00, + -2.8581483626513914445234004e+00, +} +var atan = []float64{ + 1.372590262129621651920085e+00, + 1.442290609645298083020664e+00, + -2.7011324359471758245192595e-01, + -1.3738077684543379452781531e+00, + 1.4673921193587666049154681e+00, + 1.2415173565870168649117764e+00, + 1.3818396865615168979966498e+00, + 1.2194305844639670701091426e+00, + 1.0696031952318783760193244e+00, + -1.4561721938838084990898679e+00, +} +var atanh = []float64{ + 5.4651163712251938116878204e-01, + 1.0299474112843111224914709e+00, + -2.7695084420740135145234906e-02, + -5.5072096119207195480202529e-01, + 1.9943940993171843235906642e+00, + 3.01448604578089708203017e-01, + 5.8033427206942188834370595e-01, + 2.7987997499441511013958297e-01, + 1.8459947964298794318714228e-01, + -1.3273186910532645867272502e+00, +} +var atan2 = []float64{ + 1.1088291730037004444527075e+00, + 9.1218183188715804018797795e-01, + 1.5984772603216203736068915e+00, + 2.0352918654092086637227327e+00, + 8.0391819139044720267356014e-01, + 1.2861075249894661588866752e+00, + 1.0889904479131695712182587e+00, + 1.3044821793397925293797357e+00, + 1.3902530903455392306872261e+00, + 2.2859857424479142655411058e+00, +} +var cbrt = []float64{ + 1.7075799841925094446722675e+00, + 1.9779982212970353936691498e+00, + -6.5177429017779910853339447e-01, + -1.7111838886544019873338113e+00, + 2.1279920909827937423960472e+00, + 1.4303536770460741452312367e+00, + 1.7357021059106154902341052e+00, + 1.3972633462554328350552916e+00, + 1.2221149580905388454977636e+00, + -2.0556003730500069110343596e+00, +} +var ceil = []float64{ + 5.0000000000000000e+00, + 8.0000000000000000e+00, + Copysign(0, -1), + -5.0000000000000000e+00, + 1.0000000000000000e+01, + 3.0000000000000000e+00, + 6.0000000000000000e+00, + 3.0000000000000000e+00, + 2.0000000000000000e+00, + -8.0000000000000000e+00, +} +var copysign = []float64{ + -4.9790119248836735e+00, + -7.7388724745781045e+00, + -2.7688005719200159e-01, + -5.0106036182710749e+00, + -9.6362937071984173e+00, + -2.9263772392439646e+00, + -5.2290834314593066e+00, + -2.7279399104360102e+00, + -1.8253080916808550e+00, + -8.6859247685756013e+00, +} +var cos = []float64{ + 2.634752140995199110787593e-01, + 1.148551260848219865642039e-01, + 9.6191297325640768154550453e-01, + 2.938141150061714816890637e-01, + -9.777138189897924126294461e-01, + -9.7693041344303219127199518e-01, + 4.940088096948647263961162e-01, + -9.1565869021018925545016502e-01, + -2.517729313893103197176091e-01, + -7.39241351595676573201918e-01, +} + +// Results for 100000 * Pi + vf[i] +var cosLarge = []float64{ + 2.634752141185559426744e-01, + 1.14855126055543100712e-01, + 9.61912973266488928113e-01, + 2.9381411499556122552e-01, + -9.777138189880161924641e-01, + -9.76930413445147608049e-01, + 4.940088097314976789841e-01, + -9.15658690217517835002e-01, + -2.51772931436786954751e-01, + -7.3924135157173099849e-01, +} + +var cosh = []float64{ + 7.2668796942212842775517446e+01, + 1.1479413465659254502011135e+03, + 1.0385767908766418550935495e+00, + 7.5000957789658051428857788e+01, + 7.655246669605357888468613e+03, + 9.3567491758321272072888257e+00, + 9.331351599270605471131735e+01, + 7.6833430994624643209296404e+00, + 3.1829371625150718153881164e+00, + 2.9595059261916188501640911e+03, +} +var erf = []float64{ + 5.1865354817738701906913566e-01, + 7.2623875834137295116929844e-01, + -3.123458688281309990629839e-02, + -5.2143121110253302920437013e-01, + 8.2704742671312902508629582e-01, + 3.2101767558376376743993945e-01, + 5.403990312223245516066252e-01, + 3.0034702916738588551174831e-01, + 2.0369924417882241241559589e-01, + -7.8069386968009226729944677e-01, +} +var erfc = []float64{ + 4.8134645182261298093086434e-01, + 2.7376124165862704883070156e-01, + 1.0312345868828130999062984e+00, + 1.5214312111025330292043701e+00, + 1.7295257328687097491370418e-01, + 6.7898232441623623256006055e-01, + 4.596009687776754483933748e-01, + 6.9965297083261411448825169e-01, + 7.9630075582117758758440411e-01, + 1.7806938696800922672994468e+00, +} +var erfinv = []float64{ + 4.746037673358033586786350696e-01, + 8.559054432692110956388764172e-01, + -2.45427830571707336251331946e-02, + -4.78116683518973366268905506e-01, + 1.479804430319470983648120853e+00, + 2.654485787128896161882650211e-01, + 5.027444534221520197823192493e-01, + 2.466703532707627818954585670e-01, + 1.632011465103005426240343116e-01, + -1.06672334642196900710000389e+00, +} +var exp = []float64{ + 1.4533071302642137507696589e+02, + 2.2958822575694449002537581e+03, + 7.5814542574851666582042306e-01, + 6.6668778421791005061482264e-03, + 1.5310493273896033740861206e+04, + 1.8659907517999328638667732e+01, + 1.8662167355098714543942057e+02, + 1.5301332413189378961665788e+01, + 6.2047063430646876349125085e+00, + 1.6894712385826521111610438e-04, +} +var expm1 = []float64{ + 5.105047796122957327384770212e-02, + 8.046199708567344080562675439e-02, + -2.764970978891639815187418703e-03, + -4.8871434888875355394330300273e-02, + 1.0115864277221467777117227494e-01, + 2.969616407795910726014621657e-02, + 5.368214487944892300914037972e-02, + 2.765488851131274068067445335e-02, + 1.842068661871398836913874273e-02, + -8.3193870863553801814961137573e-02, +} +var expm1Large = []float64{ + 4.2031418113550844e+21, + 4.0690789717473863e+33, + -0.9372627915981363e+00, + -1.0, + 7.077694784145933e+41, + 5.117936223839153e+12, + 5.124137759001189e+22, + 7.03546003972584e+11, + 8.456921800389698e+07, + -1.0, +} +var exp2 = []float64{ + 3.1537839463286288034313104e+01, + 2.1361549283756232296144849e+02, + 8.2537402562185562902577219e-01, + 3.1021158628740294833424229e-02, + 7.9581744110252191462569661e+02, + 7.6019905892596359262696423e+00, + 3.7506882048388096973183084e+01, + 6.6250893439173561733216375e+00, + 3.5438267900243941544605339e+00, + 2.4281533133513300984289196e-03, +} +var fabs = []float64{ + 4.9790119248836735e+00, + 7.7388724745781045e+00, + 2.7688005719200159e-01, + 5.0106036182710749e+00, + 9.6362937071984173e+00, + 2.9263772392439646e+00, + 5.2290834314593066e+00, + 2.7279399104360102e+00, + 1.8253080916808550e+00, + 8.6859247685756013e+00, +} +var fdim = []float64{ + 4.9790119248836735e+00, + 7.7388724745781045e+00, + 0.0000000000000000e+00, + 0.0000000000000000e+00, + 9.6362937071984173e+00, + 2.9263772392439646e+00, + 5.2290834314593066e+00, + 2.7279399104360102e+00, + 1.8253080916808550e+00, + 0.0000000000000000e+00, +} +var floor = []float64{ + 4.0000000000000000e+00, + 7.0000000000000000e+00, + -1.0000000000000000e+00, + -6.0000000000000000e+00, + 9.0000000000000000e+00, + 2.0000000000000000e+00, + 5.0000000000000000e+00, + 2.0000000000000000e+00, + 1.0000000000000000e+00, + -9.0000000000000000e+00, +} +var fmod = []float64{ + 4.197615023265299782906368e-02, + 2.261127525421895434476482e+00, + 3.231794108794261433104108e-02, + 4.989396381728925078391512e+00, + 3.637062928015826201999516e-01, + 1.220868282268106064236690e+00, + 4.770916568540693347699744e+00, + 1.816180268691969246219742e+00, + 8.734595415957246977711748e-01, + 1.314075231424398637614104e+00, +} + +type fi struct { + f float64 + i int +} + +var frexp = []fi{ + {6.2237649061045918750e-01, 3}, + {9.6735905932226306250e-01, 3}, + {-5.5376011438400318000e-01, -1}, + {-6.2632545228388436250e-01, 3}, + {6.02268356699901081250e-01, 4}, + {7.3159430981099115000e-01, 2}, + {6.5363542893241332500e-01, 3}, + {6.8198497760900255000e-01, 2}, + {9.1265404584042750000e-01, 1}, + {-5.4287029803597508250e-01, 4}, +} +var gamma = []float64{ + 2.3254348370739963835386613898e+01, + 2.991153837155317076427529816e+03, + -4.561154336726758060575129109e+00, + 7.719403468842639065959210984e-01, + 1.6111876618855418534325755566e+05, + 1.8706575145216421164173224946e+00, + 3.4082787447257502836734201635e+01, + 1.579733951448952054898583387e+00, + 9.3834586598354592860187267089e-01, + -2.093995902923148389186189429e-05, +} +var j0 = []float64{ + -1.8444682230601672018219338e-01, + 2.27353668906331975435892e-01, + 9.809259936157051116270273e-01, + -1.741170131426226587841181e-01, + -2.1389448451144143352039069e-01, + -2.340905848928038763337414e-01, + -1.0029099691890912094586326e-01, + -1.5466726714884328135358907e-01, + 3.252650187653420388714693e-01, + -8.72218484409407250005360235e-03, +} +var j1 = []float64{ + -3.251526395295203422162967e-01, + 1.893581711430515718062564e-01, + -1.3711761352467242914491514e-01, + 3.287486536269617297529617e-01, + 1.3133899188830978473849215e-01, + 3.660243417832986825301766e-01, + -3.4436769271848174665420672e-01, + 4.329481396640773768835036e-01, + 5.8181350531954794639333955e-01, + -2.7030574577733036112996607e-01, +} +var j2 = []float64{ + 5.3837518920137802565192769e-02, + -1.7841678003393207281244667e-01, + 9.521746934916464142495821e-03, + 4.28958355470987397983072e-02, + 2.4115371837854494725492872e-01, + 4.842458532394520316844449e-01, + -3.142145220618633390125946e-02, + 4.720849184745124761189957e-01, + 3.122312022520957042957497e-01, + 7.096213118930231185707277e-02, +} +var jM3 = []float64{ + -3.684042080996403091021151e-01, + 2.8157665936340887268092661e-01, + 4.401005480841948348343589e-04, + 3.629926999056814081597135e-01, + 3.123672198825455192489266e-02, + -2.958805510589623607540455e-01, + -3.2033177696533233403289416e-01, + -2.592737332129663376736604e-01, + -1.0241334641061485092351251e-01, + -2.3762660886100206491674503e-01, +} +var lgamma = []fi{ + {3.146492141244545774319734e+00, 1}, + {8.003414490659126375852113e+00, 1}, + {1.517575735509779707488106e+00, -1}, + {-2.588480028182145853558748e-01, 1}, + {1.1989897050205555002007985e+01, 1}, + {6.262899811091257519386906e-01, 1}, + {3.5287924899091566764846037e+00, 1}, + {4.5725644770161182299423372e-01, 1}, + {-6.363667087767961257654854e-02, 1}, + {-1.077385130910300066425564e+01, -1}, +} +var log = []float64{ + 1.605231462693062999102599e+00, + 2.0462560018708770653153909e+00, + -1.2841708730962657801275038e+00, + 1.6115563905281545116286206e+00, + 2.2655365644872016636317461e+00, + 1.0737652208918379856272735e+00, + 1.6542360106073546632707956e+00, + 1.0035467127723465801264487e+00, + 6.0174879014578057187016475e-01, + 2.161703872847352815363655e+00, +} +var logb = []float64{ + 2.0000000000000000e+00, + 2.0000000000000000e+00, + -2.0000000000000000e+00, + 2.0000000000000000e+00, + 3.0000000000000000e+00, + 1.0000000000000000e+00, + 2.0000000000000000e+00, + 1.0000000000000000e+00, + 0.0000000000000000e+00, + 3.0000000000000000e+00, +} +var log10 = []float64{ + 6.9714316642508290997617083e-01, + 8.886776901739320576279124e-01, + -5.5770832400658929815908236e-01, + 6.998900476822994346229723e-01, + 9.8391002850684232013281033e-01, + 4.6633031029295153334285302e-01, + 7.1842557117242328821552533e-01, + 4.3583479968917773161304553e-01, + 2.6133617905227038228626834e-01, + 9.3881606348649405716214241e-01, +} +var log1p = []float64{ + 4.8590257759797794104158205e-02, + 7.4540265965225865330849141e-02, + -2.7726407903942672823234024e-03, + -5.1404917651627649094953380e-02, + 9.1998280672258624681335010e-02, + 2.8843762576593352865894824e-02, + 5.0969534581863707268992645e-02, + 2.6913947602193238458458594e-02, + 1.8088493239630770262045333e-02, + -9.0865245631588989681559268e-02, +} +var log2 = []float64{ + 2.3158594707062190618898251e+00, + 2.9521233862883917703341018e+00, + -1.8526669502700329984917062e+00, + 2.3249844127278861543568029e+00, + 3.268478366538305087466309e+00, + 1.5491157592596970278166492e+00, + 2.3865580889631732407886495e+00, + 1.447811865817085365540347e+00, + 8.6813999540425116282815557e-01, + 3.118679457227342224364709e+00, +} +var modf = [][2]float64{ + {4.0000000000000000e+00, 9.7901192488367350108546816e-01}, + {7.0000000000000000e+00, 7.3887247457810456552351752e-01}, + {Copysign(0, -1), -2.7688005719200159404635997e-01}, + {-5.0000000000000000e+00, -1.060361827107492160848778e-02}, + {9.0000000000000000e+00, 6.3629370719841737980004837e-01}, + {2.0000000000000000e+00, 9.2637723924396464525443662e-01}, + {5.0000000000000000e+00, 2.2908343145930665230025625e-01}, + {2.0000000000000000e+00, 7.2793991043601025126008608e-01}, + {1.0000000000000000e+00, 8.2530809168085506044576505e-01}, + {-8.0000000000000000e+00, -6.8592476857560136238589621e-01}, +} +var nextafter32 = []float32{ + 4.979012489318848e+00, + 7.738873004913330e+00, + -2.768800258636475e-01, + -5.010602951049805e+00, + 9.636294364929199e+00, + 2.926377534866333e+00, + 5.229084014892578e+00, + 2.727940082550049e+00, + 1.825308203697205e+00, + -8.685923576354980e+00, +} +var nextafter64 = []float64{ + 4.97901192488367438926388786e+00, + 7.73887247457810545370193722e+00, + -2.7688005719200153853520874e-01, + -5.01060361827107403343006808e+00, + 9.63629370719841915615688777e+00, + 2.92637723924396508934364647e+00, + 5.22908343145930754047867595e+00, + 2.72793991043601069534929593e+00, + 1.82530809168085528249036997e+00, + -8.68592476857559958602905681e+00, +} +var pow = []float64{ + 9.5282232631648411840742957e+04, + 5.4811599352999901232411871e+07, + 5.2859121715894396531132279e-01, + 9.7587991957286474464259698e-06, + 4.328064329346044846740467e+09, + 8.4406761805034547437659092e+02, + 1.6946633276191194947742146e+05, + 5.3449040147551939075312879e+02, + 6.688182138451414936380374e+01, + 2.0609869004248742886827439e-09, +} +var remainder = []float64{ + 4.197615023265299782906368e-02, + 2.261127525421895434476482e+00, + 3.231794108794261433104108e-02, + -2.120723654214984321697556e-02, + 3.637062928015826201999516e-01, + 1.220868282268106064236690e+00, + -4.581668629186133046005125e-01, + -9.117596417440410050403443e-01, + 8.734595415957246977711748e-01, + 1.314075231424398637614104e+00, +} +var round = []float64{ + 5, + 8, + Copysign(0, -1), + -5, + 10, + 3, + 5, + 3, + 2, + -9, +} +var signbit = []bool{ + false, + false, + true, + true, + false, + false, + false, + false, + false, + true, +} +var sin = []float64{ + -9.6466616586009283766724726e-01, + 9.9338225271646545763467022e-01, + -2.7335587039794393342449301e-01, + 9.5586257685042792878173752e-01, + -2.099421066779969164496634e-01, + 2.135578780799860532750616e-01, + -8.694568971167362743327708e-01, + 4.019566681155577786649878e-01, + 9.6778633541687993721617774e-01, + -6.734405869050344734943028e-01, +} + +// Results for 100000 * Pi + vf[i] +var sinLarge = []float64{ + -9.646661658548936063912e-01, + 9.933822527198506903752e-01, + -2.7335587036246899796e-01, + 9.55862576853689321268e-01, + -2.099421066862688873691e-01, + 2.13557878070308981163e-01, + -8.694568970959221300497e-01, + 4.01956668098863248917e-01, + 9.67786335404528727927e-01, + -6.7344058693131973066e-01, +} +var sinh = []float64{ + 7.2661916084208532301448439e+01, + 1.1479409110035194500526446e+03, + -2.8043136512812518927312641e-01, + -7.499429091181587232835164e+01, + 7.6552466042906758523925934e+03, + 9.3031583421672014313789064e+00, + 9.330815755828109072810322e+01, + 7.6179893137269146407361477e+00, + 3.021769180549615819524392e+00, + -2.95950575724449499189888e+03, +} +var sqrt = []float64{ + 2.2313699659365484748756904e+00, + 2.7818829009464263511285458e+00, + 5.2619393496314796848143251e-01, + 2.2384377628763938724244104e+00, + 3.1042380236055381099288487e+00, + 1.7106657298385224403917771e+00, + 2.286718922705479046148059e+00, + 1.6516476350711159636222979e+00, + 1.3510396336454586262419247e+00, + 2.9471892997524949215723329e+00, +} +var tan = []float64{ + -3.661316565040227801781974e+00, + 8.64900232648597589369854e+00, + -2.8417941955033612725238097e-01, + 3.253290185974728640827156e+00, + 2.147275640380293804770778e-01, + -2.18600910711067004921551e-01, + -1.760002817872367935518928e+00, + -4.389808914752818126249079e-01, + -3.843885560201130679995041e+00, + 9.10988793377685105753416e-01, +} + +// Results for 100000 * Pi + vf[i] +var tanLarge = []float64{ + -3.66131656475596512705e+00, + 8.6490023287202547927e+00, + -2.841794195104782406e-01, + 3.2532901861033120983e+00, + 2.14727564046880001365e-01, + -2.18600910700688062874e-01, + -1.760002817699722747043e+00, + -4.38980891453536115952e-01, + -3.84388555942723509071e+00, + 9.1098879344275101051e-01, +} +var tanh = []float64{ + 9.9990531206936338549262119e-01, + 9.9999962057085294197613294e-01, + -2.7001505097318677233756845e-01, + -9.9991110943061718603541401e-01, + 9.9999999146798465745022007e-01, + 9.9427249436125236705001048e-01, + 9.9994257600983138572705076e-01, + 9.9149409509772875982054701e-01, + 9.4936501296239685514466577e-01, + -9.9999994291374030946055701e-01, +} +var trunc = []float64{ + 4.0000000000000000e+00, + 7.0000000000000000e+00, + Copysign(0, -1), + -5.0000000000000000e+00, + 9.0000000000000000e+00, + 2.0000000000000000e+00, + 5.0000000000000000e+00, + 2.0000000000000000e+00, + 1.0000000000000000e+00, + -8.0000000000000000e+00, +} +var y0 = []float64{ + -3.053399153780788357534855e-01, + 1.7437227649515231515503649e-01, + -8.6221781263678836910392572e-01, + -3.100664880987498407872839e-01, + 1.422200649300982280645377e-01, + 4.000004067997901144239363e-01, + -3.3340749753099352392332536e-01, + 4.5399790746668954555205502e-01, + 4.8290004112497761007536522e-01, + 2.7036697826604756229601611e-01, +} +var y1 = []float64{ + 0.15494213737457922210218611, + -0.2165955142081145245075746, + -2.4644949631241895201032829, + 0.1442740489541836405154505, + 0.2215379960518984777080163, + 0.3038800915160754150565448, + 0.0691107642452362383808547, + 0.2380116417809914424860165, + -0.20849492979459761009678934, + 0.0242503179793232308250804, +} +var y2 = []float64{ + 0.3675780219390303613394936, + -0.23034826393250119879267257, + -16.939677983817727205631397, + 0.367653980523052152867791, + -0.0962401471767804440353136, + -0.1923169356184851105200523, + 0.35984072054267882391843766, + -0.2794987252299739821654982, + -0.7113490692587462579757954, + -0.2647831587821263302087457, +} +var yM3 = []float64{ + -0.14035984421094849100895341, + -0.097535139617792072703973, + 242.25775994555580176377379, + -0.1492267014802818619511046, + 0.26148702629155918694500469, + 0.56675383593895176530394248, + -0.206150264009006981070575, + 0.64784284687568332737963658, + 1.3503631555901938037008443, + 0.1461869756579956803341844, +} + +// arguments and expected results for special cases +var vfacosSC = []float64{ + -Pi, + 1, + Pi, + NaN(), +} +var acosSC = []float64{ + NaN(), + 0, + NaN(), + NaN(), +} + +var vfacoshSC = []float64{ + Inf(-1), + 0.5, + 1, + Inf(1), + NaN(), +} +var acoshSC = []float64{ + NaN(), + NaN(), + 0, + Inf(1), + NaN(), +} + +var vfasinSC = []float64{ + -Pi, + Copysign(0, -1), + 0, + Pi, + NaN(), +} +var asinSC = []float64{ + NaN(), + Copysign(0, -1), + 0, + NaN(), + NaN(), +} + +var vfasinhSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var asinhSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} + +var vfatanSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var atanSC = []float64{ + -Pi / 2, + Copysign(0, -1), + 0, + Pi / 2, + NaN(), +} + +var vfatanhSC = []float64{ + Inf(-1), + -Pi, + -1, + Copysign(0, -1), + 0, + 1, + Pi, + Inf(1), + NaN(), +} +var atanhSC = []float64{ + NaN(), + NaN(), + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), + NaN(), + NaN(), +} +var vfatan2SC = [][2]float64{ + {Inf(-1), Inf(-1)}, + {Inf(-1), -Pi}, + {Inf(-1), 0}, + {Inf(-1), +Pi}, + {Inf(-1), Inf(1)}, + {Inf(-1), NaN()}, + {-Pi, Inf(-1)}, + {-Pi, 0}, + {-Pi, Inf(1)}, + {-Pi, NaN()}, + {Copysign(0, -1), Inf(-1)}, + {Copysign(0, -1), -Pi}, + {Copysign(0, -1), Copysign(0, -1)}, + {Copysign(0, -1), 0}, + {Copysign(0, -1), +Pi}, + {Copysign(0, -1), Inf(1)}, + {Copysign(0, -1), NaN()}, + {0, Inf(-1)}, + {0, -Pi}, + {0, Copysign(0, -1)}, + {0, 0}, + {0, +Pi}, + {0, Inf(1)}, + {0, NaN()}, + {+Pi, Inf(-1)}, + {+Pi, 0}, + {+Pi, Inf(1)}, + {1.0, Inf(1)}, + {-1.0, Inf(1)}, + {+Pi, NaN()}, + {Inf(1), Inf(-1)}, + {Inf(1), -Pi}, + {Inf(1), 0}, + {Inf(1), +Pi}, + {Inf(1), Inf(1)}, + {Inf(1), NaN()}, + {NaN(), NaN()}, +} +var atan2SC = []float64{ + -3 * Pi / 4, // atan2(-Inf, -Inf) + -Pi / 2, // atan2(-Inf, -Pi) + -Pi / 2, // atan2(-Inf, +0) + -Pi / 2, // atan2(-Inf, +Pi) + -Pi / 4, // atan2(-Inf, +Inf) + NaN(), // atan2(-Inf, NaN) + -Pi, // atan2(-Pi, -Inf) + -Pi / 2, // atan2(-Pi, +0) + Copysign(0, -1), // atan2(-Pi, Inf) + NaN(), // atan2(-Pi, NaN) + -Pi, // atan2(-0, -Inf) + -Pi, // atan2(-0, -Pi) + -Pi, // atan2(-0, -0) + Copysign(0, -1), // atan2(-0, +0) + Copysign(0, -1), // atan2(-0, +Pi) + Copysign(0, -1), // atan2(-0, +Inf) + NaN(), // atan2(-0, NaN) + Pi, // atan2(+0, -Inf) + Pi, // atan2(+0, -Pi) + Pi, // atan2(+0, -0) + 0, // atan2(+0, +0) + 0, // atan2(+0, +Pi) + 0, // atan2(+0, +Inf) + NaN(), // atan2(+0, NaN) + Pi, // atan2(+Pi, -Inf) + Pi / 2, // atan2(+Pi, +0) + 0, // atan2(+Pi, +Inf) + 0, // atan2(+1, +Inf) + Copysign(0, -1), // atan2(-1, +Inf) + NaN(), // atan2(+Pi, NaN) + 3 * Pi / 4, // atan2(+Inf, -Inf) + Pi / 2, // atan2(+Inf, -Pi) + Pi / 2, // atan2(+Inf, +0) + Pi / 2, // atan2(+Inf, +Pi) + Pi / 4, // atan2(+Inf, +Inf) + NaN(), // atan2(+Inf, NaN) + NaN(), // atan2(NaN, NaN) +} + +var vfcbrtSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var cbrtSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} + +var vfceilSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), + 1<<52 - 1, + 1<<52 - 0.5, // largest fractional float64 + 1 << 52, + -1 << 52, + -1<<52 + 0.5, // smallest fractional float64 + -1<<52 + 1, + 1 << 53, + -1 << 53, +} + +var ceilBaseSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} + +var ceilSC = append(ceilBaseSC, + 1<<52-1, + 1<<52, + 1<<52, + -1<<52, + -1<<52+1, + -1<<52+1, + 1<<53, + -1<<53, +) + +var floorSC = append(ceilBaseSC, + 1<<52-1, + 1<<52-1, + 1<<52, + -1<<52, + -1<<52, + -1<<52+1, + 1<<53, + -1<<53, +) + +var truncSC = append(ceilBaseSC, + 1<<52-1, + 1<<52-1, + 1<<52, + -1<<52, + -1<<52+1, + -1<<52+1, + 1<<53, + -1<<53, +) + +var vfcopysignSC = []float64{ + Inf(-1), + Inf(1), + NaN(), +} +var copysignSC = []float64{ + Inf(-1), + Inf(-1), + NaN(), +} + +var vfcosSC = []float64{ + Inf(-1), + Inf(1), + NaN(), +} +var cosSC = []float64{ + NaN(), + NaN(), + NaN(), +} + +var vfcoshSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var coshSC = []float64{ + Inf(1), + 1, + 1, + Inf(1), + NaN(), +} + +var vferfSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), + -1000, + 1000, +} +var erfSC = []float64{ + -1, + Copysign(0, -1), + 0, + 1, + NaN(), + -1, + 1, +} + +var vferfcSC = []float64{ + Inf(-1), + Inf(1), + NaN(), + -1000, + 1000, +} +var erfcSC = []float64{ + 2, + 0, + NaN(), + 2, + 0, +} + +var vferfinvSC = []float64{ + 1, + -1, + 0, + Inf(-1), + Inf(1), + NaN(), +} +var erfinvSC = []float64{ + Inf(+1), + Inf(-1), + 0, + NaN(), + NaN(), + NaN(), +} + +var vferfcinvSC = []float64{ + 0, + 2, + 1, + Inf(1), + Inf(-1), + NaN(), +} +var erfcinvSC = []float64{ + Inf(+1), + Inf(-1), + 0, + NaN(), + NaN(), + NaN(), +} + +var vfexpSC = []float64{ + Inf(-1), + -2000, + 2000, + Inf(1), + NaN(), + // smallest float64 that overflows Exp(x) + 7.097827128933841e+02, + // Issue 18912 + 1.48852223e+09, + 1.4885222e+09, + 1, + // near zero + 3.725290298461915e-09, + // denormal + -740, +} +var expSC = []float64{ + 0, + 0, + Inf(1), + Inf(1), + NaN(), + Inf(1), + Inf(1), + Inf(1), + 2.718281828459045, + 1.0000000037252903, + 4.2e-322, +} + +var vfexp2SC = []float64{ + Inf(-1), + -2000, + 2000, + Inf(1), + NaN(), + // smallest float64 that overflows Exp2(x) + 1024, + // near underflow + -1.07399999999999e+03, + // near zero + 3.725290298461915e-09, +} +var exp2SC = []float64{ + 0, + 0, + Inf(1), + Inf(1), + NaN(), + Inf(1), + 5e-324, + 1.0000000025821745, +} + +var vfexpm1SC = []float64{ + Inf(-1), + -710, + Copysign(0, -1), + 0, + 710, + Inf(1), + NaN(), +} +var expm1SC = []float64{ + -1, + -1, + Copysign(0, -1), + 0, + Inf(1), + Inf(1), + NaN(), +} + +var vffabsSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var fabsSC = []float64{ + Inf(1), + 0, + 0, + Inf(1), + NaN(), +} + +var vffdimSC = [][2]float64{ + {Inf(-1), Inf(-1)}, + {Inf(-1), Inf(1)}, + {Inf(-1), NaN()}, + {Copysign(0, -1), Copysign(0, -1)}, + {Copysign(0, -1), 0}, + {0, Copysign(0, -1)}, + {0, 0}, + {Inf(1), Inf(-1)}, + {Inf(1), Inf(1)}, + {Inf(1), NaN()}, + {NaN(), Inf(-1)}, + {NaN(), Copysign(0, -1)}, + {NaN(), 0}, + {NaN(), Inf(1)}, + {NaN(), NaN()}, +} +var nan = Float64frombits(0xFFF8000000000000) // SSE2 DIVSD 0/0 +var vffdim2SC = [][2]float64{ + {Inf(-1), Inf(-1)}, + {Inf(-1), Inf(1)}, + {Inf(-1), nan}, + {Copysign(0, -1), Copysign(0, -1)}, + {Copysign(0, -1), 0}, + {0, Copysign(0, -1)}, + {0, 0}, + {Inf(1), Inf(-1)}, + {Inf(1), Inf(1)}, + {Inf(1), nan}, + {nan, Inf(-1)}, + {nan, Copysign(0, -1)}, + {nan, 0}, + {nan, Inf(1)}, + {nan, nan}, +} +var fdimSC = []float64{ + NaN(), + 0, + NaN(), + 0, + 0, + 0, + 0, + Inf(1), + NaN(), + NaN(), + NaN(), + NaN(), + NaN(), + NaN(), + NaN(), +} +var fmaxSC = []float64{ + Inf(-1), + Inf(1), + NaN(), + Copysign(0, -1), + 0, + 0, + 0, + Inf(1), + Inf(1), + Inf(1), + NaN(), + NaN(), + NaN(), + Inf(1), + NaN(), +} +var fminSC = []float64{ + Inf(-1), + Inf(-1), + Inf(-1), + Copysign(0, -1), + Copysign(0, -1), + Copysign(0, -1), + 0, + Inf(-1), + Inf(1), + NaN(), + Inf(-1), + NaN(), + NaN(), + NaN(), + NaN(), +} + +var vffmodSC = [][2]float64{ + {Inf(-1), Inf(-1)}, + {Inf(-1), -Pi}, + {Inf(-1), 0}, + {Inf(-1), Pi}, + {Inf(-1), Inf(1)}, + {Inf(-1), NaN()}, + {-Pi, Inf(-1)}, + {-Pi, 0}, + {-Pi, Inf(1)}, + {-Pi, NaN()}, + {Copysign(0, -1), Inf(-1)}, + {Copysign(0, -1), 0}, + {Copysign(0, -1), Inf(1)}, + {Copysign(0, -1), NaN()}, + {0, Inf(-1)}, + {0, 0}, + {0, Inf(1)}, + {0, NaN()}, + {Pi, Inf(-1)}, + {Pi, 0}, + {Pi, Inf(1)}, + {Pi, NaN()}, + {Inf(1), Inf(-1)}, + {Inf(1), -Pi}, + {Inf(1), 0}, + {Inf(1), Pi}, + {Inf(1), Inf(1)}, + {Inf(1), NaN()}, + {NaN(), Inf(-1)}, + {NaN(), -Pi}, + {NaN(), 0}, + {NaN(), Pi}, + {NaN(), Inf(1)}, + {NaN(), NaN()}, +} +var fmodSC = []float64{ + NaN(), // fmod(-Inf, -Inf) + NaN(), // fmod(-Inf, -Pi) + NaN(), // fmod(-Inf, 0) + NaN(), // fmod(-Inf, Pi) + NaN(), // fmod(-Inf, +Inf) + NaN(), // fmod(-Inf, NaN) + -Pi, // fmod(-Pi, -Inf) + NaN(), // fmod(-Pi, 0) + -Pi, // fmod(-Pi, +Inf) + NaN(), // fmod(-Pi, NaN) + Copysign(0, -1), // fmod(-0, -Inf) + NaN(), // fmod(-0, 0) + Copysign(0, -1), // fmod(-0, Inf) + NaN(), // fmod(-0, NaN) + 0, // fmod(0, -Inf) + NaN(), // fmod(0, 0) + 0, // fmod(0, +Inf) + NaN(), // fmod(0, NaN) + Pi, // fmod(Pi, -Inf) + NaN(), // fmod(Pi, 0) + Pi, // fmod(Pi, +Inf) + NaN(), // fmod(Pi, NaN) + NaN(), // fmod(+Inf, -Inf) + NaN(), // fmod(+Inf, -Pi) + NaN(), // fmod(+Inf, 0) + NaN(), // fmod(+Inf, Pi) + NaN(), // fmod(+Inf, +Inf) + NaN(), // fmod(+Inf, NaN) + NaN(), // fmod(NaN, -Inf) + NaN(), // fmod(NaN, -Pi) + NaN(), // fmod(NaN, 0) + NaN(), // fmod(NaN, Pi) + NaN(), // fmod(NaN, +Inf) + NaN(), // fmod(NaN, NaN) +} + +var vffrexpSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var frexpSC = []fi{ + {Inf(-1), 0}, + {Copysign(0, -1), 0}, + {0, 0}, + {Inf(1), 0}, + {NaN(), 0}, +} + +var vfgamma = [][2]float64{ + {Inf(1), Inf(1)}, + {Inf(-1), NaN()}, + {0, Inf(1)}, + {Copysign(0, -1), Inf(-1)}, + {NaN(), NaN()}, + {-1, NaN()}, + {-2, NaN()}, + {-3, NaN()}, + {-1e16, NaN()}, + {-1e300, NaN()}, + {1.7e308, Inf(1)}, + + // Test inputs inspired by Python test suite. + // Outputs computed at high precision by PARI/GP. + // If recomputing table entries, be careful to use + // high-precision (%.1000g) formatting of the float64 inputs. + // For example, -2.0000000000000004 is the float64 with exact value + // -2.00000000000000044408920985626161695, and + // gamma(-2.0000000000000004) = -1249999999999999.5386078562728167651513, while + // gamma(-2.00000000000000044408920985626161695) = -1125899906826907.2044875028130093136826. + // Thus the table lists -1.1258999068426235e+15 as the answer. + {0.5, 1.772453850905516}, + {1.5, 0.886226925452758}, + {2.5, 1.329340388179137}, + {3.5, 3.3233509704478426}, + {-0.5, -3.544907701811032}, + {-1.5, 2.363271801207355}, + {-2.5, -0.9453087204829419}, + {-3.5, 0.2700882058522691}, + {0.1, 9.51350769866873}, + {0.01, 99.4325851191506}, + {1e-08, 9.999999942278434e+07}, + {1e-16, 1e+16}, + {0.001, 999.4237724845955}, + {1e-16, 1e+16}, + {1e-308, 1e+308}, + {5.6e-309, 1.7857142857142864e+308}, + {5.5e-309, Inf(1)}, + {1e-309, Inf(1)}, + {1e-323, Inf(1)}, + {5e-324, Inf(1)}, + {-0.1, -10.686287021193193}, + {-0.01, -100.58719796441078}, + {-1e-08, -1.0000000057721567e+08}, + {-1e-16, -1e+16}, + {-0.001, -1000.5782056293586}, + {-1e-16, -1e+16}, + {-1e-308, -1e+308}, + {-5.6e-309, -1.7857142857142864e+308}, + {-5.5e-309, Inf(-1)}, + {-1e-309, Inf(-1)}, + {-1e-323, Inf(-1)}, + {-5e-324, Inf(-1)}, + {-0.9999999999999999, -9.007199254740992e+15}, + {-1.0000000000000002, 4.5035996273704955e+15}, + {-1.9999999999999998, 2.2517998136852485e+15}, + {-2.0000000000000004, -1.1258999068426235e+15}, + {-100.00000000000001, -7.540083334883109e-145}, + {-99.99999999999999, 7.540083334884096e-145}, + {17, 2.0922789888e+13}, + {171, 7.257415615307999e+306}, + {171.6, 1.5858969096672565e+308}, + {171.624, 1.7942117599248104e+308}, + {171.625, Inf(1)}, + {172, Inf(1)}, + {2000, Inf(1)}, + {-100.5, -3.3536908198076787e-159}, + {-160.5, -5.255546447007829e-286}, + {-170.5, -3.3127395215386074e-308}, + {-171.5, 1.9316265431712e-310}, + {-176.5, -1.196e-321}, + {-177.5, 5e-324}, + {-178.5, Copysign(0, -1)}, + {-179.5, 0}, + {-201.0001, 0}, + {-202.9999, Copysign(0, -1)}, + {-1000.5, Copysign(0, -1)}, + {-1.0000000003e+09, Copysign(0, -1)}, + {-4.5035996273704955e+15, 0}, + {-63.349078729022985, 4.177797167776188e-88}, + {-127.45117632943295, 1.183111089623681e-214}, +} + +var vfhypotSC = [][2]float64{ + {Inf(-1), Inf(-1)}, + {Inf(-1), 0}, + {Inf(-1), Inf(1)}, + {Inf(-1), NaN()}, + {Copysign(0, -1), Copysign(0, -1)}, + {Copysign(0, -1), 0}, + {0, Copysign(0, -1)}, + {0, 0}, // +0, +0 + {0, Inf(-1)}, + {0, Inf(1)}, + {0, NaN()}, + {Inf(1), Inf(-1)}, + {Inf(1), 0}, + {Inf(1), Inf(1)}, + {Inf(1), NaN()}, + {NaN(), Inf(-1)}, + {NaN(), 0}, + {NaN(), Inf(1)}, + {NaN(), NaN()}, +} +var hypotSC = []float64{ + Inf(1), + Inf(1), + Inf(1), + Inf(1), + 0, + 0, + 0, + 0, + Inf(1), + Inf(1), + NaN(), + Inf(1), + Inf(1), + Inf(1), + Inf(1), + Inf(1), + NaN(), + Inf(1), + NaN(), +} + +var ilogbSC = []int{ + MaxInt32, + MinInt32, + MaxInt32, + MaxInt32, +} + +var vfj0SC = []float64{ + Inf(-1), + 0, + Inf(1), + NaN(), +} +var j0SC = []float64{ + 0, + 1, + 0, + NaN(), +} +var j1SC = []float64{ + 0, + 0, + 0, + NaN(), +} +var j2SC = []float64{ + 0, + 0, + 0, + NaN(), +} +var jM3SC = []float64{ + 0, + 0, + 0, + NaN(), +} + +var vfldexpSC = []fi{ + {0, 0}, + {0, -1075}, + {0, 1024}, + {Copysign(0, -1), 0}, + {Copysign(0, -1), -1075}, + {Copysign(0, -1), 1024}, + {Inf(1), 0}, + {Inf(1), -1024}, + {Inf(-1), 0}, + {Inf(-1), -1024}, + {NaN(), -1024}, + {10, int(1) << (uint64(unsafe.Sizeof(0)-1) * 8)}, + {10, -(int(1) << (uint64(unsafe.Sizeof(0)-1) * 8))}, +} +var ldexpSC = []float64{ + 0, + 0, + 0, + Copysign(0, -1), + Copysign(0, -1), + Copysign(0, -1), + Inf(1), + Inf(1), + Inf(-1), + Inf(-1), + NaN(), + Inf(1), + 0, +} + +var vflgammaSC = []float64{ + Inf(-1), + -3, + 0, + 1, + 2, + Inf(1), + NaN(), +} +var lgammaSC = []fi{ + {Inf(-1), 1}, + {Inf(1), 1}, + {Inf(1), 1}, + {0, 1}, + {0, 1}, + {Inf(1), 1}, + {NaN(), 1}, +} + +var vflogSC = []float64{ + Inf(-1), + -Pi, + Copysign(0, -1), + 0, + 1, + Inf(1), + NaN(), +} +var logSC = []float64{ + NaN(), + NaN(), + Inf(-1), + Inf(-1), + 0, + Inf(1), + NaN(), +} + +var vflogbSC = []float64{ + Inf(-1), + 0, + Inf(1), + NaN(), +} +var logbSC = []float64{ + Inf(1), + Inf(-1), + Inf(1), + NaN(), +} + +var vflog1pSC = []float64{ + Inf(-1), + -Pi, + -1, + Copysign(0, -1), + 0, + Inf(1), + NaN(), + 4503599627370496.5, // Issue #29488 +} +var log1pSC = []float64{ + NaN(), + NaN(), + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), + 36.04365338911715, // Issue #29488 +} + +var vfmodfSC = []float64{ + Inf(-1), + Copysign(0, -1), + Inf(1), + NaN(), +} +var modfSC = [][2]float64{ + {Inf(-1), NaN()}, // [2]float64{Copysign(0, -1), Inf(-1)}, + {Copysign(0, -1), Copysign(0, -1)}, + {Inf(1), NaN()}, // [2]float64{0, Inf(1)}, + {NaN(), NaN()}, +} + +var vfnextafter32SC = [][2]float32{ + {0, 0}, + {0, float32(Copysign(0, -1))}, + {0, -1}, + {0, float32(NaN())}, + {float32(Copysign(0, -1)), 1}, + {float32(Copysign(0, -1)), 0}, + {float32(Copysign(0, -1)), float32(Copysign(0, -1))}, + {float32(Copysign(0, -1)), -1}, + {float32(NaN()), 0}, + {float32(NaN()), float32(NaN())}, +} +var nextafter32SC = []float32{ + 0, + 0, + -1.401298464e-45, // Float32frombits(0x80000001) + float32(NaN()), + 1.401298464e-45, // Float32frombits(0x00000001) + float32(Copysign(0, -1)), + float32(Copysign(0, -1)), + -1.401298464e-45, // Float32frombits(0x80000001) + float32(NaN()), + float32(NaN()), +} + +var vfnextafter64SC = [][2]float64{ + {0, 0}, + {0, Copysign(0, -1)}, + {0, -1}, + {0, NaN()}, + {Copysign(0, -1), 1}, + {Copysign(0, -1), 0}, + {Copysign(0, -1), Copysign(0, -1)}, + {Copysign(0, -1), -1}, + {NaN(), 0}, + {NaN(), NaN()}, +} +var nextafter64SC = []float64{ + 0, + 0, + -4.9406564584124654418e-324, // Float64frombits(0x8000000000000001) + NaN(), + 4.9406564584124654418e-324, // Float64frombits(0x0000000000000001) + Copysign(0, -1), + Copysign(0, -1), + -4.9406564584124654418e-324, // Float64frombits(0x8000000000000001) + NaN(), + NaN(), +} + +var vfpowSC = [][2]float64{ + {Inf(-1), -Pi}, + {Inf(-1), -3}, + {Inf(-1), Copysign(0, -1)}, + {Inf(-1), 0}, + {Inf(-1), 1}, + {Inf(-1), 3}, + {Inf(-1), Pi}, + {Inf(-1), 0.5}, + {Inf(-1), NaN()}, + + {-Pi, Inf(-1)}, + {-Pi, -Pi}, + {-Pi, Copysign(0, -1)}, + {-Pi, 0}, + {-Pi, 1}, + {-Pi, Pi}, + {-Pi, Inf(1)}, + {-Pi, NaN()}, + + {-1, Inf(-1)}, + {-1, Inf(1)}, + {-1, NaN()}, + {-0.5, Inf(-1)}, + {-0.5, Inf(1)}, + {Copysign(0, -1), Inf(-1)}, + {Copysign(0, -1), -Pi}, + {Copysign(0, -1), -0.5}, + {Copysign(0, -1), -3}, + {Copysign(0, -1), 3}, + {Copysign(0, -1), Pi}, + {Copysign(0, -1), 0.5}, + {Copysign(0, -1), Inf(1)}, + + {0, Inf(-1)}, + {0, -Pi}, + {0, -3}, + {0, Copysign(0, -1)}, + {0, 0}, + {0, 3}, + {0, Pi}, + {0, Inf(1)}, + {0, NaN()}, + + {0.5, Inf(-1)}, + {0.5, Inf(1)}, + {1, Inf(-1)}, + {1, Inf(1)}, + {1, NaN()}, + + {Pi, Inf(-1)}, + {Pi, Copysign(0, -1)}, + {Pi, 0}, + {Pi, 1}, + {Pi, Inf(1)}, + {Pi, NaN()}, + {Inf(1), -Pi}, + {Inf(1), Copysign(0, -1)}, + {Inf(1), 0}, + {Inf(1), 1}, + {Inf(1), Pi}, + {Inf(1), NaN()}, + {NaN(), -Pi}, + {NaN(), Copysign(0, -1)}, + {NaN(), 0}, + {NaN(), 1}, + {NaN(), Pi}, + {NaN(), NaN()}, + + // Issue #7394 overflow checks + {2, float64(1 << 32)}, + {2, -float64(1 << 32)}, + {-2, float64(1<<32 + 1)}, + {0.5, float64(1 << 45)}, + {0.5, -float64(1 << 45)}, + {Nextafter(1, 2), float64(1 << 63)}, + {Nextafter(1, -2), float64(1 << 63)}, + {Nextafter(-1, 2), float64(1 << 63)}, + {Nextafter(-1, -2), float64(1 << 63)}, + + // Issue #57465 + {Copysign(0, -1), 1e19}, + {Copysign(0, -1), -1e19}, + {Copysign(0, -1), 1<<53 - 1}, + {Copysign(0, -1), -(1<<53 - 1)}, +} +var powSC = []float64{ + 0, // pow(-Inf, -Pi) + Copysign(0, -1), // pow(-Inf, -3) + 1, // pow(-Inf, -0) + 1, // pow(-Inf, +0) + Inf(-1), // pow(-Inf, 1) + Inf(-1), // pow(-Inf, 3) + Inf(1), // pow(-Inf, Pi) + Inf(1), // pow(-Inf, 0.5) + NaN(), // pow(-Inf, NaN) + 0, // pow(-Pi, -Inf) + NaN(), // pow(-Pi, -Pi) + 1, // pow(-Pi, -0) + 1, // pow(-Pi, +0) + -Pi, // pow(-Pi, 1) + NaN(), // pow(-Pi, Pi) + Inf(1), // pow(-Pi, +Inf) + NaN(), // pow(-Pi, NaN) + 1, // pow(-1, -Inf) IEEE 754-2008 + 1, // pow(-1, +Inf) IEEE 754-2008 + NaN(), // pow(-1, NaN) + Inf(1), // pow(-1/2, -Inf) + 0, // pow(-1/2, +Inf) + Inf(1), // pow(-0, -Inf) + Inf(1), // pow(-0, -Pi) + Inf(1), // pow(-0, -0.5) + Inf(-1), // pow(-0, -3) IEEE 754-2008 + Copysign(0, -1), // pow(-0, 3) IEEE 754-2008 + 0, // pow(-0, +Pi) + 0, // pow(-0, 0.5) + 0, // pow(-0, +Inf) + Inf(1), // pow(+0, -Inf) + Inf(1), // pow(+0, -Pi) + Inf(1), // pow(+0, -3) + 1, // pow(+0, -0) + 1, // pow(+0, +0) + 0, // pow(+0, 3) + 0, // pow(+0, +Pi) + 0, // pow(+0, +Inf) + NaN(), // pow(+0, NaN) + Inf(1), // pow(1/2, -Inf) + 0, // pow(1/2, +Inf) + 1, // pow(1, -Inf) IEEE 754-2008 + 1, // pow(1, +Inf) IEEE 754-2008 + 1, // pow(1, NaN) IEEE 754-2008 + 0, // pow(+Pi, -Inf) + 1, // pow(+Pi, -0) + 1, // pow(+Pi, +0) + Pi, // pow(+Pi, 1) + Inf(1), // pow(+Pi, +Inf) + NaN(), // pow(+Pi, NaN) + 0, // pow(+Inf, -Pi) + 1, // pow(+Inf, -0) + 1, // pow(+Inf, +0) + Inf(1), // pow(+Inf, 1) + Inf(1), // pow(+Inf, Pi) + NaN(), // pow(+Inf, NaN) + NaN(), // pow(NaN, -Pi) + 1, // pow(NaN, -0) + 1, // pow(NaN, +0) + NaN(), // pow(NaN, 1) + NaN(), // pow(NaN, +Pi) + NaN(), // pow(NaN, NaN) + + // Issue #7394 overflow checks + Inf(1), // pow(2, float64(1 << 32)) + 0, // pow(2, -float64(1 << 32)) + Inf(-1), // pow(-2, float64(1<<32 + 1)) + 0, // pow(1/2, float64(1 << 45)) + Inf(1), // pow(1/2, -float64(1 << 45)) + Inf(1), // pow(Nextafter(1, 2), float64(1 << 63)) + 0, // pow(Nextafter(1, -2), float64(1 << 63)) + 0, // pow(Nextafter(-1, 2), float64(1 << 63)) + Inf(1), // pow(Nextafter(-1, -2), float64(1 << 63)) + + // Issue #57465 + 0, // pow(-0, 1e19) + Inf(1), // pow(-0, -1e19) + Copysign(0, -1), // pow(-0, 1<<53 -1) + Inf(-1), // pow(-0, -(1<<53 -1)) +} + +var vfpow10SC = []int{ + MinInt32, + -324, + -323, + -50, + -22, + -1, + 0, + 1, + 22, + 50, + 100, + 200, + 308, + 309, + MaxInt32, +} + +var pow10SC = []float64{ + 0, // pow10(MinInt32) + 0, // pow10(-324) + 1.0e-323, // pow10(-323) + 1.0e-50, // pow10(-50) + 1.0e-22, // pow10(-22) + 1.0e-1, // pow10(-1) + 1.0e0, // pow10(0) + 1.0e1, // pow10(1) + 1.0e22, // pow10(22) + 1.0e50, // pow10(50) + 1.0e100, // pow10(100) + 1.0e200, // pow10(200) + 1.0e308, // pow10(308) + Inf(1), // pow10(309) + Inf(1), // pow10(MaxInt32) +} + +var vfroundSC = [][2]float64{ + {0, 0}, + {1.390671161567e-309, 0}, // denormal + {0.49999999999999994, 0}, // 0.5-epsilon + {0.5, 1}, + {0.5000000000000001, 1}, // 0.5+epsilon + {-1.5, -2}, + {-2.5, -3}, + {NaN(), NaN()}, + {Inf(1), Inf(1)}, + {2251799813685249.5, 2251799813685250}, // 1 bit fraction + {2251799813685250.5, 2251799813685251}, + {4503599627370495.5, 4503599627370496}, // 1 bit fraction, rounding to 0 bit fraction + {4503599627370497, 4503599627370497}, // large integer +} +var vfroundEvenSC = [][2]float64{ + {0, 0}, + {1.390671161567e-309, 0}, // denormal + {0.49999999999999994, 0}, // 0.5-epsilon + {0.5, 0}, + {0.5000000000000001, 1}, // 0.5+epsilon + {-1.5, -2}, + {-2.5, -2}, + {NaN(), NaN()}, + {Inf(1), Inf(1)}, + {2251799813685249.5, 2251799813685250}, // 1 bit fraction + {2251799813685250.5, 2251799813685250}, + {4503599627370495.5, 4503599627370496}, // 1 bit fraction, rounding to 0 bit fraction + {4503599627370497, 4503599627370497}, // large integer +} + +var vfsignbitSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var signbitSC = []bool{ + true, + true, + false, + false, + false, +} + +var vfsinSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var sinSC = []float64{ + NaN(), + Copysign(0, -1), + 0, + NaN(), + NaN(), +} + +var vfsinhSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var sinhSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} + +var vfsqrtSC = []float64{ + Inf(-1), + -Pi, + Copysign(0, -1), + 0, + Inf(1), + NaN(), + Float64frombits(2), // subnormal; see https://golang.org/issue/13013 +} +var sqrtSC = []float64{ + NaN(), + NaN(), + Copysign(0, -1), + 0, + Inf(1), + NaN(), + 3.1434555694052576e-162, +} + +var vftanhSC = []float64{ + Inf(-1), + Copysign(0, -1), + 0, + Inf(1), + NaN(), +} +var tanhSC = []float64{ + -1, + Copysign(0, -1), + 0, + 1, + NaN(), +} + +var vfy0SC = []float64{ + Inf(-1), + 0, + Inf(1), + NaN(), + -1, +} +var y0SC = []float64{ + NaN(), + Inf(-1), + 0, + NaN(), + NaN(), +} +var y1SC = []float64{ + NaN(), + Inf(-1), + 0, + NaN(), + NaN(), +} +var y2SC = []float64{ + NaN(), + Inf(-1), + 0, + NaN(), + NaN(), +} +var yM3SC = []float64{ + NaN(), + Inf(1), + 0, + NaN(), + NaN(), +} + +// arguments and expected results for boundary cases +const ( + SmallestNormalFloat64 = 2.2250738585072014e-308 // 2**-1022 + LargestSubnormalFloat64 = SmallestNormalFloat64 - SmallestNonzeroFloat64 +) + +var vffrexpBC = []float64{ + SmallestNormalFloat64, + LargestSubnormalFloat64, + SmallestNonzeroFloat64, + MaxFloat64, + -SmallestNormalFloat64, + -LargestSubnormalFloat64, + -SmallestNonzeroFloat64, + -MaxFloat64, +} +var frexpBC = []fi{ + {0.5, -1021}, + {0.99999999999999978, -1022}, + {0.5, -1073}, + {0.99999999999999989, 1024}, + {-0.5, -1021}, + {-0.99999999999999978, -1022}, + {-0.5, -1073}, + {-0.99999999999999989, 1024}, +} + +var vfldexpBC = []fi{ + {SmallestNormalFloat64, -52}, + {LargestSubnormalFloat64, -51}, + {SmallestNonzeroFloat64, 1074}, + {MaxFloat64, -(1023 + 1074)}, + {1, -1075}, + {-1, -1075}, + {1, 1024}, + {-1, 1024}, + {1.0000000000000002, -1075}, + {1, -1075}, +} +var ldexpBC = []float64{ + SmallestNonzeroFloat64, + 1e-323, // 2**-1073 + 1, + 1e-323, // 2**-1073 + 0, + Copysign(0, -1), + Inf(1), + Inf(-1), + SmallestNonzeroFloat64, + 0, +} + +var logbBC = []float64{ + -1022, + -1023, + -1074, + 1023, + -1022, + -1023, + -1074, + 1023, +} + +// Test cases were generated with Berkeley TestFloat-3e/testfloat_gen. +// http://www.jhauser.us/arithmetic/TestFloat.html. +// The default rounding mode is selected (nearest/even), and exception flags are ignored. +var fmaC = []struct{ x, y, z, want float64 }{ + // Large exponent spread + {-3.999999999999087, -1.1123914289620494e-16, -7.999877929687506, -7.999877929687505}, + {-262112.0000004768, -0.06251525855623184, 1.1102230248837136e-16, 16385.99945072085}, + {-6.462348523533467e-27, -2.3763644720331857e-211, 4.000000000931324, 4.000000000931324}, + + // Effective addition + {-2.0000000037252907, 6.7904383376e-313, -3.3951933161e-313, -1.697607001654e-312}, + {-0.12499999999999999, 512.007568359375, -1.4193627164960366e-16, -64.00094604492188}, + {-2.7550648847397148e-39, -3.4028301595800694e+38, 0.9960937495343386, 1.9335955376735676}, + {5.723369164769208e+24, 3.8149300927159385e-06, 1.84489958778182e+19, 4.028324913621874e+19}, + {-0.4843749999990904, -3.6893487872543293e+19, 9.223653786709391e+18, 2.7093936974938993e+19}, + {-3.8146972665201165e-06, 4.2949672959999385e+09, -2.2204460489938386e-16, -16384.000003844263}, + {6.98156394130982e-309, -1.1072962560000002e+09, -4.4414561548793455e-308, -7.73065965765153e-300}, + + // Effective subtraction + {5e-324, 4.5, -2e-323, 0}, + {5e-324, 7, -3.5e-323, 0}, + {5e-324, 0.5000000000000001, -5e-324, Copysign(0, -1)}, + {-2.1240680525e-314, -1.233647078189316e+308, -0.25781249999954525, -0.25780987964919844}, + {8.579992955364441e-308, 0.6037391876780558, -4.4501307410480706e-308, 7.29947236107098e-309}, + {-4.450143471986689e-308, -0.9960937499927239, -4.450419332475649e-308, -1.7659233458788e-310}, + {1.4932076393918112, -2.2248022430460833e-308, 4.449875571054211e-308, 1.127783865601762e-308}, + + // Overflow + {-2.288020632214759e+38, -8.98846570988901e+307, 1.7696041796300924e+308, Inf(0)}, + {1.4888652783208255e+308, -9.007199254742012e+15, -6.807282911929205e+38, Inf(-1)}, + {9.142703268902826e+192, -1.3504889569802838e+296, -1.9082200803806996e-89, Inf(-1)}, + + // Finite x and y, but non-finite z. + {31.99218749627471, -1.7976930544991702e+308, Inf(0), Inf(0)}, + {-1.7976931281784667e+308, -2.0009765625002265, Inf(-1), Inf(-1)}, + + // Special + {0, 0, 0, 0}, + {Copysign(0, -1), 0, 0, 0}, + {0, 0, Copysign(0, -1), 0}, + {Copysign(0, -1), 0, Copysign(0, -1), Copysign(0, -1)}, + {-1.1754226043408471e-38, NaN(), Inf(0), NaN()}, + {0, 0, 2.22507385643494e-308, 2.22507385643494e-308}, + {-8.65697792e+09, NaN(), -7.516192799999999e+09, NaN()}, + {-0.00012207403779029757, 3.221225471996093e+09, NaN(), NaN()}, + {Inf(-1), 0.1252441407414153, -1.387184532981584e-76, Inf(-1)}, + {Inf(0), 1.525878907671432e-05, -9.214364835452549e+18, Inf(0)}, + + // Random + {0.1777916152213626, -32.000015266239636, -2.2204459148334633e-16, -5.689334401293007}, + {-2.0816681711722314e-16, -0.4997558592585846, -0.9465627129124969, -0.9465627129124968}, + {-1.9999997615814211, 1.8518819259933516e+19, 16.874999999999996, -3.703763410463646e+19}, + {-0.12499994039717421, 32767.99999976135, -2.0752587082923246e+19, -2.075258708292325e+19}, + {7.705600568510257e-34, -1.801432979000528e+16, -0.17224197722973714, -0.17224197722973716}, + {3.8988133103758913e-308, -0.9848632812499999, 3.893879244098556e-308, 5.40811742605814e-310}, + {-0.012651981190687427, 6.911985574912436e+38, 6.669240527007144e+18, -8.745031148409496e+36}, + {4.612811918325842e+18, 1.4901161193847641e-08, 2.6077032311277997e-08, 6.873625395187494e+10}, + {-9.094947033611148e-13, 4.450691014249257e-308, 2.086006742350485e-308, 2.086006742346437e-308}, + {-7.751454006381804e-05, 5.588653777189071e-308, -2.2207280111272877e-308, -2.2211612130544025e-308}, + + // Issue #61130 + {-1, 1, 1, 0}, + {1, 1, -1, 0}, + + // Issue #73757 + {0x1p-1022, -0x1p-1022, 0, Copysign(0, -1)}, + {Copysign(0, -1), 1, 0, 0}, + {1, Copysign(0, -1), 0, 0}, +} + +var sqrt32 = []float32{ + 0, + float32(Copysign(0, -1)), + float32(NaN()), + float32(Inf(1)), + float32(Inf(-1)), + 1, + 2, + -2, + 4.9790119248836735e+00, + 7.7388724745781045e+00, + -2.7688005719200159e-01, + -5.0106036182710749e+00, +} + +func tolerance(a, b, e float64) bool { + // Multiplying by e here can underflow denormal values to zero. + // Check a==b so that at least if a and b are small and identical + // we say they match. + if a == b { + return true + } + d := a - b + if d < 0 { + d = -d + } + + // note: b is correct (expected) value, a is actual value. + // make error tolerance a fraction of b, not a. + if b != 0 { + e = e * b + if e < 0 { + e = -e + } + } + return d < e +} +func close(a, b float64) bool { return tolerance(a, b, 1e-14) } +func veryclose(a, b float64) bool { return tolerance(a, b, 4e-16) } +func soclose(a, b, e float64) bool { return tolerance(a, b, e) } +func alike(a, b float64) bool { + switch { + case IsNaN(a) && IsNaN(b): + return true + case a == b: + return Signbit(a) == Signbit(b) + } + return false +} + +func TestNaN(t *testing.T) { + f64 := NaN() + if f64 == f64 { + t.Fatalf("NaN() returns %g, expected NaN", f64) + } + f32 := float32(f64) + if f32 == f32 { + t.Fatalf("float32(NaN()) is %g, expected NaN", f32) + } +} + +func TestAcos(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := Acos(a); !close(acos[i], f) { + t.Errorf("Acos(%g) = %g, want %g", a, f, acos[i]) + } + } + for i := 0; i < len(vfacosSC); i++ { + if f := Acos(vfacosSC[i]); !alike(acosSC[i], f) { + t.Errorf("Acos(%g) = %g, want %g", vfacosSC[i], f, acosSC[i]) + } + } +} + +func TestAcosh(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := 1 + Abs(vf[i]) + if f := Acosh(a); !veryclose(acosh[i], f) { + t.Errorf("Acosh(%g) = %g, want %g", a, f, acosh[i]) + } + } + for i := 0; i < len(vfacoshSC); i++ { + if f := Acosh(vfacoshSC[i]); !alike(acoshSC[i], f) { + t.Errorf("Acosh(%g) = %g, want %g", vfacoshSC[i], f, acoshSC[i]) + } + } +} + +func TestAsin(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := Asin(a); !veryclose(asin[i], f) { + t.Errorf("Asin(%g) = %g, want %g", a, f, asin[i]) + } + } + for i := 0; i < len(vfasinSC); i++ { + if f := Asin(vfasinSC[i]); !alike(asinSC[i], f) { + t.Errorf("Asin(%g) = %g, want %g", vfasinSC[i], f, asinSC[i]) + } + } +} + +func TestAsinh(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Asinh(vf[i]); !veryclose(asinh[i], f) { + t.Errorf("Asinh(%g) = %g, want %g", vf[i], f, asinh[i]) + } + } + for i := 0; i < len(vfasinhSC); i++ { + if f := Asinh(vfasinhSC[i]); !alike(asinhSC[i], f) { + t.Errorf("Asinh(%g) = %g, want %g", vfasinhSC[i], f, asinhSC[i]) + } + } +} + +func TestAtan(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Atan(vf[i]); !veryclose(atan[i], f) { + t.Errorf("Atan(%g) = %g, want %g", vf[i], f, atan[i]) + } + } + for i := 0; i < len(vfatanSC); i++ { + if f := Atan(vfatanSC[i]); !alike(atanSC[i], f) { + t.Errorf("Atan(%g) = %g, want %g", vfatanSC[i], f, atanSC[i]) + } + } +} + +func TestAtanh(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := Atanh(a); !veryclose(atanh[i], f) { + t.Errorf("Atanh(%g) = %g, want %g", a, f, atanh[i]) + } + } + for i := 0; i < len(vfatanhSC); i++ { + if f := Atanh(vfatanhSC[i]); !alike(atanhSC[i], f) { + t.Errorf("Atanh(%g) = %g, want %g", vfatanhSC[i], f, atanhSC[i]) + } + } +} + +func TestAtan2(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Atan2(10, vf[i]); !veryclose(atan2[i], f) { + t.Errorf("Atan2(10, %g) = %g, want %g", vf[i], f, atan2[i]) + } + } + for i := 0; i < len(vfatan2SC); i++ { + if f := Atan2(vfatan2SC[i][0], vfatan2SC[i][1]); !alike(atan2SC[i], f) { + t.Errorf("Atan2(%g, %g) = %g, want %g", vfatan2SC[i][0], vfatan2SC[i][1], f, atan2SC[i]) + } + } +} + +func TestCbrt(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Cbrt(vf[i]); !veryclose(cbrt[i], f) { + t.Errorf("Cbrt(%g) = %g, want %g", vf[i], f, cbrt[i]) + } + } + for i := 0; i < len(vfcbrtSC); i++ { + if f := Cbrt(vfcbrtSC[i]); !alike(cbrtSC[i], f) { + t.Errorf("Cbrt(%g) = %g, want %g", vfcbrtSC[i], f, cbrtSC[i]) + } + } +} + +func TestCeil(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Ceil(vf[i]); !alike(ceil[i], f) { + t.Errorf("Ceil(%g) = %g, want %g", vf[i], f, ceil[i]) + } + } + for i := 0; i < len(vfceilSC); i++ { + if f := Ceil(vfceilSC[i]); !alike(ceilSC[i], f) { + t.Errorf("Ceil(%g) = %g, want %g", vfceilSC[i], f, ceilSC[i]) + } + } +} + +func TestCopysign(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Copysign(vf[i], -1); copysign[i] != f { + t.Errorf("Copysign(%g, -1) = %g, want %g", vf[i], f, copysign[i]) + } + } + for i := 0; i < len(vf); i++ { + if f := Copysign(vf[i], 1); -copysign[i] != f { + t.Errorf("Copysign(%g, 1) = %g, want %g", vf[i], f, -copysign[i]) + } + } + for i := 0; i < len(vfcopysignSC); i++ { + if f := Copysign(vfcopysignSC[i], -1); !alike(copysignSC[i], f) { + t.Errorf("Copysign(%g, -1) = %g, want %g", vfcopysignSC[i], f, copysignSC[i]) + } + } +} + +func TestCos(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Cos(vf[i]); !veryclose(cos[i], f) { + t.Errorf("Cos(%g) = %g, want %g", vf[i], f, cos[i]) + } + } + for i := 0; i < len(vfcosSC); i++ { + if f := Cos(vfcosSC[i]); !alike(cosSC[i], f) { + t.Errorf("Cos(%g) = %g, want %g", vfcosSC[i], f, cosSC[i]) + } + } +} + +func TestCosh(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Cosh(vf[i]); !close(cosh[i], f) { + t.Errorf("Cosh(%g) = %g, want %g", vf[i], f, cosh[i]) + } + } + for i := 0; i < len(vfcoshSC); i++ { + if f := Cosh(vfcoshSC[i]); !alike(coshSC[i], f) { + t.Errorf("Cosh(%g) = %g, want %g", vfcoshSC[i], f, coshSC[i]) + } + } +} + +func TestErf(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := Erf(a); !veryclose(erf[i], f) { + t.Errorf("Erf(%g) = %g, want %g", a, f, erf[i]) + } + } + for i := 0; i < len(vferfSC); i++ { + if f := Erf(vferfSC[i]); !alike(erfSC[i], f) { + t.Errorf("Erf(%g) = %g, want %g", vferfSC[i], f, erfSC[i]) + } + } +} + +func TestErfc(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := Erfc(a); !veryclose(erfc[i], f) { + t.Errorf("Erfc(%g) = %g, want %g", a, f, erfc[i]) + } + } + for i := 0; i < len(vferfcSC); i++ { + if f := Erfc(vferfcSC[i]); !alike(erfcSC[i], f) { + t.Errorf("Erfc(%g) = %g, want %g", vferfcSC[i], f, erfcSC[i]) + } + } +} + +func TestErfinv(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := Erfinv(a); !veryclose(erfinv[i], f) { + t.Errorf("Erfinv(%g) = %g, want %g", a, f, erfinv[i]) + } + } + for i := 0; i < len(vferfinvSC); i++ { + if f := Erfinv(vferfinvSC[i]); !alike(erfinvSC[i], f) { + t.Errorf("Erfinv(%g) = %g, want %g", vferfinvSC[i], f, erfinvSC[i]) + } + } + for x := -0.9; x <= 0.90; x += 1e-2 { + if f := Erf(Erfinv(x)); !close(x, f) { + t.Errorf("Erf(Erfinv(%g)) = %g, want %g", x, f, x) + } + } + for x := -0.9; x <= 0.90; x += 1e-2 { + if f := Erfinv(Erf(x)); !close(x, f) { + t.Errorf("Erfinv(Erf(%g)) = %g, want %g", x, f, x) + } + } +} + +func TestErfcinv(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := 1.0 - (vf[i] / 10) + if f := Erfcinv(a); !veryclose(erfinv[i], f) { + t.Errorf("Erfcinv(%g) = %g, want %g", a, f, erfinv[i]) + } + } + for i := 0; i < len(vferfcinvSC); i++ { + if f := Erfcinv(vferfcinvSC[i]); !alike(erfcinvSC[i], f) { + t.Errorf("Erfcinv(%g) = %g, want %g", vferfcinvSC[i], f, erfcinvSC[i]) + } + } + for x := 0.1; x <= 1.9; x += 1e-2 { + if f := Erfc(Erfcinv(x)); !close(x, f) { + t.Errorf("Erfc(Erfcinv(%g)) = %g, want %g", x, f, x) + } + } + for x := 0.1; x <= 1.9; x += 1e-2 { + if f := Erfcinv(Erfc(x)); !close(x, f) { + t.Errorf("Erfcinv(Erfc(%g)) = %g, want %g", x, f, x) + } + } +} + +func TestExp(t *testing.T) { + testExp(t, Exp, "Exp") + testExp(t, ExpGo, "ExpGo") +} + +func testExp(t *testing.T, Exp func(float64) float64, name string) { + for i := 0; i < len(vf); i++ { + if f := Exp(vf[i]); !veryclose(exp[i], f) { + t.Errorf("%s(%g) = %g, want %g", name, vf[i], f, exp[i]) + } + } + for i := 0; i < len(vfexpSC); i++ { + if f := Exp(vfexpSC[i]); !alike(expSC[i], f) { + t.Errorf("%s(%g) = %g, want %g", name, vfexpSC[i], f, expSC[i]) + } + } +} + +func TestExpm1(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 100 + if f := Expm1(a); !veryclose(expm1[i], f) { + t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1[i]) + } + } + for i := 0; i < len(vf); i++ { + a := vf[i] * 10 + if f := Expm1(a); !close(expm1Large[i], f) { + t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1Large[i]) + } + } + for i := 0; i < len(vfexpm1SC); i++ { + if f := Expm1(vfexpm1SC[i]); !alike(expm1SC[i], f) { + t.Errorf("Expm1(%g) = %g, want %g", vfexpm1SC[i], f, expm1SC[i]) + } + } +} + +func TestExp2(t *testing.T) { + testExp2(t, Exp2, "Exp2") + testExp2(t, Exp2Go, "Exp2Go") +} + +func testExp2(t *testing.T, Exp2 func(float64) float64, name string) { + for i := 0; i < len(vf); i++ { + if f := Exp2(vf[i]); !close(exp2[i], f) { + t.Errorf("%s(%g) = %g, want %g", name, vf[i], f, exp2[i]) + } + } + for i := 0; i < len(vfexp2SC); i++ { + if f := Exp2(vfexp2SC[i]); !alike(exp2SC[i], f) { + t.Errorf("%s(%g) = %g, want %g", name, vfexp2SC[i], f, exp2SC[i]) + } + } + for n := -1074; n < 1024; n++ { + f := Exp2(float64(n)) + vf := Ldexp(1, n) + if f != vf { + t.Errorf("%s(%d) = %g, want %g", name, n, f, vf) + } + } +} + +func TestAbs(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Abs(vf[i]); fabs[i] != f { + t.Errorf("Abs(%g) = %g, want %g", vf[i], f, fabs[i]) + } + } + for i := 0; i < len(vffabsSC); i++ { + if f := Abs(vffabsSC[i]); !alike(fabsSC[i], f) { + t.Errorf("Abs(%g) = %g, want %g", vffabsSC[i], f, fabsSC[i]) + } + } +} + +func TestDim(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Dim(vf[i], 0); fdim[i] != f { + t.Errorf("Dim(%g, %g) = %g, want %g", vf[i], 0.0, f, fdim[i]) + } + } + for i := 0; i < len(vffdimSC); i++ { + if f := Dim(vffdimSC[i][0], vffdimSC[i][1]); !alike(fdimSC[i], f) { + t.Errorf("Dim(%g, %g) = %g, want %g", vffdimSC[i][0], vffdimSC[i][1], f, fdimSC[i]) + } + } + for i := 0; i < len(vffdim2SC); i++ { + if f := Dim(vffdim2SC[i][0], vffdim2SC[i][1]); !alike(fdimSC[i], f) { + t.Errorf("Dim(%g, %g) = %g, want %g", vffdim2SC[i][0], vffdim2SC[i][1], f, fdimSC[i]) + } + } +} + +func TestFloor(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Floor(vf[i]); !alike(floor[i], f) { + t.Errorf("Floor(%g) = %g, want %g", vf[i], f, floor[i]) + } + } + for i := 0; i < len(vfceilSC); i++ { + if f := Floor(vfceilSC[i]); !alike(floorSC[i], f) { + t.Errorf("Floor(%g) = %g, want %g", vfceilSC[i], f, floorSC[i]) + } + } +} + +func TestMax(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Max(vf[i], ceil[i]); ceil[i] != f { + t.Errorf("Max(%g, %g) = %g, want %g", vf[i], ceil[i], f, ceil[i]) + } + } + for i := 0; i < len(vffdimSC); i++ { + if f := Max(vffdimSC[i][0], vffdimSC[i][1]); !alike(fmaxSC[i], f) { + t.Errorf("Max(%g, %g) = %g, want %g", vffdimSC[i][0], vffdimSC[i][1], f, fmaxSC[i]) + } + } + for i := 0; i < len(vffdim2SC); i++ { + if f := Max(vffdim2SC[i][0], vffdim2SC[i][1]); !alike(fmaxSC[i], f) { + t.Errorf("Max(%g, %g) = %g, want %g", vffdim2SC[i][0], vffdim2SC[i][1], f, fmaxSC[i]) + } + } +} + +func TestMin(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Min(vf[i], floor[i]); floor[i] != f { + t.Errorf("Min(%g, %g) = %g, want %g", vf[i], floor[i], f, floor[i]) + } + } + for i := 0; i < len(vffdimSC); i++ { + if f := Min(vffdimSC[i][0], vffdimSC[i][1]); !alike(fminSC[i], f) { + t.Errorf("Min(%g, %g) = %g, want %g", vffdimSC[i][0], vffdimSC[i][1], f, fminSC[i]) + } + } + for i := 0; i < len(vffdim2SC); i++ { + if f := Min(vffdim2SC[i][0], vffdim2SC[i][1]); !alike(fminSC[i], f) { + t.Errorf("Min(%g, %g) = %g, want %g", vffdim2SC[i][0], vffdim2SC[i][1], f, fminSC[i]) + } + } +} + +func TestMod(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Mod(10, vf[i]); fmod[i] != f { + t.Errorf("Mod(10, %g) = %g, want %g", vf[i], f, fmod[i]) + } + } + for i := 0; i < len(vffmodSC); i++ { + if f := Mod(vffmodSC[i][0], vffmodSC[i][1]); !alike(fmodSC[i], f) { + t.Errorf("Mod(%g, %g) = %g, want %g", vffmodSC[i][0], vffmodSC[i][1], f, fmodSC[i]) + } + } + // verify precision of result for extreme inputs + if f := Mod(5.9790119248836734e+200, 1.1258465975523544); 0.6447968302508578 != f { + t.Errorf("Remainder(5.9790119248836734e+200, 1.1258465975523544) = %g, want 0.6447968302508578", f) + } +} + +func TestFrexp(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f, j := Frexp(vf[i]); !veryclose(frexp[i].f, f) || frexp[i].i != j { + t.Errorf("Frexp(%g) = %g, %d, want %g, %d", vf[i], f, j, frexp[i].f, frexp[i].i) + } + } + for i := 0; i < len(vffrexpSC); i++ { + if f, j := Frexp(vffrexpSC[i]); !alike(frexpSC[i].f, f) || frexpSC[i].i != j { + t.Errorf("Frexp(%g) = %g, %d, want %g, %d", vffrexpSC[i], f, j, frexpSC[i].f, frexpSC[i].i) + } + } + for i := 0; i < len(vffrexpBC); i++ { + if f, j := Frexp(vffrexpBC[i]); !alike(frexpBC[i].f, f) || frexpBC[i].i != j { + t.Errorf("Frexp(%g) = %g, %d, want %g, %d", vffrexpBC[i], f, j, frexpBC[i].f, frexpBC[i].i) + } + } +} + +func TestGamma(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Gamma(vf[i]); !close(gamma[i], f) { + t.Errorf("Gamma(%g) = %g, want %g", vf[i], f, gamma[i]) + } + } + for _, g := range vfgamma { + f := Gamma(g[0]) + var ok bool + if IsNaN(g[1]) || IsInf(g[1], 0) || g[1] == 0 || f == 0 { + ok = alike(g[1], f) + } else if g[0] > -50 && g[0] <= 171 { + ok = veryclose(g[1], f) + } else { + ok = close(g[1], f) + } + if !ok { + t.Errorf("Gamma(%g) = %g, want %g", g[0], f, g[1]) + } + } +} + +func TestHypot(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(1e200 * tanh[i] * Sqrt(2)) + if f := Hypot(1e200*tanh[i], 1e200*tanh[i]); !veryclose(a, f) { + t.Errorf("Hypot(%g, %g) = %g, want %g", 1e200*tanh[i], 1e200*tanh[i], f, a) + } + } + for i := 0; i < len(vfhypotSC); i++ { + if f := Hypot(vfhypotSC[i][0], vfhypotSC[i][1]); !alike(hypotSC[i], f) { + t.Errorf("Hypot(%g, %g) = %g, want %g", vfhypotSC[i][0], vfhypotSC[i][1], f, hypotSC[i]) + } + } +} + +func TestHypotGo(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(1e200 * tanh[i] * Sqrt(2)) + if f := HypotGo(1e200*tanh[i], 1e200*tanh[i]); !veryclose(a, f) { + t.Errorf("HypotGo(%g, %g) = %g, want %g", 1e200*tanh[i], 1e200*tanh[i], f, a) + } + } + for i := 0; i < len(vfhypotSC); i++ { + if f := HypotGo(vfhypotSC[i][0], vfhypotSC[i][1]); !alike(hypotSC[i], f) { + t.Errorf("HypotGo(%g, %g) = %g, want %g", vfhypotSC[i][0], vfhypotSC[i][1], f, hypotSC[i]) + } + } +} + +func TestIlogb(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := frexp[i].i - 1 // adjust because fr in the interval [½, 1) + if e := Ilogb(vf[i]); a != e { + t.Errorf("Ilogb(%g) = %d, want %d", vf[i], e, a) + } + } + for i := 0; i < len(vflogbSC); i++ { + if e := Ilogb(vflogbSC[i]); ilogbSC[i] != e { + t.Errorf("Ilogb(%g) = %d, want %d", vflogbSC[i], e, ilogbSC[i]) + } + } + for i := 0; i < len(vffrexpBC); i++ { + if e := Ilogb(vffrexpBC[i]); int(logbBC[i]) != e { + t.Errorf("Ilogb(%g) = %d, want %d", vffrexpBC[i], e, int(logbBC[i])) + } + } +} + +func TestJ0(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := J0(vf[i]); !soclose(j0[i], f, 4e-14) { + t.Errorf("J0(%g) = %g, want %g", vf[i], f, j0[i]) + } + } + for i := 0; i < len(vfj0SC); i++ { + if f := J0(vfj0SC[i]); !alike(j0SC[i], f) { + t.Errorf("J0(%g) = %g, want %g", vfj0SC[i], f, j0SC[i]) + } + } +} + +func TestJ1(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := J1(vf[i]); !close(j1[i], f) { + t.Errorf("J1(%g) = %g, want %g", vf[i], f, j1[i]) + } + } + for i := 0; i < len(vfj0SC); i++ { + if f := J1(vfj0SC[i]); !alike(j1SC[i], f) { + t.Errorf("J1(%g) = %g, want %g", vfj0SC[i], f, j1SC[i]) + } + } +} + +func TestJn(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Jn(2, vf[i]); !close(j2[i], f) { + t.Errorf("Jn(2, %g) = %g, want %g", vf[i], f, j2[i]) + } + if f := Jn(-3, vf[i]); !close(jM3[i], f) { + t.Errorf("Jn(-3, %g) = %g, want %g", vf[i], f, jM3[i]) + } + } + for i := 0; i < len(vfj0SC); i++ { + if f := Jn(2, vfj0SC[i]); !alike(j2SC[i], f) { + t.Errorf("Jn(2, %g) = %g, want %g", vfj0SC[i], f, j2SC[i]) + } + if f := Jn(-3, vfj0SC[i]); !alike(jM3SC[i], f) { + t.Errorf("Jn(-3, %g) = %g, want %g", vfj0SC[i], f, jM3SC[i]) + } + } +} + +func TestLdexp(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Ldexp(frexp[i].f, frexp[i].i); !veryclose(vf[i], f) { + t.Errorf("Ldexp(%g, %d) = %g, want %g", frexp[i].f, frexp[i].i, f, vf[i]) + } + } + for i := 0; i < len(vffrexpSC); i++ { + if f := Ldexp(frexpSC[i].f, frexpSC[i].i); !alike(vffrexpSC[i], f) { + t.Errorf("Ldexp(%g, %d) = %g, want %g", frexpSC[i].f, frexpSC[i].i, f, vffrexpSC[i]) + } + } + for i := 0; i < len(vfldexpSC); i++ { + if f := Ldexp(vfldexpSC[i].f, vfldexpSC[i].i); !alike(ldexpSC[i], f) { + t.Errorf("Ldexp(%g, %d) = %g, want %g", vfldexpSC[i].f, vfldexpSC[i].i, f, ldexpSC[i]) + } + } + for i := 0; i < len(vffrexpBC); i++ { + if f := Ldexp(frexpBC[i].f, frexpBC[i].i); !alike(vffrexpBC[i], f) { + t.Errorf("Ldexp(%g, %d) = %g, want %g", frexpBC[i].f, frexpBC[i].i, f, vffrexpBC[i]) + } + } + for i := 0; i < len(vfldexpBC); i++ { + if f := Ldexp(vfldexpBC[i].f, vfldexpBC[i].i); !alike(ldexpBC[i], f) { + t.Errorf("Ldexp(%g, %d) = %g, want %g", vfldexpBC[i].f, vfldexpBC[i].i, f, ldexpBC[i]) + } + } +} + +func TestLgamma(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f, s := Lgamma(vf[i]); !close(lgamma[i].f, f) || lgamma[i].i != s { + t.Errorf("Lgamma(%g) = %g, %d, want %g, %d", vf[i], f, s, lgamma[i].f, lgamma[i].i) + } + } + for i := 0; i < len(vflgammaSC); i++ { + if f, s := Lgamma(vflgammaSC[i]); !alike(lgammaSC[i].f, f) || lgammaSC[i].i != s { + t.Errorf("Lgamma(%g) = %g, %d, want %g, %d", vflgammaSC[i], f, s, lgammaSC[i].f, lgammaSC[i].i) + } + } +} + +func TestLog(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := Log(a); log[i] != f { + t.Errorf("Log(%g) = %g, want %g", a, f, log[i]) + } + } + if f := Log(10); f != Ln10 { + t.Errorf("Log(%g) = %g, want %g", 10.0, f, Ln10) + } + for i := 0; i < len(vflogSC); i++ { + if f := Log(vflogSC[i]); !alike(logSC[i], f) { + t.Errorf("Log(%g) = %g, want %g", vflogSC[i], f, logSC[i]) + } + } +} + +func TestLogb(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Logb(vf[i]); logb[i] != f { + t.Errorf("Logb(%g) = %g, want %g", vf[i], f, logb[i]) + } + } + for i := 0; i < len(vflogbSC); i++ { + if f := Logb(vflogbSC[i]); !alike(logbSC[i], f) { + t.Errorf("Logb(%g) = %g, want %g", vflogbSC[i], f, logbSC[i]) + } + } + for i := 0; i < len(vffrexpBC); i++ { + if f := Logb(vffrexpBC[i]); !alike(logbBC[i], f) { + t.Errorf("Logb(%g) = %g, want %g", vffrexpBC[i], f, logbBC[i]) + } + } +} + +func TestLog10(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := Log10(a); !veryclose(log10[i], f) { + t.Errorf("Log10(%g) = %g, want %g", a, f, log10[i]) + } + } + if f := Log10(E); f != Log10E { + t.Errorf("Log10(%g) = %g, want %g", E, f, Log10E) + } + for i := 0; i < len(vflogSC); i++ { + if f := Log10(vflogSC[i]); !alike(logSC[i], f) { + t.Errorf("Log10(%g) = %g, want %g", vflogSC[i], f, logSC[i]) + } + } +} + +func TestLog1p(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := vf[i] / 100 + if f := Log1p(a); !veryclose(log1p[i], f) { + t.Errorf("Log1p(%g) = %g, want %g", a, f, log1p[i]) + } + } + a := 9.0 + if f := Log1p(a); f != Ln10 { + t.Errorf("Log1p(%g) = %g, want %g", a, f, Ln10) + } + for i := 0; i < len(vflogSC); i++ { + if f := Log1p(vflog1pSC[i]); !alike(log1pSC[i], f) { + t.Errorf("Log1p(%g) = %g, want %g", vflog1pSC[i], f, log1pSC[i]) + } + } +} + +func TestLog2(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := Log2(a); !veryclose(log2[i], f) { + t.Errorf("Log2(%g) = %g, want %g", a, f, log2[i]) + } + } + if f := Log2(E); f != Log2E { + t.Errorf("Log2(%g) = %g, want %g", E, f, Log2E) + } + for i := 0; i < len(vflogSC); i++ { + if f := Log2(vflogSC[i]); !alike(logSC[i], f) { + t.Errorf("Log2(%g) = %g, want %g", vflogSC[i], f, logSC[i]) + } + } + for i := -1074; i <= 1023; i++ { + f := Ldexp(1, i) + l := Log2(f) + if l != float64(i) { + t.Errorf("Log2(2**%d) = %g, want %d", i, l, i) + } + } +} + +func TestModf(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f, g := Modf(vf[i]); !veryclose(modf[i][0], f) || !veryclose(modf[i][1], g) { + t.Errorf("Modf(%g) = %g, %g, want %g, %g", vf[i], f, g, modf[i][0], modf[i][1]) + } + } + for i := 0; i < len(vfmodfSC); i++ { + if f, g := Modf(vfmodfSC[i]); !alike(modfSC[i][0], f) || !alike(modfSC[i][1], g) { + t.Errorf("Modf(%g) = %g, %g, want %g, %g", vfmodfSC[i], f, g, modfSC[i][0], modfSC[i][1]) + } + } +} + +func TestNextafter32(t *testing.T) { + for i := 0; i < len(vf); i++ { + vfi := float32(vf[i]) + if f := Nextafter32(vfi, 10); nextafter32[i] != f { + t.Errorf("Nextafter32(%g, %g) = %g want %g", vfi, 10.0, f, nextafter32[i]) + } + } + for i := 0; i < len(vfnextafter32SC); i++ { + if f := Nextafter32(vfnextafter32SC[i][0], vfnextafter32SC[i][1]); !alike(float64(nextafter32SC[i]), float64(f)) { + t.Errorf("Nextafter32(%g, %g) = %g want %g", vfnextafter32SC[i][0], vfnextafter32SC[i][1], f, nextafter32SC[i]) + } + } +} + +func TestNextafter64(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Nextafter(vf[i], 10); nextafter64[i] != f { + t.Errorf("Nextafter64(%g, %g) = %g want %g", vf[i], 10.0, f, nextafter64[i]) + } + } + for i := 0; i < len(vfnextafter64SC); i++ { + if f := Nextafter(vfnextafter64SC[i][0], vfnextafter64SC[i][1]); !alike(nextafter64SC[i], f) { + t.Errorf("Nextafter64(%g, %g) = %g want %g", vfnextafter64SC[i][0], vfnextafter64SC[i][1], f, nextafter64SC[i]) + } + } +} + +func TestPow(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Pow(10, vf[i]); !close(pow[i], f) { + t.Errorf("Pow(10, %g) = %g, want %g", vf[i], f, pow[i]) + } + } + for i := 0; i < len(vfpowSC); i++ { + if f := Pow(vfpowSC[i][0], vfpowSC[i][1]); !alike(powSC[i], f) { + t.Errorf("Pow(%g, %g) = %g, want %g", vfpowSC[i][0], vfpowSC[i][1], f, powSC[i]) + } + } +} + +func TestPow10(t *testing.T) { + for i := 0; i < len(vfpow10SC); i++ { + if f := Pow10(vfpow10SC[i]); !alike(pow10SC[i], f) { + t.Errorf("Pow10(%d) = %g, want %g", vfpow10SC[i], f, pow10SC[i]) + } + } +} + +func TestRemainder(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Remainder(10, vf[i]); remainder[i] != f { + t.Errorf("Remainder(10, %g) = %g, want %g", vf[i], f, remainder[i]) + } + } + for i := 0; i < len(vffmodSC); i++ { + if f := Remainder(vffmodSC[i][0], vffmodSC[i][1]); !alike(fmodSC[i], f) { + t.Errorf("Remainder(%g, %g) = %g, want %g", vffmodSC[i][0], vffmodSC[i][1], f, fmodSC[i]) + } + } + // verify precision of result for extreme inputs + if f := Remainder(5.9790119248836734e+200, 1.1258465975523544); -0.4810497673014966 != f { + t.Errorf("Remainder(5.9790119248836734e+200, 1.1258465975523544) = %g, want -0.4810497673014966", f) + } + // verify that sign is correct when r == 0. + test := func(x, y float64) { + if r := Remainder(x, y); r == 0 && Signbit(r) != Signbit(x) { + t.Errorf("Remainder(x=%f, y=%f) = %f, sign of (zero) result should agree with sign of x", x, y, r) + } + } + for x := 0.0; x <= 3.0; x += 1 { + for y := 1.0; y <= 3.0; y += 1 { + test(x, y) + test(x, -y) + test(-x, y) + test(-x, -y) + } + } +} + +func TestRound(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Round(vf[i]); !alike(round[i], f) { + t.Errorf("Round(%g) = %g, want %g", vf[i], f, round[i]) + } + } + for i := 0; i < len(vfroundSC); i++ { + if f := Round(vfroundSC[i][0]); !alike(vfroundSC[i][1], f) { + t.Errorf("Round(%g) = %g, want %g", vfroundSC[i][0], f, vfroundSC[i][1]) + } + } +} + +func TestRoundToEven(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := RoundToEven(vf[i]); !alike(round[i], f) { + t.Errorf("RoundToEven(%g) = %g, want %g", vf[i], f, round[i]) + } + } + for i := 0; i < len(vfroundEvenSC); i++ { + if f := RoundToEven(vfroundEvenSC[i][0]); !alike(vfroundEvenSC[i][1], f) { + t.Errorf("RoundToEven(%g) = %g, want %g", vfroundEvenSC[i][0], f, vfroundEvenSC[i][1]) + } + } +} + +func TestSignbit(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Signbit(vf[i]); signbit[i] != f { + t.Errorf("Signbit(%g) = %t, want %t", vf[i], f, signbit[i]) + } + } + for i := 0; i < len(vfsignbitSC); i++ { + if f := Signbit(vfsignbitSC[i]); signbitSC[i] != f { + t.Errorf("Signbit(%g) = %t, want %t", vfsignbitSC[i], f, signbitSC[i]) + } + } +} +func TestSin(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Sin(vf[i]); !veryclose(sin[i], f) { + t.Errorf("Sin(%g) = %g, want %g", vf[i], f, sin[i]) + } + } + for i := 0; i < len(vfsinSC); i++ { + if f := Sin(vfsinSC[i]); !alike(sinSC[i], f) { + t.Errorf("Sin(%g) = %g, want %g", vfsinSC[i], f, sinSC[i]) + } + } +} + +func TestSincos(t *testing.T) { + for i := 0; i < len(vf); i++ { + if s, c := Sincos(vf[i]); !veryclose(sin[i], s) || !veryclose(cos[i], c) { + t.Errorf("Sincos(%g) = %g, %g want %g, %g", vf[i], s, c, sin[i], cos[i]) + } + } +} + +func TestSinh(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Sinh(vf[i]); !close(sinh[i], f) { + t.Errorf("Sinh(%g) = %g, want %g", vf[i], f, sinh[i]) + } + } + for i := 0; i < len(vfsinhSC); i++ { + if f := Sinh(vfsinhSC[i]); !alike(sinhSC[i], f) { + t.Errorf("Sinh(%g) = %g, want %g", vfsinhSC[i], f, sinhSC[i]) + } + } +} + +func TestSqrt(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := SqrtGo(a); sqrt[i] != f { + t.Errorf("SqrtGo(%g) = %g, want %g", a, f, sqrt[i]) + } + a = Abs(vf[i]) + if f := Sqrt(a); sqrt[i] != f { + t.Errorf("Sqrt(%g) = %g, want %g", a, f, sqrt[i]) + } + } + for i := 0; i < len(vfsqrtSC); i++ { + if f := SqrtGo(vfsqrtSC[i]); !alike(sqrtSC[i], f) { + t.Errorf("SqrtGo(%g) = %g, want %g", vfsqrtSC[i], f, sqrtSC[i]) + } + if f := Sqrt(vfsqrtSC[i]); !alike(sqrtSC[i], f) { + t.Errorf("Sqrt(%g) = %g, want %g", vfsqrtSC[i], f, sqrtSC[i]) + } + } +} + +func TestTan(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Tan(vf[i]); !veryclose(tan[i], f) { + t.Errorf("Tan(%g) = %g, want %g", vf[i], f, tan[i]) + } + } + // same special cases as Sin + for i := 0; i < len(vfsinSC); i++ { + if f := Tan(vfsinSC[i]); !alike(sinSC[i], f) { + t.Errorf("Tan(%g) = %g, want %g", vfsinSC[i], f, sinSC[i]) + } + } +} + +func TestTanh(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Tanh(vf[i]); !veryclose(tanh[i], f) { + t.Errorf("Tanh(%g) = %g, want %g", vf[i], f, tanh[i]) + } + } + for i := 0; i < len(vftanhSC); i++ { + if f := Tanh(vftanhSC[i]); !alike(tanhSC[i], f) { + t.Errorf("Tanh(%g) = %g, want %g", vftanhSC[i], f, tanhSC[i]) + } + } +} + +func TestTrunc(t *testing.T) { + for i := 0; i < len(vf); i++ { + if f := Trunc(vf[i]); !alike(trunc[i], f) { + t.Errorf("Trunc(%g) = %g, want %g", vf[i], f, trunc[i]) + } + } + for i := 0; i < len(vfceilSC); i++ { + if f := Trunc(vfceilSC[i]); !alike(truncSC[i], f) { + t.Errorf("Trunc(%g) = %g, want %g", vfceilSC[i], f, truncSC[i]) + } + } +} + +func TestY0(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := Y0(a); !close(y0[i], f) { + t.Errorf("Y0(%g) = %g, want %g", a, f, y0[i]) + } + } + for i := 0; i < len(vfy0SC); i++ { + if f := Y0(vfy0SC[i]); !alike(y0SC[i], f) { + t.Errorf("Y0(%g) = %g, want %g", vfy0SC[i], f, y0SC[i]) + } + } +} + +func TestY1(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := Y1(a); !soclose(y1[i], f, 2e-14) { + t.Errorf("Y1(%g) = %g, want %g", a, f, y1[i]) + } + } + for i := 0; i < len(vfy0SC); i++ { + if f := Y1(vfy0SC[i]); !alike(y1SC[i], f) { + t.Errorf("Y1(%g) = %g, want %g", vfy0SC[i], f, y1SC[i]) + } + } +} + +func TestYn(t *testing.T) { + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := Yn(2, a); !close(y2[i], f) { + t.Errorf("Yn(2, %g) = %g, want %g", a, f, y2[i]) + } + if f := Yn(-3, a); !close(yM3[i], f) { + t.Errorf("Yn(-3, %g) = %g, want %g", a, f, yM3[i]) + } + } + for i := 0; i < len(vfy0SC); i++ { + if f := Yn(2, vfy0SC[i]); !alike(y2SC[i], f) { + t.Errorf("Yn(2, %g) = %g, want %g", vfy0SC[i], f, y2SC[i]) + } + if f := Yn(-3, vfy0SC[i]); !alike(yM3SC[i], f) { + t.Errorf("Yn(-3, %g) = %g, want %g", vfy0SC[i], f, yM3SC[i]) + } + } + if f := Yn(0, 0); !alike(Inf(-1), f) { + t.Errorf("Yn(0, 0) = %g, want %g", f, Inf(-1)) + } +} + +var PortableFMA = FMA // hide call from compiler intrinsic; falls back to portable code + +func TestFMA(t *testing.T) { + for _, c := range fmaC { + got := FMA(c.x, c.y, c.z) + if !alike(got, c.want) { + t.Errorf("FMA(%g,%g,%g) == %g; want %g", c.x, c.y, c.z, got, c.want) + } + got = PortableFMA(c.x, c.y, c.z) + if !alike(got, c.want) { + t.Errorf("PortableFMA(%g,%g,%g) == %g; want %g", c.x, c.y, c.z, got, c.want) + } + } +} + +//go:noinline +func fmsub(x, y, z float64) float64 { + return FMA(x, y, -z) +} + +//go:noinline +func fnmsub(x, y, z float64) float64 { + return FMA(-x, y, z) +} + +//go:noinline +func fnmadd(x, y, z float64) float64 { + return FMA(-x, y, -z) +} + +func TestFMANegativeArgs(t *testing.T) { + // Some architectures have instructions for fused multiply-subtract and + // also negated variants of fused multiply-add and subtract. This test + // aims to check that the optimizations that generate those instructions + // are applied correctly, if they exist. + for _, c := range fmaC { + want := PortableFMA(c.x, c.y, -c.z) + got := fmsub(c.x, c.y, c.z) + if !alike(got, want) { + t.Errorf("FMA(%g, %g, -(%g)) == %g, want %g", c.x, c.y, c.z, got, want) + } + want = PortableFMA(-c.x, c.y, c.z) + got = fnmsub(c.x, c.y, c.z) + if !alike(got, want) { + t.Errorf("FMA(-(%g), %g, %g) == %g, want %g", c.x, c.y, c.z, got, want) + } + want = PortableFMA(-c.x, c.y, -c.z) + got = fnmadd(c.x, c.y, c.z) + if !alike(got, want) { + t.Errorf("FMA(-(%g), %g, -(%g)) == %g, want %g", c.x, c.y, c.z, got, want) + } + } +} + +// Check that math functions of high angle values +// return accurate results. [Since (vf[i] + large) - large != vf[i], +// testing for Trig(vf[i] + large) == Trig(vf[i]), where large is +// a multiple of 2*Pi, is misleading.] +func TestLargeCos(t *testing.T) { + large := float64(100000 * Pi) + for i := 0; i < len(vf); i++ { + f1 := cosLarge[i] + f2 := Cos(vf[i] + large) + if !close(f1, f2) { + t.Errorf("Cos(%g) = %g, want %g", vf[i]+large, f2, f1) + } + } +} + +func TestLargeSin(t *testing.T) { + large := float64(100000 * Pi) + for i := 0; i < len(vf); i++ { + f1 := sinLarge[i] + f2 := Sin(vf[i] + large) + if !close(f1, f2) { + t.Errorf("Sin(%g) = %g, want %g", vf[i]+large, f2, f1) + } + } +} + +func TestLargeSincos(t *testing.T) { + large := float64(100000 * Pi) + for i := 0; i < len(vf); i++ { + f1, g1 := sinLarge[i], cosLarge[i] + f2, g2 := Sincos(vf[i] + large) + if !close(f1, f2) || !close(g1, g2) { + t.Errorf("Sincos(%g) = %g, %g, want %g, %g", vf[i]+large, f2, g2, f1, g1) + } + } +} + +func TestLargeTan(t *testing.T) { + large := float64(100000 * Pi) + for i := 0; i < len(vf); i++ { + f1 := tanLarge[i] + f2 := Tan(vf[i] + large) + if !close(f1, f2) { + t.Errorf("Tan(%g) = %g, want %g", vf[i]+large, f2, f1) + } + } +} + +// Check that trigReduce matches the standard reduction results for input values +// below reduceThreshold. +func TestTrigReduce(t *testing.T) { + inputs := make([]float64, len(vf)) + // all of the standard inputs + copy(inputs, vf) + // all of the large inputs + large := float64(100000 * Pi) + for _, v := range vf { + inputs = append(inputs, v+large) + } + // Also test some special inputs, Pi and right below the reduceThreshold + inputs = append(inputs, Pi, Nextafter(ReduceThreshold, 0)) + for _, x := range inputs { + // reduce the value to compare + j, z := TrigReduce(x) + xred := float64(j)*(Pi/4) + z + + if f, fred := Sin(x), Sin(xred); !close(f, fred) { + t.Errorf("Sin(trigReduce(%g)) != Sin(%g), got %g, want %g", x, x, fred, f) + } + if f, fred := Cos(x), Cos(xred); !close(f, fred) { + t.Errorf("Cos(trigReduce(%g)) != Cos(%g), got %g, want %g", x, x, fred, f) + } + if f, fred := Tan(x), Tan(xred); !close(f, fred) { + t.Errorf(" Tan(trigReduce(%g)) != Tan(%g), got %g, want %g", x, x, fred, f) + } + f, g := Sincos(x) + fred, gred := Sincos(xred) + if !close(f, fred) || !close(g, gred) { + t.Errorf(" Sincos(trigReduce(%g)) != Sincos(%g), got %g, %g, want %g, %g", x, x, fred, gred, f, g) + } + } +} + +// Check that math constants are accepted by compiler +// and have right value (assumes strconv.ParseFloat works). +// https://golang.org/issue/201 + +type floatTest struct { + val any + name string + str string +} + +var floatTests = []floatTest{ + {float64(MaxFloat64), "MaxFloat64", "1.7976931348623157e+308"}, + {float64(SmallestNonzeroFloat64), "SmallestNonzeroFloat64", "5e-324"}, + {float32(MaxFloat32), "MaxFloat32", "3.4028235e+38"}, + {float32(SmallestNonzeroFloat32), "SmallestNonzeroFloat32", "1e-45"}, +} + +func TestFloatMinMax(t *testing.T) { + for _, tt := range floatTests { + s := fmt.Sprint(tt.val) + if s != tt.str { + t.Errorf("Sprint(%v) = %s, want %s", tt.name, s, tt.str) + } + } +} + +func TestFloatMinima(t *testing.T) { + if q := float32(SmallestNonzeroFloat32 / 2); q != 0 { + t.Errorf("float32(SmallestNonzeroFloat32 / 2) = %g, want 0", q) + } + if q := float64(SmallestNonzeroFloat64 / 2); q != 0 { + t.Errorf("float64(SmallestNonzeroFloat64 / 2) = %g, want 0", q) + } +} + +var indirectSqrt = Sqrt + +// TestFloat32Sqrt checks the correctness of the float32 square root optimization result. +func TestFloat32Sqrt(t *testing.T) { + for _, v := range sqrt32 { + want := float32(indirectSqrt(float64(v))) + got := float32(Sqrt(float64(v))) + if IsNaN(float64(want)) { + if !IsNaN(float64(got)) { + t.Errorf("got=%#v want=NaN, v=%#v", got, v) + } + continue + } + if got != want { + t.Errorf("got=%#v want=%#v, v=%#v", got, want, v) + } + } +} + +// Benchmarks + +// Global exported variables are used to store the +// return values of functions measured in the benchmarks. +// Storing the results in these variables prevents the compiler +// from completely optimizing the benchmarked functions away. +var ( + GlobalI int + GlobalB bool + GlobalF float64 +) + +func BenchmarkAcos(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Acos(.5) + } + GlobalF = x +} + +func BenchmarkAcosh(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Acosh(1.5) + } + GlobalF = x +} + +func BenchmarkAsin(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Asin(.5) + } + GlobalF = x +} + +func BenchmarkAsinh(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Asinh(.5) + } + GlobalF = x +} + +func BenchmarkAtan(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Atan(.5) + } + GlobalF = x +} + +func BenchmarkAtanh(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Atanh(.5) + } + GlobalF = x +} + +func BenchmarkAtan2(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Atan2(.5, 1) + } + GlobalF = x +} + +func BenchmarkCbrt(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Cbrt(10) + } + GlobalF = x +} + +func BenchmarkCeil(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Ceil(.5) + } + GlobalF = x +} + +var copysignNeg = -1.0 + +func BenchmarkCopysign(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Copysign(.5, copysignNeg) + } + GlobalF = x +} + +func BenchmarkCos(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Cos(.5) + } + GlobalF = x +} + +func BenchmarkCosh(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Cosh(2.5) + } + GlobalF = x +} + +func BenchmarkErf(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Erf(.5) + } + GlobalF = x +} + +func BenchmarkErfc(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Erfc(.5) + } + GlobalF = x +} + +func BenchmarkErfinv(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Erfinv(.5) + } + GlobalF = x +} + +func BenchmarkErfcinv(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Erfcinv(.5) + } + GlobalF = x +} + +func BenchmarkExp(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Exp(.5) + } + GlobalF = x +} + +func BenchmarkExpGo(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = ExpGo(.5) + } + GlobalF = x +} + +func BenchmarkExpm1(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Expm1(.5) + } + GlobalF = x +} + +func BenchmarkExp2(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Exp2(.5) + } + GlobalF = x +} + +func BenchmarkExp2Go(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Exp2Go(.5) + } + GlobalF = x +} + +var absPos = .5 + +func BenchmarkAbs(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Abs(absPos) + } + GlobalF = x + +} + +func BenchmarkDim(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Dim(GlobalF, x) + } + GlobalF = x +} + +func BenchmarkFloor(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Floor(.5) + } + GlobalF = x +} + +func BenchmarkMax(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Max(10, 3) + } + GlobalF = x +} + +func BenchmarkMin(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Min(10, 3) + } + GlobalF = x +} + +func BenchmarkMod(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Mod(10, 3) + } + GlobalF = x +} + +func BenchmarkFrexp(b *testing.B) { + x := 0.0 + y := 0 + for i := 0; i < b.N; i++ { + x, y = Frexp(8) + } + GlobalF = x + GlobalI = y +} + +func BenchmarkGamma(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Gamma(2.5) + } + GlobalF = x +} + +func BenchmarkHypot(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Hypot(3, 4) + } + GlobalF = x +} + +func BenchmarkHypotGo(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = HypotGo(3, 4) + } + GlobalF = x +} + +func BenchmarkIlogb(b *testing.B) { + x := 0 + for i := 0; i < b.N; i++ { + x = Ilogb(.5) + } + GlobalI = x +} + +func BenchmarkJ0(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = J0(2.5) + } + GlobalF = x +} + +func BenchmarkJ1(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = J1(2.5) + } + GlobalF = x +} + +func BenchmarkJn(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Jn(2, 2.5) + } + GlobalF = x +} + +func BenchmarkLdexp(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Ldexp(.5, 2) + } + GlobalF = x +} + +func BenchmarkLgamma(b *testing.B) { + x := 0.0 + y := 0 + for i := 0; i < b.N; i++ { + x, y = Lgamma(2.5) + } + GlobalF = x + GlobalI = y +} + +func BenchmarkLog(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Log(.5) + } + GlobalF = x +} + +func BenchmarkLogb(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Logb(.5) + } + GlobalF = x +} + +func BenchmarkLog1p(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Log1p(.5) + } + GlobalF = x +} + +func BenchmarkLog10(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Log10(.5) + } + GlobalF = x +} + +func BenchmarkLog2(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Log2(.5) + } + GlobalF += x +} + +func BenchmarkModf(b *testing.B) { + x := 0.0 + y := 0.0 + for i := 0; i < b.N; i++ { + x, y = Modf(1.5) + } + GlobalF += x + GlobalF += y +} + +func BenchmarkNextafter32(b *testing.B) { + x := float32(0.0) + for i := 0; i < b.N; i++ { + x = Nextafter32(.5, 1) + } + GlobalF = float64(x) +} + +func BenchmarkNextafter64(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Nextafter(.5, 1) + } + GlobalF = x +} + +func BenchmarkPowInt(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Pow(2, 2) + } + GlobalF = x +} + +func BenchmarkPowFrac(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Pow(2.5, 1.5) + } + GlobalF = x +} + +var pow10pos = int(300) + +func BenchmarkPow10Pos(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Pow10(pow10pos) + } + GlobalF = x +} + +var pow10neg = int(-300) + +func BenchmarkPow10Neg(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Pow10(pow10neg) + } + GlobalF = x +} + +var roundNeg = float64(-2.5) + +func BenchmarkRound(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Round(roundNeg) + } + GlobalF = x +} + +func BenchmarkRoundToEven(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = RoundToEven(roundNeg) + } + GlobalF = x +} + +func BenchmarkRemainder(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Remainder(10, 3) + } + GlobalF = x +} + +var signbitPos = 2.5 + +func BenchmarkSignbit(b *testing.B) { + x := false + for i := 0; i < b.N; i++ { + x = Signbit(signbitPos) + } + GlobalB = x +} + +func BenchmarkSin(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Sin(.5) + } + GlobalF = x +} + +func BenchmarkSincos(b *testing.B) { + x := 0.0 + y := 0.0 + for i := 0; i < b.N; i++ { + x, y = Sincos(.5) + } + GlobalF += x + GlobalF += y +} + +func BenchmarkSinh(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Sinh(2.5) + } + GlobalF = x +} + +func BenchmarkSqrtIndirect(b *testing.B) { + x, y := 0.0, 10.0 + f := Sqrt + for i := 0; i < b.N; i++ { + x += f(y) + } + GlobalF = x +} + +func BenchmarkSqrtLatency(b *testing.B) { + x := 10.0 + for i := 0; i < b.N; i++ { + x = Sqrt(x) + } + GlobalF = x +} + +func BenchmarkSqrtIndirectLatency(b *testing.B) { + x := 10.0 + f := Sqrt + for i := 0; i < b.N; i++ { + x = f(x) + } + GlobalF = x +} + +func BenchmarkSqrtGoLatency(b *testing.B) { + x := 10.0 + for i := 0; i < b.N; i++ { + x = SqrtGo(x) + } + GlobalF = x +} + +func isPrime(i int) bool { + // Yes, this is a dumb way to write this code, + // but calling Sqrt repeatedly in this way demonstrates + // the benefit of using a direct SQRT instruction on systems + // that have one, whereas the obvious loop seems not to + // demonstrate such a benefit. + for j := 2; float64(j) <= Sqrt(float64(i)); j++ { + if i%j == 0 { + return false + } + } + return true +} + +func BenchmarkSqrtPrime(b *testing.B) { + x := false + for i := 0; i < b.N; i++ { + x = isPrime(100003) + } + GlobalB = x +} + +func BenchmarkTan(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Tan(.5) + } + GlobalF = x +} + +func BenchmarkTanh(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Tanh(2.5) + } + GlobalF = x +} +func BenchmarkTrunc(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Trunc(.5) + } + GlobalF = x +} + +func BenchmarkY0(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Y0(2.5) + } + GlobalF = x +} + +func BenchmarkY1(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Y1(2.5) + } + GlobalF = x +} + +func BenchmarkYn(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Yn(2, 2.5) + } + GlobalF = x +} + +func BenchmarkFloat64bits(b *testing.B) { + y := uint64(0) + for i := 0; i < b.N; i++ { + y = Float64bits(roundNeg) + } + GlobalI = int(y) +} + +var roundUint64 = uint64(5) + +func BenchmarkFloat64frombits(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = Float64frombits(roundUint64) + } + GlobalF = x +} + +var roundFloat32 = float32(-2.5) + +func BenchmarkFloat32bits(b *testing.B) { + y := uint32(0) + for i := 0; i < b.N; i++ { + y = Float32bits(roundFloat32) + } + GlobalI = int(y) +} + +var roundUint32 = uint32(5) + +func BenchmarkFloat32frombits(b *testing.B) { + x := float32(0.0) + for i := 0; i < b.N; i++ { + x = Float32frombits(roundUint32) + } + GlobalF = float64(x) +} + +func BenchmarkFMA(b *testing.B) { + x := 0.0 + for i := 0; i < b.N; i++ { + x = FMA(E, Pi, x) + } + GlobalF = x +} diff --git a/go/src/math/arith_s390x.go b/go/src/math/arith_s390x.go new file mode 100644 index 0000000000000000000000000000000000000000..2fda82fff4e8f6111f9406933f973e1bb86c8c9b --- /dev/null +++ b/go/src/math/arith_s390x.go @@ -0,0 +1,170 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +import "internal/cpu" + +func expTrampolineSetup(x float64) float64 +func expAsm(x float64) float64 + +func logTrampolineSetup(x float64) float64 +func logAsm(x float64) float64 + +// Below here all functions are grouped in stubs.go for other +// architectures. + +const haveArchLog10 = true + +func archLog10(x float64) float64 +func log10TrampolineSetup(x float64) float64 +func log10Asm(x float64) float64 + +const haveArchCos = true + +func archCos(x float64) float64 +func cosTrampolineSetup(x float64) float64 +func cosAsm(x float64) float64 + +const haveArchCosh = true + +func archCosh(x float64) float64 +func coshTrampolineSetup(x float64) float64 +func coshAsm(x float64) float64 + +const haveArchSin = true + +func archSin(x float64) float64 +func sinTrampolineSetup(x float64) float64 +func sinAsm(x float64) float64 + +const haveArchSinh = true + +func archSinh(x float64) float64 +func sinhTrampolineSetup(x float64) float64 +func sinhAsm(x float64) float64 + +const haveArchTanh = true + +func archTanh(x float64) float64 +func tanhTrampolineSetup(x float64) float64 +func tanhAsm(x float64) float64 + +const haveArchLog1p = true + +func archLog1p(x float64) float64 +func log1pTrampolineSetup(x float64) float64 +func log1pAsm(x float64) float64 + +const haveArchAtanh = true + +func archAtanh(x float64) float64 +func atanhTrampolineSetup(x float64) float64 +func atanhAsm(x float64) float64 + +const haveArchAcos = true + +func archAcos(x float64) float64 +func acosTrampolineSetup(x float64) float64 +func acosAsm(x float64) float64 + +const haveArchAcosh = true + +func archAcosh(x float64) float64 +func acoshTrampolineSetup(x float64) float64 +func acoshAsm(x float64) float64 + +const haveArchAsin = true + +func archAsin(x float64) float64 +func asinTrampolineSetup(x float64) float64 +func asinAsm(x float64) float64 + +const haveArchAsinh = true + +func archAsinh(x float64) float64 +func asinhTrampolineSetup(x float64) float64 +func asinhAsm(x float64) float64 + +const haveArchErf = true + +func archErf(x float64) float64 +func erfTrampolineSetup(x float64) float64 +func erfAsm(x float64) float64 + +const haveArchErfc = true + +func archErfc(x float64) float64 +func erfcTrampolineSetup(x float64) float64 +func erfcAsm(x float64) float64 + +const haveArchAtan = true + +func archAtan(x float64) float64 +func atanTrampolineSetup(x float64) float64 +func atanAsm(x float64) float64 + +const haveArchAtan2 = true + +func archAtan2(y, x float64) float64 +func atan2TrampolineSetup(x, y float64) float64 +func atan2Asm(x, y float64) float64 + +const haveArchCbrt = true + +func archCbrt(x float64) float64 +func cbrtTrampolineSetup(x float64) float64 +func cbrtAsm(x float64) float64 + +const haveArchTan = true + +func archTan(x float64) float64 +func tanTrampolineSetup(x float64) float64 +func tanAsm(x float64) float64 + +const haveArchExpm1 = true + +func archExpm1(x float64) float64 +func expm1TrampolineSetup(x float64) float64 +func expm1Asm(x float64) float64 + +const haveArchPow = false + +func archPow(x, y float64) float64 +func powTrampolineSetup(x, y float64) float64 +func powAsm(x, y float64) float64 + +const haveArchFrexp = false + +func archFrexp(x float64) (float64, int) { + panic("not implemented") +} + +const haveArchLdexp = false + +func archLdexp(frac float64, exp int) float64 { + panic("not implemented") +} + +const haveArchLog2 = false + +func archLog2(x float64) float64 { + panic("not implemented") +} + +const haveArchMod = false + +func archMod(x, y float64) float64 { + panic("not implemented") +} + +const haveArchRemainder = false + +func archRemainder(x, y float64) float64 { + panic("not implemented") +} + +// hasVX reports whether the machine has the z/Architecture +// vector facility installed and enabled. +var hasVX = cpu.S390X.HasVX diff --git a/go/src/math/arith_s390x_test.go b/go/src/math/arith_s390x_test.go new file mode 100644 index 0000000000000000000000000000000000000000..cfbc7b7823a93c3a3ae7457607c13e1b4f5ce640 --- /dev/null +++ b/go/src/math/arith_s390x_test.go @@ -0,0 +1,442 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests whether the non vector routines are working, even when the tests are run on a +// vector-capable machine. +package math_test + +import ( + . "math" + "testing" +) + +func TestCosNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := CosNoVec(vf[i]); !veryclose(cos[i], f) { + t.Errorf("Cos(%g) = %g, want %g", vf[i], f, cos[i]) + } + } + for i := 0; i < len(vfcosSC); i++ { + if f := CosNoVec(vfcosSC[i]); !alike(cosSC[i], f) { + t.Errorf("Cos(%g) = %g, want %g", vfcosSC[i], f, cosSC[i]) + } + } +} + +func TestCoshNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := CoshNoVec(vf[i]); !close(cosh[i], f) { + t.Errorf("Cosh(%g) = %g, want %g", vf[i], f, cosh[i]) + } + } + for i := 0; i < len(vfcoshSC); i++ { + if f := CoshNoVec(vfcoshSC[i]); !alike(coshSC[i], f) { + t.Errorf("Cosh(%g) = %g, want %g", vfcoshSC[i], f, coshSC[i]) + } + } +} +func TestSinNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := SinNoVec(vf[i]); !veryclose(sin[i], f) { + t.Errorf("Sin(%g) = %g, want %g", vf[i], f, sin[i]) + } + } + for i := 0; i < len(vfsinSC); i++ { + if f := SinNoVec(vfsinSC[i]); !alike(sinSC[i], f) { + t.Errorf("Sin(%g) = %g, want %g", vfsinSC[i], f, sinSC[i]) + } + } +} + +func TestSinhNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := SinhNoVec(vf[i]); !close(sinh[i], f) { + t.Errorf("Sinh(%g) = %g, want %g", vf[i], f, sinh[i]) + } + } + for i := 0; i < len(vfsinhSC); i++ { + if f := SinhNoVec(vfsinhSC[i]); !alike(sinhSC[i], f) { + t.Errorf("Sinh(%g) = %g, want %g", vfsinhSC[i], f, sinhSC[i]) + } + } +} + +// Check that math functions of high angle values +// return accurate results. [Since (vf[i] + large) - large != vf[i], +// testing for Trig(vf[i] + large) == Trig(vf[i]), where large is +// a multiple of 2*Pi, is misleading.] +func TestLargeCosNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + large := float64(100000 * Pi) + for i := 0; i < len(vf); i++ { + f1 := cosLarge[i] + f2 := CosNoVec(vf[i] + large) + if !close(f1, f2) { + t.Errorf("Cos(%g) = %g, want %g", vf[i]+large, f2, f1) + } + } +} + +func TestLargeSinNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + large := float64(100000 * Pi) + for i := 0; i < len(vf); i++ { + f1 := sinLarge[i] + f2 := SinNoVec(vf[i] + large) + if !close(f1, f2) { + t.Errorf("Sin(%g) = %g, want %g", vf[i]+large, f2, f1) + } + } +} + +func TestLargeTanNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + large := float64(100000 * Pi) + for i := 0; i < len(vf); i++ { + f1 := tanLarge[i] + f2 := TanNovec(vf[i] + large) + if !close(f1, f2) { + t.Errorf("Tan(%g) = %g, want %g", vf[i]+large, f2, f1) + } + } +} + +func TestTanNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := TanNovec(vf[i]); !veryclose(tan[i], f) { + t.Errorf("Tan(%g) = %g, want %g", vf[i], f, tan[i]) + } + } + // same special cases as Sin + for i := 0; i < len(vfsinSC); i++ { + if f := TanNovec(vfsinSC[i]); !alike(sinSC[i], f) { + t.Errorf("Tan(%g) = %g, want %g", vfsinSC[i], f, sinSC[i]) + } + } +} + +func TestTanhNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := TanhNoVec(vf[i]); !veryclose(tanh[i], f) { + t.Errorf("Tanh(%g) = %g, want %g", vf[i], f, tanh[i]) + } + } + for i := 0; i < len(vftanhSC); i++ { + if f := TanhNoVec(vftanhSC[i]); !alike(tanhSC[i], f) { + t.Errorf("Tanh(%g) = %g, want %g", vftanhSC[i], f, tanhSC[i]) + } + } + +} + +func TestLog10Novec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := Log10NoVec(a); !veryclose(log10[i], f) { + t.Errorf("Log10(%g) = %g, want %g", a, f, log10[i]) + } + } + if f := Log10NoVec(E); f != Log10E { + t.Errorf("Log10(%g) = %g, want %g", E, f, Log10E) + } + for i := 0; i < len(vflogSC); i++ { + if f := Log10NoVec(vflogSC[i]); !alike(logSC[i], f) { + t.Errorf("Log10(%g) = %g, want %g", vflogSC[i], f, logSC[i]) + } + } +} + +func TestLog1pNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := vf[i] / 100 + if f := Log1pNovec(a); !veryclose(log1p[i], f) { + t.Errorf("Log1p(%g) = %g, want %g", a, f, log1p[i]) + } + } + a := 9.0 + if f := Log1pNovec(a); f != Ln10 { + t.Errorf("Log1p(%g) = %g, want %g", a, f, Ln10) + } + for i := 0; i < len(vflogSC); i++ { + if f := Log1pNovec(vflog1pSC[i]); !alike(log1pSC[i], f) { + t.Errorf("Log1p(%g) = %g, want %g", vflog1pSC[i], f, log1pSC[i]) + } + } +} + +func TestAtanhNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := AtanhNovec(a); !veryclose(atanh[i], f) { + t.Errorf("Atanh(%g) = %g, want %g", a, f, atanh[i]) + } + } + for i := 0; i < len(vfatanhSC); i++ { + if f := AtanhNovec(vfatanhSC[i]); !alike(atanhSC[i], f) { + t.Errorf("Atanh(%g) = %g, want %g", vfatanhSC[i], f, atanhSC[i]) + } + } +} + +func TestAcosNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := AcosNovec(a); !close(acos[i], f) { + t.Errorf("Acos(%g) = %g, want %g", a, f, acos[i]) + } + } + for i := 0; i < len(vfacosSC); i++ { + if f := AcosNovec(vfacosSC[i]); !alike(acosSC[i], f) { + t.Errorf("Acos(%g) = %g, want %g", vfacosSC[i], f, acosSC[i]) + } + } +} + +func TestAsinNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := AsinNovec(a); !veryclose(asin[i], f) { + t.Errorf("Asin(%g) = %g, want %g", a, f, asin[i]) + } + } + for i := 0; i < len(vfasinSC); i++ { + if f := AsinNovec(vfasinSC[i]); !alike(asinSC[i], f) { + t.Errorf("Asin(%g) = %g, want %g", vfasinSC[i], f, asinSC[i]) + } + } +} + +func TestAcoshNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := 1 + Abs(vf[i]) + if f := AcoshNovec(a); !veryclose(acosh[i], f) { + t.Errorf("Acosh(%g) = %g, want %g", a, f, acosh[i]) + } + } + for i := 0; i < len(vfacoshSC); i++ { + if f := AcoshNovec(vfacoshSC[i]); !alike(acoshSC[i], f) { + t.Errorf("Acosh(%g) = %g, want %g", vfacoshSC[i], f, acoshSC[i]) + } + } +} + +func TestAsinhNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := AsinhNovec(vf[i]); !veryclose(asinh[i], f) { + t.Errorf("Asinh(%g) = %g, want %g", vf[i], f, asinh[i]) + } + } + for i := 0; i < len(vfasinhSC); i++ { + if f := AsinhNovec(vfasinhSC[i]); !alike(asinhSC[i], f) { + t.Errorf("Asinh(%g) = %g, want %g", vfasinhSC[i], f, asinhSC[i]) + } + } +} + +func TestErfNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := ErfNovec(a); !veryclose(erf[i], f) { + t.Errorf("Erf(%g) = %g, want %g", a, f, erf[i]) + } + } + for i := 0; i < len(vferfSC); i++ { + if f := ErfNovec(vferfSC[i]); !alike(erfSC[i], f) { + t.Errorf("Erf(%g) = %g, want %g", vferfSC[i], f, erfSC[i]) + } + } +} + +func TestErfcNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := vf[i] / 10 + if f := ErfcNovec(a); !veryclose(erfc[i], f) { + t.Errorf("Erfc(%g) = %g, want %g", a, f, erfc[i]) + } + } + for i := 0; i < len(vferfcSC); i++ { + if f := ErfcNovec(vferfcSC[i]); !alike(erfcSC[i], f) { + t.Errorf("Erfc(%g) = %g, want %g", vferfcSC[i], f, erfcSC[i]) + } + } +} + +func TestAtanNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := AtanNovec(vf[i]); !veryclose(atan[i], f) { + t.Errorf("Atan(%g) = %g, want %g", vf[i], f, atan[i]) + } + } + for i := 0; i < len(vfatanSC); i++ { + if f := AtanNovec(vfatanSC[i]); !alike(atanSC[i], f) { + t.Errorf("Atan(%g) = %g, want %g", vfatanSC[i], f, atanSC[i]) + } + } +} + +func TestAtan2Novec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := Atan2Novec(10, vf[i]); !veryclose(atan2[i], f) { + t.Errorf("Atan2(10, %g) = %g, want %g", vf[i], f, atan2[i]) + } + } + for i := 0; i < len(vfatan2SC); i++ { + if f := Atan2Novec(vfatan2SC[i][0], vfatan2SC[i][1]); !alike(atan2SC[i], f) { + t.Errorf("Atan2(%g, %g) = %g, want %g", vfatan2SC[i][0], vfatan2SC[i][1], f, atan2SC[i]) + } + } +} + +func TestCbrtNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := CbrtNovec(vf[i]); !veryclose(cbrt[i], f) { + t.Errorf("Cbrt(%g) = %g, want %g", vf[i], f, cbrt[i]) + } + } + for i := 0; i < len(vfcbrtSC); i++ { + if f := CbrtNovec(vfcbrtSC[i]); !alike(cbrtSC[i], f) { + t.Errorf("Cbrt(%g) = %g, want %g", vfcbrtSC[i], f, cbrtSC[i]) + } + } +} + +func TestLogNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := Abs(vf[i]) + if f := LogNovec(a); log[i] != f { + t.Errorf("Log(%g) = %g, want %g", a, f, log[i]) + } + } + if f := LogNovec(10); f != Ln10 { + t.Errorf("Log(%g) = %g, want %g", 10.0, f, Ln10) + } + for i := 0; i < len(vflogSC); i++ { + if f := LogNovec(vflogSC[i]); !alike(logSC[i], f) { + t.Errorf("Log(%g) = %g, want %g", vflogSC[i], f, logSC[i]) + } + } +} + +func TestExpNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + testExpNovec(t, Exp, "Exp") + testExpNovec(t, ExpGo, "ExpGo") +} + +func testExpNovec(t *testing.T, Exp func(float64) float64, name string) { + for i := 0; i < len(vf); i++ { + if f := ExpNovec(vf[i]); !veryclose(exp[i], f) { + t.Errorf("%s(%g) = %g, want %g", name, vf[i], f, exp[i]) + } + } + for i := 0; i < len(vfexpSC); i++ { + if f := ExpNovec(vfexpSC[i]); !alike(expSC[i], f) { + t.Errorf("%s(%g) = %g, want %g", name, vfexpSC[i], f, expSC[i]) + } + } +} + +func TestExpm1Novec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + a := vf[i] / 100 + if f := Expm1Novec(a); !veryclose(expm1[i], f) { + t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1[i]) + } + } + for i := 0; i < len(vf); i++ { + a := vf[i] * 10 + if f := Expm1Novec(a); !close(expm1Large[i], f) { + t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1Large[i]) + } + } + for i := 0; i < len(vfexpm1SC); i++ { + if f := Expm1Novec(vfexpm1SC[i]); !alike(expm1SC[i], f) { + t.Errorf("Expm1(%g) = %g, want %g", vfexpm1SC[i], f, expm1SC[i]) + } + } +} + +func TestPowNovec(t *testing.T) { + if !HasVX { + t.Skipf("no vector support") + } + for i := 0; i < len(vf); i++ { + if f := PowNovec(10, vf[i]); !close(pow[i], f) { + t.Errorf("Pow(10, %g) = %g, want %g", vf[i], f, pow[i]) + } + } + for i := 0; i < len(vfpowSC); i++ { + if f := PowNovec(vfpowSC[i][0], vfpowSC[i][1]); !alike(powSC[i], f) { + t.Errorf("Pow(%g, %g) = %g, want %g", vfpowSC[i][0], vfpowSC[i][1], f, powSC[i]) + } + } +} diff --git a/go/src/math/asin.go b/go/src/math/asin.go new file mode 100644 index 0000000000000000000000000000000000000000..8e1b2ab4916ed13202df297981a0346b6a51277a --- /dev/null +++ b/go/src/math/asin.go @@ -0,0 +1,67 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point arcsine and arccosine. + + They are implemented by computing the arctangent + after appropriate range reduction. +*/ + +// Asin returns the arcsine, in radians, of x. +// +// Special cases are: +// +// Asin(±0) = ±0 +// Asin(x) = NaN if x < -1 or x > 1 +func Asin(x float64) float64 { + if haveArchAsin { + return archAsin(x) + } + return asin(x) +} + +func asin(x float64) float64 { + if x == 0 { + return x // special case + } + sign := false + if x < 0 { + x = -x + sign = true + } + if x > 1 { + return NaN() // special case + } + + temp := Sqrt(1 - x*x) + if x > 0.7 { + temp = Pi/2 - satan(temp/x) + } else { + temp = satan(x / temp) + } + + if sign { + temp = -temp + } + return temp +} + +// Acos returns the arccosine, in radians, of x. +// +// Special case is: +// +// Acos(x) = NaN if x < -1 or x > 1 +func Acos(x float64) float64 { + if haveArchAcos { + return archAcos(x) + } + return acos(x) +} + +func acos(x float64) float64 { + return Pi/2 - Asin(x) +} diff --git a/go/src/math/asin_s390x.s b/go/src/math/asin_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..e5887c9bea3336a1f1695c222377a9aa290248f4 --- /dev/null +++ b/go/src/math/asin_s390x.s @@ -0,0 +1,162 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·asinrodataL15<> + 0(SB)/8, $-1.309611320495605469 +DATA ·asinrodataL15<> + 8(SB)/8, $0x3ff921fb54442d18 +DATA ·asinrodataL15<> + 16(SB)/8, $0xbff921fb54442d18 +DATA ·asinrodataL15<> + 24(SB)/8, $1.309611320495605469 +DATA ·asinrodataL15<> + 32(SB)/8, $-0.0 +DATA ·asinrodataL15<> + 40(SB)/8, $1.199437040755305217 +DATA ·asinrodataL15<> + 48(SB)/8, $0.166666666666651626E+00 +DATA ·asinrodataL15<> + 56(SB)/8, $0.750000000042621169E-01 +DATA ·asinrodataL15<> + 64(SB)/8, $0.446428567178116477E-01 +DATA ·asinrodataL15<> + 72(SB)/8, $0.303819660378071894E-01 +DATA ·asinrodataL15<> + 80(SB)/8, $0.223715011892010405E-01 +DATA ·asinrodataL15<> + 88(SB)/8, $0.173659424522364952E-01 +DATA ·asinrodataL15<> + 96(SB)/8, $0.137810186504372266E-01 +DATA ·asinrodataL15<> + 104(SB)/8, $0.134066870961173521E-01 +DATA ·asinrodataL15<> + 112(SB)/8, $-.412335502831898721E-02 +DATA ·asinrodataL15<> + 120(SB)/8, $0.867383739532082719E-01 +DATA ·asinrodataL15<> + 128(SB)/8, $-.328765950607171649E+00 +DATA ·asinrodataL15<> + 136(SB)/8, $0.110401073869414626E+01 +DATA ·asinrodataL15<> + 144(SB)/8, $-.270694366992537307E+01 +DATA ·asinrodataL15<> + 152(SB)/8, $0.500196500770928669E+01 +DATA ·asinrodataL15<> + 160(SB)/8, $-.665866959108585165E+01 +DATA ·asinrodataL15<> + 168(SB)/8, $-.344895269334086578E+01 +DATA ·asinrodataL15<> + 176(SB)/8, $0.927437952918301659E+00 +DATA ·asinrodataL15<> + 184(SB)/8, $0.610487478874645653E+01 +DATA ·asinrodataL15<> + 192(SB)/8, $0x7ff8000000000000 //+Inf +DATA ·asinrodataL15<> + 200(SB)/8, $-1.0 +DATA ·asinrodataL15<> + 208(SB)/8, $1.0 +DATA ·asinrodataL15<> + 216(SB)/8, $1.00000000000000000e-20 +GLOBL ·asinrodataL15<> + 0(SB), RODATA, $224 + +// Asin returns the arcsine, in radians, of the argument. +// +// Special cases are: +// Asin(±0) = ±0= +// Asin(x) = NaN if x < -1 or x > 1 +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·asinAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·asinrodataL15<>+0(SB), R9 + LGDR F0, R7 + FMOVD F0, F8 + SRAD $32, R7 + WORD $0xC0193FE6 //iilf %r1,1072079005 + BYTE $0xA0 + BYTE $0x9D + WORD $0xB91700C7 //llgtr %r12,%r7 + MOVW R12, R8 + MOVW R1, R6 + CMPBGT R8, R6, L2 + WORD $0xC0193BFF //iilf %r1,1006632959 + BYTE $0xFF + BYTE $0xFF + MOVW R1, R6 + CMPBGT R8, R6, L13 +L3: + FMOVD 216(R9), F0 + FMADD F0, F8, F8 +L1: + FMOVD F8, ret+8(FP) + RET +L2: + WORD $0xC0193FEF //iilf %r1,1072693247 + BYTE $0xFF + BYTE $0xFF + CMPW R12, R1 + BLE L14 +L5: + WORD $0xED0090D0 //cdb %f0,.L17-.L15(%r9) + BYTE $0x00 + BYTE $0x19 + BEQ L9 + WORD $0xED0090C8 //cdb %f0,.L18-.L15(%r9) + BYTE $0x00 + BYTE $0x19 + BEQ L10 + WFCEDBS V8, V8, V0 + BVS L1 + FMOVD 192(R9), F8 + BR L1 +L13: + WFMDB V0, V0, V10 +L4: + WFMDB V10, V10, V0 + FMOVD 184(R9), F6 + FMOVD 176(R9), F2 + FMOVD 168(R9), F4 + WFMADB V0, V2, V6, V2 + FMOVD 160(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 152(R9), F6 + WFMADB V0, V2, V6, V2 + FMOVD 144(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 136(R9), F6 + WFMADB V0, V2, V6, V2 + WORD $0xC0193FE6 //iilf %r1,1072079005 + BYTE $0xA0 + BYTE $0x9D + FMOVD 128(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 120(R9), F6 + WFMADB V0, V2, V6, V2 + FMOVD 112(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 104(R9), F6 + WFMADB V0, V2, V6, V2 + FMOVD 96(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 88(R9), F6 + WFMADB V0, V2, V6, V2 + FMOVD 80(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 72(R9), F6 + WFMADB V0, V2, V6, V2 + FMOVD 64(R9), F6 + WFMADB V0, V4, V6, V4 + FMOVD 56(R9), F6 + WFMADB V0, V2, V6, V2 + FMOVD 48(R9), F6 + WFMADB V0, V4, V6, V0 + WFMDB V8, V10, V4 + FMADD F2, F10, F0 + FMADD F0, F4, F8 + CMPW R12, R1 + BLE L1 + FMOVD 40(R9), F0 + FMADD F0, F1, F8 + FMOVD F8, ret+8(FP) + RET +L14: + FMOVD 200(R9), F0 + FMADD F8, F8, F0 + LCDBR F0, F10 + WORD $0xED009020 //cdb %f0,.L39-.L15(%r9) + BYTE $0x00 + BYTE $0x19 + FSQRT F10, F8 +L6: + MOVW R7, R6 + CMPBLE R6, $0, L8 + LCDBR F8, F8 + FMOVD 24(R9), F1 + BR L4 +L10: + FMOVD 16(R9), F8 + BR L1 +L9: + FMOVD 8(R9), F8 + FMOVD F8, ret+8(FP) + RET +L8: + FMOVD 0(R9), F1 + BR L4 diff --git a/go/src/math/asinh.go b/go/src/math/asinh.go new file mode 100644 index 0000000000000000000000000000000000000000..d913239d1e2c681f34005f527e301a5bcdbbe8e4 --- /dev/null +++ b/go/src/math/asinh.go @@ -0,0 +1,77 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/s_asinh.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// asinh(x) +// Method : +// Based on +// asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] +// we have +// asinh(x) := x if 1+x*x=1, +// := sign(x)*(log(x)+ln2) for large |x|, else +// := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else +// := sign(x)*log1p(|x| + x**2/(1 + sqrt(1+x**2))) +// + +// Asinh returns the inverse hyperbolic sine of x. +// +// Special cases are: +// +// Asinh(±0) = ±0 +// Asinh(±Inf) = ±Inf +// Asinh(NaN) = NaN +func Asinh(x float64) float64 { + if haveArchAsinh { + return archAsinh(x) + } + return asinh(x) +} + +func asinh(x float64) float64 { + const ( + Ln2 = 6.93147180559945286227e-01 // 0x3FE62E42FEFA39EF + NearZero = 1.0 / (1 << 28) // 2**-28 + Large = 1 << 28 // 2**28 + ) + // special cases + if IsNaN(x) || IsInf(x, 0) { + return x + } + sign := false + if x < 0 { + x = -x + sign = true + } + var temp float64 + switch { + case x > Large: + temp = Log(x) + Ln2 // |x| > 2**28 + case x > 2: + temp = Log(2*x + 1/(Sqrt(x*x+1)+x)) // 2**28 > |x| > 2.0 + case x < NearZero: + temp = x // |x| < 2**-28 + default: + temp = Log1p(x + x*x/(1+Sqrt(1+x*x))) // 2.0 > |x| > 2**-28 + } + if sign { + temp = -temp + } + return temp +} diff --git a/go/src/math/asinh_s390x.s b/go/src/math/asinh_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..94081d3b15ce0517793cb1ec97cb8db9db98bad5 --- /dev/null +++ b/go/src/math/asinh_s390x.s @@ -0,0 +1,213 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·asinhrodataL18<> + 0(SB)/8, $0.749999999977387502E-01 +DATA ·asinhrodataL18<> + 8(SB)/8, $-.166666666666657082E+00 +DATA ·asinhrodataL18<> + 16(SB)/8, $0.303819368237360639E-01 +DATA ·asinhrodataL18<> + 24(SB)/8, $-.446428569571752982E-01 +DATA ·asinhrodataL18<> + 32(SB)/8, $0.173500047922695924E-01 +DATA ·asinhrodataL18<> + 40(SB)/8, $-.223719767210027185E-01 +DATA ·asinhrodataL18<> + 48(SB)/8, $0.113655037946822130E-01 +DATA ·asinhrodataL18<> + 56(SB)/8, $0.579747490622448943E-02 +DATA ·asinhrodataL18<> + 64(SB)/8, $-.139372433914359122E-01 +DATA ·asinhrodataL18<> + 72(SB)/8, $-.218674325255800840E-02 +DATA ·asinhrodataL18<> + 80(SB)/8, $-.891074277756961157E-02 +DATA ·asinhrodataL18<> + 88(SB)/8, $.41375273347623353626 +DATA ·asinhrodataL18<> + 96(SB)/8, $.51487302528619766235E+04 +DATA ·asinhrodataL18<> + 104(SB)/8, $-1.67526912689208984375 +DATA ·asinhrodataL18<> + 112(SB)/8, $0.181818181818181826E+00 +DATA ·asinhrodataL18<> + 120(SB)/8, $-.165289256198351540E-01 +DATA ·asinhrodataL18<> + 128(SB)/8, $0.200350613573012186E-02 +DATA ·asinhrodataL18<> + 136(SB)/8, $-.273205381970859341E-03 +DATA ·asinhrodataL18<> + 144(SB)/8, $0.397389654305194527E-04 +DATA ·asinhrodataL18<> + 152(SB)/8, $0.938370938292558173E-06 +DATA ·asinhrodataL18<> + 160(SB)/8, $0.212881813645679599E-07 +DATA ·asinhrodataL18<> + 168(SB)/8, $-.602107458843052029E-05 +DATA ·asinhrodataL18<> + 176(SB)/8, $-.148682720127920854E-06 +DATA ·asinhrodataL18<> + 184(SB)/8, $-5.5 +DATA ·asinhrodataL18<> + 192(SB)/8, $1.0 +DATA ·asinhrodataL18<> + 200(SB)/8, $1.0E-20 +GLOBL ·asinhrodataL18<> + 0(SB), RODATA, $208 + +// Table of log correction terms +DATA ·asinhtab2080<> + 0(SB)/8, $0.585235384085551248E-01 +DATA ·asinhtab2080<> + 8(SB)/8, $0.412206153771168640E-01 +DATA ·asinhtab2080<> + 16(SB)/8, $0.273839003221648339E-01 +DATA ·asinhtab2080<> + 24(SB)/8, $0.166383778368856480E-01 +DATA ·asinhtab2080<> + 32(SB)/8, $0.866678223433169637E-02 +DATA ·asinhtab2080<> + 40(SB)/8, $0.319831684989627514E-02 +DATA ·asinhtab2080<> + 48(SB)/8, $0.0 +DATA ·asinhtab2080<> + 56(SB)/8, $-.113006378583725549E-02 +DATA ·asinhtab2080<> + 64(SB)/8, $-.367979419636602491E-03 +DATA ·asinhtab2080<> + 72(SB)/8, $0.213172484510484979E-02 +DATA ·asinhtab2080<> + 80(SB)/8, $0.623271047682013536E-02 +DATA ·asinhtab2080<> + 88(SB)/8, $0.118140812789696885E-01 +DATA ·asinhtab2080<> + 96(SB)/8, $0.187681358930914206E-01 +DATA ·asinhtab2080<> + 104(SB)/8, $0.269985148668178992E-01 +DATA ·asinhtab2080<> + 112(SB)/8, $0.364186619761331328E-01 +DATA ·asinhtab2080<> + 120(SB)/8, $0.469505379381388441E-01 +GLOBL ·asinhtab2080<> + 0(SB), RODATA, $128 + +// Asinh returns the inverse hyperbolic sine of the argument. +// +// Special cases are: +// Asinh(±0) = ±0 +// Asinh(±Inf) = ±Inf +// Asinh(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·asinhAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·asinhrodataL18<>+0(SB), R9 + LGDR F0, R12 + WORD $0xC0293FDF //iilf %r2,1071644671 + BYTE $0xFF + BYTE $0xFF + SRAD $32, R12 + WORD $0xB917001C //llgtr %r1,%r12 + MOVW R1, R6 + MOVW R2, R7 + CMPBLE R6, R7, L2 + WORD $0xC0295FEF //iilf %r2,1609564159 + BYTE $0xFF + BYTE $0xFF + MOVW R2, R7 + CMPBLE R6, R7, L14 +L3: + WORD $0xC0297FEF //iilf %r2,2146435071 + BYTE $0xFF + BYTE $0xFF + CMPW R1, R2 + BGT L1 + LTDBR F0, F0 + FMOVD F0, F10 + BLTU L15 +L9: + FMOVD $0, F0 + WFADB V0, V10, V0 + WORD $0xC0398006 //iilf %r3,2147909631 + BYTE $0x7F + BYTE $0xFF + LGDR F0, R5 + SRAD $32, R5 + MOVH $0x0, R2 + SUBW R5, R3 + FMOVD $0, F8 + RISBGZ $32, $47, $0, R3, R4 + BYTE $0x18 //lr %r1,%r4 + BYTE $0x14 + RISBGN $0, $31, $32, R4, R2 + SUBW $0x100000, R1 + SRAW $8, R1, R1 + ORW $0x45000000, R1 + BR L6 +L2: + MOVD $0x30000000, R2 + CMPW R1, R2 + BGT L16 + FMOVD 200(R9), F2 + FMADD F2, F0, F0 +L1: + FMOVD F0, ret+8(FP) + RET +L14: + LTDBR F0, F0 + BLTU L17 + FMOVD F0, F10 +L4: + FMOVD 192(R9), F2 + WFMADB V0, V0, V2, V0 + LTDBR F0, F0 + FSQRT F0, F8 +L5: + WFADB V8, V10, V0 + WORD $0xC0398006 //iilf %r3,2147909631 + BYTE $0x7F + BYTE $0xFF + LGDR F0, R5 + SRAD $32, R5 + MOVH $0x0, R2 + SUBW R5, R3 + RISBGZ $32, $47, $0, R3, R4 + SRAW $8, R4, R1 + RISBGN $0, $31, $32, R4, R2 + ORW $0x45000000, R1 +L6: + LDGR R2, F2 + FMOVD 184(R9), F0 + WFMADB V8, V2, V0, V8 + FMOVD 176(R9), F4 + WFMADB V10, V2, V8, V2 + FMOVD 168(R9), F0 + FMOVD 160(R9), F6 + FMOVD 152(R9), F1 + WFMADB V2, V6, V4, V6 + WFMADB V2, V1, V0, V1 + WFMDB V2, V2, V4 + FMOVD 144(R9), F0 + WFMADB V6, V4, V1, V6 + FMOVD 136(R9), F1 + RISBGZ $57, $60, $51, R3, R3 + WFMADB V2, V0, V1, V0 + FMOVD 128(R9), F1 + WFMADB V4, V6, V0, V6 + FMOVD 120(R9), F0 + WFMADB V2, V1, V0, V1 + VLVGF $0, R1, V0 + WFMADB V4, V6, V1, V4 + LDEBR F0, F0 + FMOVD 112(R9), F6 + WFMADB V2, V4, V6, V4 + MOVD $·asinhtab2080<>+0(SB), R1 + FMOVD 104(R9), F1 + WORD $0x68331000 //ld %f3,0(%r3,%r1) + FMOVD 96(R9), F6 + WFMADB V2, V4, V3, V2 + WFMADB V0, V1, V6, V0 + FMOVD 88(R9), F4 + WFMADB V0, V4, V2, V0 + MOVD R12, R6 + CMPBGT R6, $0, L1 + + LCDBR F0, F0 + FMOVD F0, ret+8(FP) + RET +L16: + WFMDB V0, V0, V1 + FMOVD 80(R9), F6 + WFMDB V1, V1, V4 + FMOVD 72(R9), F2 + WFMADB V4, V2, V6, V2 + FMOVD 64(R9), F3 + FMOVD 56(R9), F6 + WFMADB V4, V2, V3, V2 + FMOVD 48(R9), F3 + WFMADB V4, V6, V3, V6 + FMOVD 40(R9), F5 + FMOVD 32(R9), F3 + WFMADB V4, V2, V5, V2 + WFMADB V4, V6, V3, V6 + FMOVD 24(R9), F5 + FMOVD 16(R9), F3 + WFMADB V4, V2, V5, V2 + WFMADB V4, V6, V3, V6 + FMOVD 8(R9), F5 + FMOVD 0(R9), F3 + WFMADB V4, V2, V5, V2 + WFMADB V4, V6, V3, V4 + WFMDB V0, V1, V6 + WFMADB V1, V4, V2, V4 + FMADD F4, F6, F0 + FMOVD F0, ret+8(FP) + RET +L17: + LCDBR F0, F10 + BR L4 +L15: + LCDBR F0, F10 + BR L9 diff --git a/go/src/math/atan.go b/go/src/math/atan.go new file mode 100644 index 0000000000000000000000000000000000000000..e722e99757fd2048f4d80fc6941b2c93f0b81442 --- /dev/null +++ b/go/src/math/atan.go @@ -0,0 +1,111 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point arctangent. +*/ + +// The original C code, the long comment, and the constants below were +// from http://netlib.sandia.gov/cephes/cmath/atan.c, available from +// http://www.netlib.org/cephes/cmath.tgz. +// The go code is a version of the original C. +// +// atan.c +// Inverse circular tangent (arctangent) +// +// SYNOPSIS: +// double x, y, atan(); +// y = atan( x ); +// +// DESCRIPTION: +// Returns radian angle between -pi/2 and +pi/2 whose tangent is x. +// +// Range reduction is from three intervals into the interval from zero to 0.66. +// The approximant uses a rational function of degree 4/5 of the form +// x + x**3 P(x)/Q(x). +// +// ACCURACY: +// Relative error: +// arithmetic domain # trials peak rms +// DEC -10, 10 50000 2.4e-17 8.3e-18 +// IEEE -10, 10 10^6 1.8e-16 5.0e-17 +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov + +// xatan evaluates a series valid in the range [0, 0.66]. +func xatan(x float64) float64 { + const ( + P0 = -8.750608600031904122785e-01 + P1 = -1.615753718733365076637e+01 + P2 = -7.500855792314704667340e+01 + P3 = -1.228866684490136173410e+02 + P4 = -6.485021904942025371773e+01 + Q0 = +2.485846490142306297962e+01 + Q1 = +1.650270098316988542046e+02 + Q2 = +4.328810604912902668951e+02 + Q3 = +4.853903996359136964868e+02 + Q4 = +1.945506571482613964425e+02 + ) + z := x * x + z = z * ((((P0*z+P1)*z+P2)*z+P3)*z + P4) / (((((z+Q0)*z+Q1)*z+Q2)*z+Q3)*z + Q4) + z = x*z + x + return z +} + +// satan reduces its argument (known to be positive) +// to the range [0, 0.66] and calls xatan. +func satan(x float64) float64 { + const ( + Morebits = 6.123233995736765886130e-17 // pi/2 = PIO2 + Morebits + Tan3pio8 = 2.41421356237309504880 // tan(3*pi/8) + ) + if x <= 0.66 { + return xatan(x) + } + if x > Tan3pio8 { + return Pi/2 - xatan(1/x) + Morebits + } + return Pi/4 + xatan((x-1)/(x+1)) + 0.5*Morebits +} + +// Atan returns the arctangent, in radians, of x. +// +// Special cases are: +// +// Atan(±0) = ±0 +// Atan(±Inf) = ±Pi/2 +func Atan(x float64) float64 { + if haveArchAtan { + return archAtan(x) + } + return atan(x) +} + +func atan(x float64) float64 { + if x == 0 { + return x + } + if x > 0 { + return satan(x) + } + return -satan(-x) +} diff --git a/go/src/math/atan2.go b/go/src/math/atan2.go new file mode 100644 index 0000000000000000000000000000000000000000..c324ed0a1578a25195586ebc448d11374824e23d --- /dev/null +++ b/go/src/math/atan2.go @@ -0,0 +1,77 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Atan2 returns the arc tangent of y/x, using +// the signs of the two to determine the quadrant +// of the return value. +// +// Special cases are (in order): +// +// Atan2(y, NaN) = NaN +// Atan2(NaN, x) = NaN +// Atan2(+0, x>=0) = +0 +// Atan2(-0, x>=0) = -0 +// Atan2(+0, x<=-0) = +Pi +// Atan2(-0, x<=-0) = -Pi +// Atan2(y>0, 0) = +Pi/2 +// Atan2(y<0, 0) = -Pi/2 +// Atan2(+Inf, +Inf) = +Pi/4 +// Atan2(-Inf, +Inf) = -Pi/4 +// Atan2(+Inf, -Inf) = 3Pi/4 +// Atan2(-Inf, -Inf) = -3Pi/4 +// Atan2(y, +Inf) = 0 +// Atan2(y>0, -Inf) = +Pi +// Atan2(y<0, -Inf) = -Pi +// Atan2(+Inf, x) = +Pi/2 +// Atan2(-Inf, x) = -Pi/2 +func Atan2(y, x float64) float64 { + if haveArchAtan2 { + return archAtan2(y, x) + } + return atan2(y, x) +} + +func atan2(y, x float64) float64 { + // special cases + switch { + case IsNaN(y) || IsNaN(x): + return NaN() + case y == 0: + if x >= 0 && !Signbit(x) { + return Copysign(0, y) + } + return Copysign(Pi, y) + case x == 0: + return Copysign(Pi/2, y) + case IsInf(x, 0): + if IsInf(x, 1) { + switch { + case IsInf(y, 0): + return Copysign(Pi/4, y) + default: + return Copysign(0, y) + } + } + switch { + case IsInf(y, 0): + return Copysign(3*Pi/4, y) + default: + return Copysign(Pi, y) + } + case IsInf(y, 0): + return Copysign(Pi/2, y) + } + + // Call atan and determine the quadrant. + q := Atan(y / x) + if x < 0 { + if q <= 0 { + return q + Pi + } + return q - Pi + } + return q +} diff --git a/go/src/math/atan2_s390x.s b/go/src/math/atan2_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..13ff31977b5376676c0aa622286a8ff6b0a8d719 --- /dev/null +++ b/go/src/math/atan2_s390x.s @@ -0,0 +1,297 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define PosInf 0x7FF0000000000000 +#define NegInf 0xFFF0000000000000 +#define NegZero 0x8000000000000000 +#define Pi 0x400921FB54442D18 +#define NegPi 0xC00921FB54442D18 +#define Pi3Div4 0x4002D97C7F3321D2 // 3Pi/4 +#define NegPi3Div4 0xC002D97C7F3321D2 // -3Pi/4 +#define PiDiv4 0x3FE921FB54442D18 // Pi/4 +#define NegPiDiv4 0xBFE921FB54442D18 // -Pi/4 + +// Minimax polynomial coefficients and other constants +DATA ·atan2rodataL25<> + 0(SB)/8, $0.199999999999554423E+00 +DATA ·atan2rodataL25<> + 8(SB)/8, $-.333333333333330928E+00 +DATA ·atan2rodataL25<> + 16(SB)/8, $0.111111110136634272E+00 +DATA ·atan2rodataL25<> + 24(SB)/8, $-.142857142828026806E+00 +DATA ·atan2rodataL25<> + 32(SB)/8, $0.769228118888682505E-01 +DATA ·atan2rodataL25<> + 40(SB)/8, $0.588059263575587687E-01 +DATA ·atan2rodataL25<> + 48(SB)/8, $-.909090711945939878E-01 +DATA ·atan2rodataL25<> + 56(SB)/8, $-.666641501287528609E-01 +DATA ·atan2rodataL25<> + 64(SB)/8, $0.472329433805024762E-01 +DATA ·atan2rodataL25<> + 72(SB)/8, $-.525380587584426406E-01 +DATA ·atan2rodataL25<> + 80(SB)/8, $-.422172007412067035E-01 +DATA ·atan2rodataL25<> + 88(SB)/8, $0.366935664549587481E-01 +DATA ·atan2rodataL25<> + 96(SB)/8, $0.220852012160300086E-01 +DATA ·atan2rodataL25<> + 104(SB)/8, $-.299856214685512712E-01 +DATA ·atan2rodataL25<> + 112(SB)/8, $0.726338160757602439E-02 +DATA ·atan2rodataL25<> + 120(SB)/8, $0.134893651284712515E-04 +DATA ·atan2rodataL25<> + 128(SB)/8, $-.291935324869629616E-02 +DATA ·atan2rodataL25<> + 136(SB)/8, $-.154797890856877418E-03 +DATA ·atan2rodataL25<> + 144(SB)/8, $0.843488472994227321E-03 +DATA ·atan2rodataL25<> + 152(SB)/8, $-.139950258898989925E-01 +GLOBL ·atan2rodataL25<> + 0(SB), RODATA, $160 + +DATA ·atan2xpi2h<> + 0(SB)/8, $0x3ff330e4e4fa7b1b +DATA ·atan2xpi2h<> + 8(SB)/8, $0xbff330e4e4fa7b1b +DATA ·atan2xpi2h<> + 16(SB)/8, $0x400330e4e4fa7b1b +DATA ·atan2xpi2h<> + 24(SB)/8, $0xc00330e4e4fa7b1b +GLOBL ·atan2xpi2h<> + 0(SB), RODATA, $32 +DATA ·atan2xpim<> + 0(SB)/8, $0x3ff4f42b00000000 +GLOBL ·atan2xpim<> + 0(SB), RODATA, $8 + +// Atan2 returns the arc tangent of y/x, using +// the signs of the two to determine the quadrant +// of the return value. +// +// Special cases are (in order): +// Atan2(y, NaN) = NaN +// Atan2(NaN, x) = NaN +// Atan2(+0, x>=0) = +0 +// Atan2(-0, x>=0) = -0 +// Atan2(+0, x<=-0) = +Pi +// Atan2(-0, x<=-0) = -Pi +// Atan2(y>0, 0) = +Pi/2 +// Atan2(y<0, 0) = -Pi/2 +// Atan2(+Inf, +Inf) = +Pi/4 +// Atan2(-Inf, +Inf) = -Pi/4 +// Atan2(+Inf, -Inf) = 3Pi/4 +// Atan2(-Inf, -Inf) = -3Pi/4 +// Atan2(y, +Inf) = 0 +// Atan2(y>0, -Inf) = +Pi +// Atan2(y<0, -Inf) = -Pi +// Atan2(+Inf, x) = +Pi/2 +// Atan2(-Inf, x) = -Pi/2 +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·atan2Asm(SB), NOSPLIT, $0-24 + // special case + MOVD x+0(FP), R1 + MOVD y+8(FP), R2 + + // special case Atan2(NaN, y) = NaN + MOVD $~(1<<63), R5 + AND R1, R5 // x = |x| + MOVD $PosInf, R3 + CMPUBLT R3, R5, returnX + + // special case Atan2(x, NaN) = NaN + MOVD $~(1<<63), R5 + AND R2, R5 + CMPUBLT R3, R5, returnY + + MOVD $NegZero, R3 + CMPUBEQ R3, R1, xIsNegZero + + MOVD $0, R3 + CMPUBEQ R3, R1, xIsPosZero + + MOVD $PosInf, R4 + CMPUBEQ R4, R2, yIsPosInf + + MOVD $NegInf, R4 + CMPUBEQ R4, R2, yIsNegInf + BR Normal +xIsNegZero: + // special case Atan(-0, y>=0) = -0 + MOVD $0, R4 + CMPBLE R4, R2, returnX + + //special case Atan2(-0, y<=-0) = -Pi + MOVD $NegZero, R4 + CMPBGE R4, R2, returnNegPi + BR Normal +xIsPosZero: + //special case Atan2(0, 0) = 0 + MOVD $0, R4 + CMPUBEQ R4, R2, returnX + + //special case Atan2(0, y<=-0) = Pi + MOVD $NegZero, R4 + CMPBGE R4, R2, returnPi + BR Normal +yIsNegInf: + //special case Atan2(+Inf, -Inf) = 3Pi/4 + MOVD $PosInf, R3 + CMPUBEQ R3, R1, posInfNegInf + + //special case Atan2(-Inf, -Inf) = -3Pi/4 + MOVD $NegInf, R3 + CMPUBEQ R3, R1, negInfNegInf + BR Normal +yIsPosInf: + //special case Atan2(+Inf, +Inf) = Pi/4 + MOVD $PosInf, R3 + CMPUBEQ R3, R1, posInfPosInf + + //special case Atan2(-Inf, +Inf) = -Pi/4 + MOVD $NegInf, R3 + CMPUBEQ R3, R1, negInfPosInf + + //special case Atan2(x, +Inf) = Copysign(0, x) + CMPBLT R1, $0, returnNegZero + BR returnPosZero + +Normal: + FMOVD x+0(FP), F0 + FMOVD y+8(FP), F2 + MOVD $·atan2rodataL25<>+0(SB), R9 + LGDR F0, R2 + LGDR F2, R1 + RISBGNZ $32, $63, $32, R2, R2 + RISBGNZ $32, $63, $32, R1, R1 + WORD $0xB9170032 //llgtr %r3,%r2 + RISBGZ $63, $63, $33, R2, R5 + WORD $0xB9170041 //llgtr %r4,%r1 + WFLCDB V0, V20 + MOVW R4, R6 + MOVW R3, R7 + CMPUBLT R6, R7, L17 + WFDDB V2, V0, V3 + ADDW $2, R5, R2 + MOVW R4, R6 + MOVW R3, R7 + CMPUBLE R6, R7, L20 +L3: + WFMDB V3, V3, V4 + VLEG $0, 152(R9), V18 + VLEG $0, 144(R9), V16 + FMOVD 136(R9), F1 + FMOVD 128(R9), F5 + FMOVD 120(R9), F6 + WFMADB V4, V16, V5, V16 + WFMADB V4, V6, V1, V6 + FMOVD 112(R9), F7 + WFMDB V4, V4, V1 + WFMADB V4, V7, V18, V7 + VLEG $0, 104(R9), V18 + WFMADB V1, V6, V16, V6 + CMPWU R4, R3 + FMOVD 96(R9), F5 + VLEG $0, 88(R9), V16 + WFMADB V4, V5, V18, V5 + VLEG $0, 80(R9), V18 + VLEG $0, 72(R9), V22 + WFMADB V4, V16, V18, V16 + VLEG $0, 64(R9), V18 + WFMADB V1, V7, V5, V7 + WFMADB V4, V18, V22, V18 + WFMDB V1, V1, V5 + WFMADB V1, V16, V18, V16 + VLEG $0, 56(R9), V18 + WFMADB V5, V6, V7, V6 + VLEG $0, 48(R9), V22 + FMOVD 40(R9), F7 + WFMADB V4, V7, V18, V7 + VLEG $0, 32(R9), V18 + WFMADB V5, V6, V16, V6 + WFMADB V4, V18, V22, V18 + VLEG $0, 24(R9), V16 + WFMADB V1, V7, V18, V7 + VLEG $0, 16(R9), V18 + VLEG $0, 8(R9), V22 + WFMADB V4, V18, V16, V18 + VLEG $0, 0(R9), V16 + WFMADB V5, V6, V7, V6 + WFMADB V4, V16, V22, V16 + FMUL F3, F4 + WFMADB V1, V18, V16, V1 + FMADD F6, F5, F1 + WFMADB V4, V1, V3, V4 + BLT L18 + BGT L7 + LTDBR F2, F2 + BLTU L21 +L8: + LTDBR F0, F0 + BLTU L22 +L9: + WFCHDBS V2, V0, V0 + BNE L18 +L7: + MOVW R1, R6 + CMPBGE R6, $0, L1 +L18: + RISBGZ $58, $60, $3, R2, R2 + MOVD $·atan2xpi2h<>+0(SB), R1 + MOVD ·atan2xpim<>+0(SB), R3 + LDGR R3, F0 + WORD $0xED021000 //madb %f4,%f0,0(%r2,%r1) + BYTE $0x40 + BYTE $0x1E +L1: + FMOVD F4, ret+16(FP) + RET + +L20: + LTDBR F2, F2 + BLTU L23 + FMOVD F2, F6 +L4: + LTDBR F0, F0 + BLTU L24 + FMOVD F0, F4 +L5: + WFCHDBS V6, V4, V4 + BEQ L3 +L17: + WFDDB V0, V2, V4 + BYTE $0x18 //lr %r2,%r5 + BYTE $0x25 + LCDBR F4, F3 + BR L3 +L23: + LCDBR F2, F6 + BR L4 +L22: + VLR V20, V0 + BR L9 +L21: + LCDBR F2, F2 + BR L8 +L24: + VLR V20, V4 + BR L5 +returnX: //the result is same as the first argument + MOVD R1, ret+16(FP) + RET +returnY: //the result is same as the second argument + MOVD R2, ret+16(FP) + RET +returnPi: + MOVD $Pi, R1 + MOVD R1, ret+16(FP) + RET +returnNegPi: + MOVD $NegPi, R1 + MOVD R1, ret+16(FP) + RET +posInfNegInf: + MOVD $Pi3Div4, R1 + MOVD R1, ret+16(FP) + RET +negInfNegInf: + MOVD $NegPi3Div4, R1 + MOVD R1, ret+16(FP) + RET +posInfPosInf: + MOVD $PiDiv4, R1 + MOVD R1, ret+16(FP) + RET +negInfPosInf: + MOVD $NegPiDiv4, R1 + MOVD R1, ret+16(FP) + RET +returnNegZero: + MOVD $NegZero, R1 + MOVD R1, ret+16(FP) + RET +returnPosZero: + MOVD $0, ret+16(FP) + RET diff --git a/go/src/math/atan_s390x.s b/go/src/math/atan_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..3a7e59bb1ac62852663cbcbdee31c72e9ad11428 --- /dev/null +++ b/go/src/math/atan_s390x.s @@ -0,0 +1,128 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·atanrodataL8<> + 0(SB)/8, $0.199999999999554423E+00 +DATA ·atanrodataL8<> + 8(SB)/8, $0.111111110136634272E+00 +DATA ·atanrodataL8<> + 16(SB)/8, $-.142857142828026806E+00 +DATA ·atanrodataL8<> + 24(SB)/8, $-.333333333333330928E+00 +DATA ·atanrodataL8<> + 32(SB)/8, $0.769228118888682505E-01 +DATA ·atanrodataL8<> + 40(SB)/8, $0.588059263575587687E-01 +DATA ·atanrodataL8<> + 48(SB)/8, $-.666641501287528609E-01 +DATA ·atanrodataL8<> + 56(SB)/8, $-.909090711945939878E-01 +DATA ·atanrodataL8<> + 64(SB)/8, $0.472329433805024762E-01 +DATA ·atanrodataL8<> + 72(SB)/8, $0.366935664549587481E-01 +DATA ·atanrodataL8<> + 80(SB)/8, $-.422172007412067035E-01 +DATA ·atanrodataL8<> + 88(SB)/8, $-.299856214685512712E-01 +DATA ·atanrodataL8<> + 96(SB)/8, $0.220852012160300086E-01 +DATA ·atanrodataL8<> + 104(SB)/8, $0.726338160757602439E-02 +DATA ·atanrodataL8<> + 112(SB)/8, $0.843488472994227321E-03 +DATA ·atanrodataL8<> + 120(SB)/8, $0.134893651284712515E-04 +DATA ·atanrodataL8<> + 128(SB)/8, $-.525380587584426406E-01 +DATA ·atanrodataL8<> + 136(SB)/8, $-.139950258898989925E-01 +DATA ·atanrodataL8<> + 144(SB)/8, $-.291935324869629616E-02 +DATA ·atanrodataL8<> + 152(SB)/8, $-.154797890856877418E-03 +GLOBL ·atanrodataL8<> + 0(SB), RODATA, $160 + +DATA ·atanxpi2h<> + 0(SB)/8, $0x3ff330e4e4fa7b1b +DATA ·atanxpi2h<> + 8(SB)/8, $0xbff330e4e4fa7b1b +DATA ·atanxpi2h<> + 16(SB)/8, $0x400330e4e4fa7b1b +DATA ·atanxpi2h<> + 24(SB)/4, $0xc00330e4e4fa7b1b +GLOBL ·atanxpi2h<> + 0(SB), RODATA, $32 +DATA ·atanxpim<> + 0(SB)/8, $0x3ff4f42b00000000 +GLOBL ·atanxpim<> + 0(SB), RODATA, $8 +DATA ·atanxmone<> + 0(SB)/8, $-1.0 +GLOBL ·atanxmone<> + 0(SB), RODATA, $8 + +// Atan returns the arctangent, in radians, of the argument. +// +// Special cases are: +// Atan(±0) = ±0 +// Atan(±Inf) = ±Pi/2Pi +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·atanAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + //special case Atan(±0) = ±0 + FMOVD $(0.0), F1 + FCMPU F0, F1 + BEQ atanIsZero + + MOVD $·atanrodataL8<>+0(SB), R5 + MOVH $0x3FE0, R3 + LGDR F0, R1 + RISBGNZ $32, $63, $32, R1, R1 + RLL $16, R1, R2 + ANDW $0x7FF0, R2 + MOVW R2, R6 + MOVW R3, R7 + CMPUBLE R6, R7, L6 + MOVD $·atanxmone<>+0(SB), R3 + FMOVD 0(R3), F2 + WFDDB V0, V2, V0 + RISBGZ $63, $63, $33, R1, R1 + MOVD $·atanxpi2h<>+0(SB), R3 + MOVWZ R1, R1 + SLD $3, R1, R1 + WORD $0x68813000 //ld %f8,0(%r1,%r3) +L6: + WFMDB V0, V0, V2 + FMOVD 152(R5), F6 + FMOVD 144(R5), F1 + FMOVD 136(R5), F7 + VLEG $0, 128(R5), V16 + FMOVD 120(R5), F4 + FMOVD 112(R5), F5 + WFMADB V2, V4, V6, V4 + WFMADB V2, V5, V1, V5 + WFMDB V2, V2, V6 + FMOVD 104(R5), F3 + FMOVD 96(R5), F1 + WFMADB V2, V3, V7, V3 + MOVH $0x3FE0, R1 + FMOVD 88(R5), F7 + WFMADB V2, V1, V7, V1 + FMOVD 80(R5), F7 + WFMADB V6, V3, V1, V3 + WFMADB V6, V4, V5, V4 + WFMDB V6, V6, V1 + FMOVD 72(R5), F5 + WFMADB V2, V5, V7, V5 + FMOVD 64(R5), F7 + WFMADB V2, V7, V16, V7 + VLEG $0, 56(R5), V16 + WFMADB V6, V5, V7, V5 + WFMADB V1, V4, V3, V4 + FMOVD 48(R5), F7 + FMOVD 40(R5), F3 + WFMADB V2, V3, V7, V3 + FMOVD 32(R5), F7 + WFMADB V2, V7, V16, V7 + VLEG $0, 24(R5), V16 + WFMADB V1, V4, V5, V4 + FMOVD 16(R5), F5 + WFMADB V6, V3, V7, V3 + FMOVD 8(R5), F7 + WFMADB V2, V7, V5, V7 + FMOVD 0(R5), F5 + WFMADB V2, V5, V16, V5 + WFMADB V1, V4, V3, V4 + WFMADB V6, V7, V5, V6 + FMUL F0, F2 + FMADD F4, F1, F6 + FMADD F6, F2, F0 + MOVW R2, R6 + MOVW R1, R7 + CMPUBLE R6, R7, L1 + MOVD $·atanxpim<>+0(SB), R1 + WORD $0xED801000 //madb %f0,%f8,0(%r1) + BYTE $0x00 + BYTE $0x1E +L1: +atanIsZero: + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/atanh.go b/go/src/math/atanh.go new file mode 100644 index 0000000000000000000000000000000000000000..9d594625a5c04a41954d3bf2fbef2d078751ad11 --- /dev/null +++ b/go/src/math/atanh.go @@ -0,0 +1,85 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/e_atanh.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// __ieee754_atanh(x) +// Method : +// 1. Reduce x to positive by atanh(-x) = -atanh(x) +// 2. For x>=0.5 +// 1 2x x +// atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------) +// 2 1 - x 1 - x +// +// For x<0.5 +// atanh(x) = 0.5*log1p(2x+2x*x/(1-x)) +// +// Special cases: +// atanh(x) is NaN if |x| > 1 with signal; +// atanh(NaN) is that NaN with no signal; +// atanh(+-1) is +-INF with signal. +// + +// Atanh returns the inverse hyperbolic tangent of x. +// +// Special cases are: +// +// Atanh(1) = +Inf +// Atanh(±0) = ±0 +// Atanh(-1) = -Inf +// Atanh(x) = NaN if x < -1 or x > 1 +// Atanh(NaN) = NaN +func Atanh(x float64) float64 { + if haveArchAtanh { + return archAtanh(x) + } + return atanh(x) +} + +func atanh(x float64) float64 { + const NearZero = 1.0 / (1 << 28) // 2**-28 + // special cases + switch { + case x < -1 || x > 1 || IsNaN(x): + return NaN() + case x == 1: + return Inf(1) + case x == -1: + return Inf(-1) + } + sign := false + if x < 0 { + x = -x + sign = true + } + var temp float64 + switch { + case x < NearZero: + temp = x + case x < 0.5: + temp = x + x + temp = 0.5 * Log1p(temp+temp*x/(1-x)) + default: + temp = 0.5 * Log1p((x+x)/(1-x)) + } + if sign { + temp = -temp + } + return temp +} diff --git a/go/src/math/atanh_s390x.s b/go/src/math/atanh_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..ba0e92696720b3c95c1ebfd5a99594b42c17afe8 --- /dev/null +++ b/go/src/math/atanh_s390x.s @@ -0,0 +1,174 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·atanhrodataL10<> + 0(SB)/8, $.41375273347623353626 +DATA ·atanhrodataL10<> + 8(SB)/8, $.51487302528619766235E+04 +DATA ·atanhrodataL10<> + 16(SB)/8, $-1.67526912689208984375 +DATA ·atanhrodataL10<> + 24(SB)/8, $0.181818181818181826E+00 +DATA ·atanhrodataL10<> + 32(SB)/8, $-.165289256198351540E-01 +DATA ·atanhrodataL10<> + 40(SB)/8, $0.200350613573012186E-02 +DATA ·atanhrodataL10<> + 48(SB)/8, $0.397389654305194527E-04 +DATA ·atanhrodataL10<> + 56(SB)/8, $-.273205381970859341E-03 +DATA ·atanhrodataL10<> + 64(SB)/8, $0.938370938292558173E-06 +DATA ·atanhrodataL10<> + 72(SB)/8, $-.148682720127920854E-06 +DATA ·atanhrodataL10<> + 80(SB)/8, $ 0.212881813645679599E-07 +DATA ·atanhrodataL10<> + 88(SB)/8, $-.602107458843052029E-05 +DATA ·atanhrodataL10<> + 96(SB)/8, $-5.5 +DATA ·atanhrodataL10<> + 104(SB)/8, $-0.5 +DATA ·atanhrodataL10<> + 112(SB)/8, $0.0 +DATA ·atanhrodataL10<> + 120(SB)/8, $0x7ff8000000000000 //Nan +DATA ·atanhrodataL10<> + 128(SB)/8, $-1.0 +DATA ·atanhrodataL10<> + 136(SB)/8, $1.0 +DATA ·atanhrodataL10<> + 144(SB)/8, $1.0E-20 +GLOBL ·atanhrodataL10<> + 0(SB), RODATA, $152 + +// Table of log correction terms +DATA ·atanhtab2076<> + 0(SB)/8, $0.585235384085551248E-01 +DATA ·atanhtab2076<> + 8(SB)/8, $0.412206153771168640E-01 +DATA ·atanhtab2076<> + 16(SB)/8, $0.273839003221648339E-01 +DATA ·atanhtab2076<> + 24(SB)/8, $0.166383778368856480E-01 +DATA ·atanhtab2076<> + 32(SB)/8, $0.866678223433169637E-02 +DATA ·atanhtab2076<> + 40(SB)/8, $0.319831684989627514E-02 +DATA ·atanhtab2076<> + 48(SB)/8, $0.000000000000000000E+00 +DATA ·atanhtab2076<> + 56(SB)/8, $-.113006378583725549E-02 +DATA ·atanhtab2076<> + 64(SB)/8, $-.367979419636602491E-03 +DATA ·atanhtab2076<> + 72(SB)/8, $0.213172484510484979E-02 +DATA ·atanhtab2076<> + 80(SB)/8, $0.623271047682013536E-02 +DATA ·atanhtab2076<> + 88(SB)/8, $0.118140812789696885E-01 +DATA ·atanhtab2076<> + 96(SB)/8, $0.187681358930914206E-01 +DATA ·atanhtab2076<> + 104(SB)/8, $0.269985148668178992E-01 +DATA ·atanhtab2076<> + 112(SB)/8, $0.364186619761331328E-01 +DATA ·atanhtab2076<> + 120(SB)/8, $0.469505379381388441E-01 +GLOBL ·atanhtab2076<> + 0(SB), RODATA, $128 + +// Table of +/- .5 +DATA ·atanhtabh2075<> + 0(SB)/8, $0.5 +DATA ·atanhtabh2075<> + 8(SB)/8, $-.5 +GLOBL ·atanhtabh2075<> + 0(SB), RODATA, $16 + +// Atanh returns the inverse hyperbolic tangent of the argument. +// +// Special cases are: +// Atanh(1) = +Inf +// Atanh(±0) = ±0 +// Atanh(-1) = -Inf +// Atanh(x) = NaN if x < -1 or x > 1 +// Atanh(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·atanhAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·atanhrodataL10<>+0(SB), R5 + LGDR F0, R1 + WORD $0xC0393FEF //iilf %r3,1072693247 + BYTE $0xFF + BYTE $0xFF + SRAD $32, R1 + WORD $0xB9170021 //llgtr %r2,%r1 + MOVW R2, R6 + MOVW R3, R7 + CMPBGT R6, R7, L2 + WORD $0xC0392FFF //iilf %r3,805306367 + BYTE $0xFF + BYTE $0xFF + MOVW R2, R6 + MOVW R3, R7 + CMPBGT R6, R7, L9 +L3: + FMOVD 144(R5), F2 + FMADD F2, F0, F0 +L1: + FMOVD F0, ret+8(FP) + RET + +L2: + WORD $0xED005088 //cdb %f0,.L12-.L10(%r5) + BYTE $0x00 + BYTE $0x19 + BEQ L5 + WORD $0xED005080 //cdb %f0,.L13-.L10(%r5) + BYTE $0x00 + BYTE $0x19 + BEQ L5 + WFCEDBS V0, V0, V2 + BVS L1 + FMOVD 120(R5), F0 + BR L1 +L5: + WORD $0xED005070 //ddb %f0,.L15-.L10(%r5) + BYTE $0x00 + BYTE $0x1D + FMOVD F0, ret+8(FP) + RET + +L9: + FMOVD F0, F2 + MOVD $·atanhtabh2075<>+0(SB), R2 + SRW $31, R1, R1 + FMOVD 104(R5), F4 + MOVW R1, R1 + SLD $3, R1, R1 + WORD $0x68012000 //ld %f0,0(%r1,%r2) + WFMADB V2, V4, V0, V4 + VLEG $0, 96(R5), V16 + FDIV F4, F2 + WORD $0xC0298006 //iilf %r2,2147909631 + BYTE $0x7F + BYTE $0xFF + FMOVD 88(R5), F6 + FMOVD 80(R5), F1 + FMOVD 72(R5), F7 + FMOVD 64(R5), F5 + FMOVD F2, F4 + WORD $0xED405088 //adb %f4,.L12-.L10(%r5) + BYTE $0x00 + BYTE $0x1A + LGDR F4, R4 + SRAD $32, R4 + FMOVD F4, F3 + WORD $0xED305088 //sdb %f3,.L12-.L10(%r5) + BYTE $0x00 + BYTE $0x1B + SUBW R4, R2 + WFSDB V3, V2, V3 + RISBGZ $32, $47, $0, R2, R1 + SLD $32, R1, R1 + LDGR R1, F2 + WFMADB V4, V2, V16, V4 + SRAW $8, R2, R1 + WFMADB V4, V5, V6, V5 + WFMDB V4, V4, V6 + WFMADB V4, V1, V7, V1 + WFMADB V2, V3, V4, V2 + WFMADB V1, V6, V5, V1 + FMOVD 56(R5), F3 + FMOVD 48(R5), F5 + WFMADB V4, V5, V3, V4 + FMOVD 40(R5), F3 + FMADD F1, F6, F4 + FMOVD 32(R5), F1 + FMADD F3, F2, F1 + ANDW $0xFFFFFF00, R1 + WFMADB V6, V4, V1, V6 + FMOVD 24(R5), F3 + ORW $0x45000000, R1 + WFMADB V2, V6, V3, V6 + VLVGF $0, R1, V4 + LDEBR F4, F4 + RISBGZ $57, $60, $51, R2, R2 + MOVD $·atanhtab2076<>+0(SB), R1 + FMOVD 16(R5), F3 + WORD $0x68521000 //ld %f5,0(%r2,%r1) + FMOVD 8(R5), F1 + WFMADB V2, V6, V5, V2 + WFMADB V4, V3, V1, V4 + FMOVD 0(R5), F6 + FMADD F6, F4, F2 + FMUL F2, F0 + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/bits.go b/go/src/math/bits.go new file mode 100644 index 0000000000000000000000000000000000000000..3716a411f4f1b81bb99f441f0102ab3082e8477b --- /dev/null +++ b/go/src/math/bits.go @@ -0,0 +1,67 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +const ( + uvnan = 0x7FF8000000000001 + uvinf = 0x7FF0000000000000 + uvneginf = 0xFFF0000000000000 + uvone = 0x3FF0000000000000 + mask = 0x7FF + shift = 64 - 11 - 1 + bias = 1023 + signMask = 1 << 63 + fracMask = 1<= 0, negative infinity if sign < 0. +func Inf(sign int) float64 { + var v uint64 + if sign >= 0 { + v = uvinf + } else { + v = uvneginf + } + return Float64frombits(v) +} + +// NaN returns an IEEE 754 “not-a-number” value. +func NaN() float64 { return Float64frombits(uvnan) } + +// IsNaN reports whether f is an IEEE 754 “not-a-number” value. +func IsNaN(f float64) (is bool) { + // IEEE 754 says that only NaNs satisfy f != f. + // To avoid the floating-point hardware, could use: + // x := Float64bits(f); + // return uint32(x>>shift)&mask == mask && x != uvinf && x != uvneginf + return f != f +} + +// IsInf reports whether f is an infinity, according to sign. +// If sign > 0, IsInf reports whether f is positive infinity. +// If sign < 0, IsInf reports whether f is negative infinity. +// If sign == 0, IsInf reports whether f is either infinity. +func IsInf(f float64, sign int) bool { + // Test for infinity by comparing against maximum float. + // To avoid the floating-point hardware, could use: + // x := Float64bits(f); + // return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf; + if sign == 0 { + f = Abs(f) + } else if sign < 0 { + f = -f + } + return f > MaxFloat64 +} + +// normalize returns a normal number y and exponent exp +// satisfying x == y × 2**exp. It assumes x is finite and non-zero. +func normalize(x float64) (y float64, exp int) { + const SmallestNormal = 2.2250738585072014e-308 // 2**-1022 + if Abs(x) < SmallestNormal { + return x * (1 << 52), -52 + } + return x, 0 +} diff --git a/go/src/math/cbrt.go b/go/src/math/cbrt.go new file mode 100644 index 0000000000000000000000000000000000000000..e5e9548cb1f39489df6d8185b5e8c36b6e72876e --- /dev/null +++ b/go/src/math/cbrt.go @@ -0,0 +1,85 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The go code is a modified version of the original C code from +// http://www.netlib.org/fdlibm/s_cbrt.c and came with this notice. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunSoft, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== + +// Cbrt returns the cube root of x. +// +// Special cases are: +// +// Cbrt(±0) = ±0 +// Cbrt(±Inf) = ±Inf +// Cbrt(NaN) = NaN +func Cbrt(x float64) float64 { + if haveArchCbrt { + return archCbrt(x) + } + return cbrt(x) +} + +func cbrt(x float64) float64 { + const ( + B1 = 715094163 // (682-0.03306235651)*2**20 + B2 = 696219795 // (664-0.03306235651)*2**20 + C = 5.42857142857142815906e-01 // 19/35 = 0x3FE15F15F15F15F1 + D = -7.05306122448979611050e-01 // -864/1225 = 0xBFE691DE2532C834 + E = 1.41428571428571436819e+00 // 99/70 = 0x3FF6A0EA0EA0EA0F + F = 1.60714285714285720630e+00 // 45/28 = 0x3FF9B6DB6DB6DB6E + G = 3.57142857142857150787e-01 // 5/14 = 0x3FD6DB6DB6DB6DB7 + SmallestNormal = 2.22507385850720138309e-308 // 2**-1022 = 0x0010000000000000 + ) + // special cases + switch { + case x == 0 || IsNaN(x) || IsInf(x, 0): + return x + } + + sign := false + if x < 0 { + x = -x + sign = true + } + + // rough cbrt to 5 bits + t := Float64frombits(Float64bits(x)/3 + B1<<32) + if x < SmallestNormal { + // subnormal number + t = float64(1 << 54) // set t= 2**54 + t *= x + t = Float64frombits(Float64bits(t)/3 + B2<<32) + } + + // new cbrt to 23 bits + r := t * t / x + s := C + r*t + t *= G + F/(s+E+D/s) + + // chop to 22 bits, make larger than cbrt(x) + t = Float64frombits(Float64bits(t)&(0xFFFFFFFFC<<28) + 1<<30) + + // one step newton iteration to 53 bits with error less than 0.667ulps + s = t * t // t*t is exact + r = x / s + w := t + t + r = (r - t) / (w + r) // r-s is exact + t = t + t*r + + // restore the sign bit + if sign { + t = -t + } + return t +} diff --git a/go/src/math/cbrt_s390x.s b/go/src/math/cbrt_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..87bba531b8cb8d9c38edbf650cf74d599e2c4c0e --- /dev/null +++ b/go/src/math/cbrt_s390x.s @@ -0,0 +1,156 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·cbrtrodataL9<> + 0(SB)/8, $-.00016272731015974436E+00 +DATA ·cbrtrodataL9<> + 8(SB)/8, $0.66639548758285293179E+00 +DATA ·cbrtrodataL9<> + 16(SB)/8, $0.55519402697349815993E+00 +DATA ·cbrtrodataL9<> + 24(SB)/8, $0.49338566048766782004E+00 +DATA ·cbrtrodataL9<> + 32(SB)/8, $0.45208160036325611486E+00 +DATA ·cbrtrodataL9<> + 40(SB)/8, $0.43099892837778637816E+00 +DATA ·cbrtrodataL9<> + 48(SB)/8, $1.000244140625 +DATA ·cbrtrodataL9<> + 56(SB)/8, $0.33333333333333333333E+00 +DATA ·cbrtrodataL9<> + 64(SB)/8, $79228162514264337593543950336. +GLOBL ·cbrtrodataL9<> + 0(SB), RODATA, $72 + +// Index tables +DATA ·cbrttab32069<> + 0(SB)/8, $0x404030303020202 +DATA ·cbrttab32069<> + 8(SB)/8, $0x101010101000000 +DATA ·cbrttab32069<> + 16(SB)/8, $0x808070706060605 +DATA ·cbrttab32069<> + 24(SB)/8, $0x505040404040303 +DATA ·cbrttab32069<> + 32(SB)/8, $0xe0d0c0c0b0b0b0a +DATA ·cbrttab32069<> + 40(SB)/8, $0xa09090908080808 +DATA ·cbrttab32069<> + 48(SB)/8, $0x11111010100f0f0f +DATA ·cbrttab32069<> + 56(SB)/8, $0xe0e0e0e0e0d0d0d +DATA ·cbrttab32069<> + 64(SB)/8, $0x1515141413131312 +DATA ·cbrttab32069<> + 72(SB)/8, $0x1212111111111010 +GLOBL ·cbrttab32069<> + 0(SB), RODATA, $80 + +DATA ·cbrttab22068<> + 0(SB)/8, $0x151015001420141 +DATA ·cbrttab22068<> + 8(SB)/8, $0x140013201310130 +DATA ·cbrttab22068<> + 16(SB)/8, $0x122012101200112 +DATA ·cbrttab22068<> + 24(SB)/8, $0x111011001020101 +DATA ·cbrttab22068<> + 32(SB)/8, $0x10000f200f100f0 +DATA ·cbrttab22068<> + 40(SB)/8, $0xe200e100e000d2 +DATA ·cbrttab22068<> + 48(SB)/8, $0xd100d000c200c1 +DATA ·cbrttab22068<> + 56(SB)/8, $0xc000b200b100b0 +DATA ·cbrttab22068<> + 64(SB)/8, $0xa200a100a00092 +DATA ·cbrttab22068<> + 72(SB)/8, $0x91009000820081 +DATA ·cbrttab22068<> + 80(SB)/8, $0x80007200710070 +DATA ·cbrttab22068<> + 88(SB)/8, $0x62006100600052 +DATA ·cbrttab22068<> + 96(SB)/8, $0x51005000420041 +DATA ·cbrttab22068<> + 104(SB)/8, $0x40003200310030 +DATA ·cbrttab22068<> + 112(SB)/8, $0x22002100200012 +DATA ·cbrttab22068<> + 120(SB)/8, $0x11001000020001 +GLOBL ·cbrttab22068<> + 0(SB), RODATA, $128 + +DATA ·cbrttab12067<> + 0(SB)/8, $0x53e1529051324fe1 +DATA ·cbrttab12067<> + 8(SB)/8, $0x4e904d324be14a90 +DATA ·cbrttab12067<> + 16(SB)/8, $0x493247e146904532 +DATA ·cbrttab12067<> + 24(SB)/8, $0x43e1429041323fe1 +DATA ·cbrttab12067<> + 32(SB)/8, $0x3e903d323be13a90 +DATA ·cbrttab12067<> + 40(SB)/8, $0x393237e136903532 +DATA ·cbrttab12067<> + 48(SB)/8, $0x33e1329031322fe1 +DATA ·cbrttab12067<> + 56(SB)/8, $0x2e902d322be12a90 +DATA ·cbrttab12067<> + 64(SB)/8, $0xd3e1d290d132cfe1 +DATA ·cbrttab12067<> + 72(SB)/8, $0xce90cd32cbe1ca90 +DATA ·cbrttab12067<> + 80(SB)/8, $0xc932c7e1c690c532 +DATA ·cbrttab12067<> + 88(SB)/8, $0xc3e1c290c132bfe1 +DATA ·cbrttab12067<> + 96(SB)/8, $0xbe90bd32bbe1ba90 +DATA ·cbrttab12067<> + 104(SB)/8, $0xb932b7e1b690b532 +DATA ·cbrttab12067<> + 112(SB)/8, $0xb3e1b290b132afe1 +DATA ·cbrttab12067<> + 120(SB)/8, $0xae90ad32abe1aa90 +GLOBL ·cbrttab12067<> + 0(SB), RODATA, $128 + +// Cbrt returns the cube root of the argument. +// +// Special cases are: +// Cbrt(±0) = ±0 +// Cbrt(±Inf) = ±Inf +// Cbrt(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·cbrtAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·cbrtrodataL9<>+0(SB), R9 + LGDR F0, R2 + WORD $0xC039000F //iilf %r3,1048575 + BYTE $0xFF + BYTE $0xFF + SRAD $32, R2 + WORD $0xB9170012 //llgtr %r1,%r2 + MOVW R1, R6 + MOVW R3, R7 + CMPBLE R6, R7, L2 + WORD $0xC0397FEF //iilf %r3,2146435071 + BYTE $0xFF + BYTE $0xFF + MOVW R3, R7 + CMPBLE R6, R7, L8 +L1: + FMOVD F0, ret+8(FP) + RET +L3: +L2: + LTDBR F0, F0 + BEQ L1 + FMOVD F0, F2 + WORD $0xED209040 //mdb %f2,.L10-.L9(%r9) + BYTE $0x00 + BYTE $0x1C + MOVH $0x200, R4 + LGDR F2, R2 + SRAD $32, R2 +L4: + RISBGZ $57, $62, $39, R2, R3 + MOVD $·cbrttab12067<>+0(SB), R1 + WORD $0x48131000 //lh %r1,0(%r3,%r1) + RISBGZ $57, $62, $45, R2, R3 + MOVD $·cbrttab22068<>+0(SB), R5 + RISBGNZ $60, $63, $48, R2, R2 + WORD $0x4A135000 //ah %r1,0(%r3,%r5) + BYTE $0x18 //lr %r3,%r1 + BYTE $0x31 + MOVD $·cbrttab32069<>+0(SB), R1 + FMOVD 56(R9), F1 + FMOVD 48(R9), F5 + WORD $0xEC23393B //rosbg %r2,%r3,57,59,4 + BYTE $0x04 + BYTE $0x56 + WORD $0xE3121000 //llc %r1,0(%r2,%r1) + BYTE $0x00 + BYTE $0x94 + ADDW R3, R1 + ADDW R4, R1 + SLW $16, R1, R1 + SLD $32, R1, R1 + LDGR R1, F2 + WFMDB V2, V2, V4 + WFMDB V4, V0, V6 + WFMSDB V4, V6, V2, V4 + FMOVD 40(R9), F6 + FMSUB F1, F4, F2 + FMOVD 32(R9), F4 + WFMDB V2, V2, V3 + FMOVD 24(R9), F1 + FMUL F3, F0 + FMOVD 16(R9), F3 + WFMADB V2, V0, V5, V2 + FMOVD 8(R9), F5 + FMADD F6, F2, F4 + WFMADB V2, V1, V3, V1 + WFMDB V2, V2, V6 + FMOVD 0(R9), F3 + WFMADB V4, V6, V1, V4 + WFMADB V2, V5, V3, V2 + FMADD F4, F6, F2 + FMADD F2, F0, F0 + FMOVD F0, ret+8(FP) + RET +L8: + MOVH $0x0, R4 + BR L4 diff --git a/go/src/math/const.go b/go/src/math/const.go new file mode 100644 index 0000000000000000000000000000000000000000..b15e50e01820837acc344aa5646e1633f07dc8f1 --- /dev/null +++ b/go/src/math/const.go @@ -0,0 +1,57 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package math provides basic constants and mathematical functions. +// +// This package does not guarantee bit-identical results across architectures. +package math + +// Mathematical constants. +const ( + E = 2.71828182845904523536028747135266249775724709369995957496696763 // https://oeis.org/A001113 + Pi = 3.14159265358979323846264338327950288419716939937510582097494459 // https://oeis.org/A000796 + Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // https://oeis.org/A001622 + + Sqrt2 = 1.41421356237309504880168872420969807856967187537694807317667974 // https://oeis.org/A002193 + SqrtE = 1.64872127070012814684865078781416357165377610071014801157507931 // https://oeis.org/A019774 + SqrtPi = 1.77245385090551602729816748334114518279754945612238712821380779 // https://oeis.org/A002161 + SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // https://oeis.org/A139339 + + Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009 // https://oeis.org/A002162 + Log2E = 1 / Ln2 + Ln10 = 2.30258509299404568401799145468436420760110148862877297603332790 // https://oeis.org/A002392 + Log10E = 1 / Ln10 +) + +// Floating-point limit values. +// Max is the largest finite value representable by the type. +// SmallestNonzero is the smallest positive, non-zero value representable by the type. +const ( + MaxFloat32 = 0x1p127 * (1 + (1 - 0x1p-23)) // 3.40282346638528859811704183484516925440e+38 + SmallestNonzeroFloat32 = 0x1p-126 * 0x1p-23 // 1.401298464324817070923729583289916131280e-45 + + MaxFloat64 = 0x1p1023 * (1 + (1 - 0x1p-52)) // 1.79769313486231570814527423731704356798070e+308 + SmallestNonzeroFloat64 = 0x1p-1022 * 0x1p-52 // 4.9406564584124654417656879286822137236505980e-324 +) + +// Integer limit values. +const ( + intSize = 32 << (^uint(0) >> 63) // 32 or 64 + + MaxInt = 1<<(intSize-1) - 1 // MaxInt32 or MaxInt64 depending on intSize. + MinInt = -1 << (intSize - 1) // MinInt32 or MinInt64 depending on intSize. + MaxInt8 = 1<<7 - 1 // 127 + MinInt8 = -1 << 7 // -128 + MaxInt16 = 1<<15 - 1 // 32767 + MinInt16 = -1 << 15 // -32768 + MaxInt32 = 1<<31 - 1 // 2147483647 + MinInt32 = -1 << 31 // -2147483648 + MaxInt64 = 1<<63 - 1 // 9223372036854775807 + MinInt64 = -1 << 63 // -9223372036854775808 + MaxUint = 1<+0(SB)/8, $0.231904681384629956E-16 +DATA coshrodataL23<>+8(SB)/8, $0.693147180559945286E+00 +DATA coshrodataL23<>+16(SB)/8, $0.144269504088896339E+01 +DATA coshrodataL23<>+24(SB)/8, $704.E0 +GLOBL coshrodataL23<>+0(SB), RODATA, $32 +DATA coshxinf<>+0(SB)/8, $0x7FF0000000000000 +GLOBL coshxinf<>+0(SB), RODATA, $8 +DATA coshxlim1<>+0(SB)/8, $800.E0 +GLOBL coshxlim1<>+0(SB), RODATA, $8 +DATA coshxaddhy<>+0(SB)/8, $0xc2f0000100003fdf +GLOBL coshxaddhy<>+0(SB), RODATA, $8 +DATA coshx4ff<>+0(SB)/8, $0x4ff0000000000000 +GLOBL coshx4ff<>+0(SB), RODATA, $8 +DATA coshe1<>+0(SB)/8, $0x3ff000000000000a +GLOBL coshe1<>+0(SB), RODATA, $8 + +// Log multiplier table +DATA coshtab<>+0(SB)/8, $0.442737824274138381E-01 +DATA coshtab<>+8(SB)/8, $0.263602189790660309E-01 +DATA coshtab<>+16(SB)/8, $0.122565642281703586E-01 +DATA coshtab<>+24(SB)/8, $0.143757052860721398E-02 +DATA coshtab<>+32(SB)/8, $-.651375034121276075E-02 +DATA coshtab<>+40(SB)/8, $-.119317678849450159E-01 +DATA coshtab<>+48(SB)/8, $-.150868749549871069E-01 +DATA coshtab<>+56(SB)/8, $-.161992609578469234E-01 +DATA coshtab<>+64(SB)/8, $-.154492360403337917E-01 +DATA coshtab<>+72(SB)/8, $-.129850717389178721E-01 +DATA coshtab<>+80(SB)/8, $-.892902649276657891E-02 +DATA coshtab<>+88(SB)/8, $-.338202636596794887E-02 +DATA coshtab<>+96(SB)/8, $0.357266307045684762E-02 +DATA coshtab<>+104(SB)/8, $0.118665304327406698E-01 +DATA coshtab<>+112(SB)/8, $0.214434994118118914E-01 +DATA coshtab<>+120(SB)/8, $0.322580645161290314E-01 +GLOBL coshtab<>+0(SB), RODATA, $128 + +// Minimax polynomial approximations +DATA coshe2<>+0(SB)/8, $0.500000000000004237e+00 +GLOBL coshe2<>+0(SB), RODATA, $8 +DATA coshe3<>+0(SB)/8, $0.166666666630345592e+00 +GLOBL coshe3<>+0(SB), RODATA, $8 +DATA coshe4<>+0(SB)/8, $0.416666664838056960e-01 +GLOBL coshe4<>+0(SB), RODATA, $8 +DATA coshe5<>+0(SB)/8, $0.833349307718286047e-02 +GLOBL coshe5<>+0(SB), RODATA, $8 +DATA coshe6<>+0(SB)/8, $0.138926439368309441e-02 +GLOBL coshe6<>+0(SB), RODATA, $8 + +// Cosh returns the hyperbolic cosine of x. +// +// Special cases are: +// Cosh(±0) = 1 +// Cosh(±Inf) = +Inf +// Cosh(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·coshAsm(SB),NOSPLIT,$0-16 + FMOVD x+0(FP), F0 + MOVD $coshrodataL23<>+0(SB), R9 + LTDBR F0, F0 + MOVD $0x4086000000000000, R2 + MOVD $0x4086000000000000, R3 + BLTU L19 + FMOVD F0, F4 +L2: + WORD $0xED409018 //cdb %f4,.L24-.L23(%r9) + BYTE $0x00 + BYTE $0x19 + BGE L14 //jnl .L14 + BVS L14 + WFCEDBS V4, V4, V2 + BEQ L20 +L1: + FMOVD F0, ret+8(FP) + RET + +L14: + WFCEDBS V4, V4, V2 + BVS L1 + MOVD $coshxlim1<>+0(SB), R1 + FMOVD 0(R1), F2 + WFCHEDBS V4, V2, V2 + BEQ L21 + MOVD $coshxaddhy<>+0(SB), R1 + FMOVD coshrodataL23<>+16(SB), F5 + FMOVD 0(R1), F2 + WFMSDB V0, V5, V2, V5 + FMOVD coshrodataL23<>+8(SB), F3 + FADD F5, F2 + MOVD $coshe6<>+0(SB), R1 + WFMSDB V2, V3, V0, V3 + FMOVD 0(R1), F6 + WFMDB V3, V3, V1 + MOVD $coshe4<>+0(SB), R1 + FMOVD coshrodataL23<>+0(SB), F7 + WFMADB V2, V7, V3, V2 + FMOVD 0(R1), F3 + MOVD $coshe5<>+0(SB), R1 + WFMADB V1, V6, V3, V6 + FMOVD 0(R1), F7 + MOVD $coshe3<>+0(SB), R1 + FMOVD 0(R1), F3 + WFMADB V1, V7, V3, V7 + FNEG F2, F3 + LGDR F5, R1 + MOVD $coshe2<>+0(SB), R3 + WFCEDBS V4, V0, V0 + FMOVD 0(R3), F5 + MOVD $coshe1<>+0(SB), R3 + WFMADB V1, V6, V5, V6 + FMOVD 0(R3), F5 + RISBGN $0, $15, $48, R1, R2 + WFMADB V1, V7, V5, V1 + BVS L22 + RISBGZ $57, $60, $3, R1, R4 + MOVD $coshtab<>+0(SB), R3 + WFMADB V3, V6, V1, V6 + WORD $0x68043000 //ld %f0,0(%r4,%r3) + FMSUB F0, F3, F2 + WORD $0xA71AF000 //ahi %r1,-4096 + WFMADB V2, V6, V0, V6 +L17: + RISBGN $0, $15, $48, R1, R2 + LDGR R2, F2 + FMADD F2, F6, F2 + MOVD $coshx4ff<>+0(SB), R1 + FMOVD 0(R1), F0 + FMUL F2, F0 + FMOVD F0, ret+8(FP) + RET + +L19: + FNEG F0, F4 + BR L2 +L20: + MOVD $coshxaddhy<>+0(SB), R1 + FMOVD coshrodataL23<>+16(SB), F3 + FMOVD 0(R1), F2 + WFMSDB V0, V3, V2, V3 + FMOVD coshrodataL23<>+8(SB), F4 + FADD F3, F2 + MOVD $coshe6<>+0(SB), R1 + FMSUB F4, F2, F0 + FMOVD 0(R1), F6 + WFMDB V0, V0, V1 + MOVD $coshe4<>+0(SB), R1 + FMOVD 0(R1), F4 + MOVD $coshe5<>+0(SB), R1 + FMOVD coshrodataL23<>+0(SB), F5 + WFMADB V1, V6, V4, V6 + FMADD F5, F2, F0 + FMOVD 0(R1), F2 + MOVD $coshe3<>+0(SB), R1 + FMOVD 0(R1), F4 + WFMADB V1, V2, V4, V2 + MOVD $coshe2<>+0(SB), R1 + FMOVD 0(R1), F5 + FNEG F0, F4 + WFMADB V1, V6, V5, V6 + MOVD $coshe1<>+0(SB), R1 + FMOVD 0(R1), F5 + WFMADB V1, V2, V5, V1 + LGDR F3, R1 + MOVD $coshtab<>+0(SB), R5 + WFMADB V4, V6, V1, V3 + RISBGZ $57, $60, $3, R1, R4 + WFMSDB V4, V6, V1, V6 + WORD $0x68145000 //ld %f1,0(%r4,%r5) + WFMSDB V4, V1, V0, V2 + WORD $0xA7487FBE //lhi %r4,32702 + FMADD F3, F2, F1 + SUBW R1, R4 + RISBGZ $57, $60, $3, R4, R12 + WORD $0x682C5000 //ld %f2,0(%r12,%r5) + FMSUB F2, F4, F0 + RISBGN $0, $15, $48, R1, R2 + WFMADB V0, V6, V2, V6 + RISBGN $0, $15, $48, R4, R3 + LDGR R2, F2 + LDGR R3, F0 + FMADD F2, F1, F2 + FMADD F0, F6, F0 + FADD F2, F0 + FMOVD F0, ret+8(FP) + RET + +L22: + WORD $0xA7387FBE //lhi %r3,32702 + MOVD $coshtab<>+0(SB), R4 + SUBW R1, R3 + WFMSDB V3, V6, V1, V6 + RISBGZ $57, $60, $3, R3, R3 + WORD $0x68034000 //ld %f0,0(%r3,%r4) + FMSUB F0, F3, F2 + WORD $0xA7386FBE //lhi %r3,28606 + WFMADB V2, V6, V0, V6 + SUBW R1, R3, R1 + BR L17 +L21: + MOVD $coshxinf<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET + diff --git a/go/src/math/dim.go b/go/src/math/dim.go new file mode 100644 index 0000000000000000000000000000000000000000..f369f70f000fbb69823dfe987af6b6ac0191c756 --- /dev/null +++ b/go/src/math/dim.go @@ -0,0 +1,100 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Dim returns the maximum of x-y or 0. +// +// Special cases are: +// +// Dim(+Inf, +Inf) = NaN +// Dim(-Inf, -Inf) = NaN +// Dim(x, NaN) = Dim(NaN, x) = NaN +func Dim(x, y float64) float64 { + // The special cases result in NaN after the subtraction: + // +Inf - +Inf = NaN + // -Inf - -Inf = NaN + // NaN - y = NaN + // x - NaN = NaN + v := x - y + if v <= 0 { + // v is negative or 0 + return 0 + } + // v is positive or NaN + return v +} + +// Max returns the larger of x or y. +// +// Special cases are: +// +// Max(x, +Inf) = Max(+Inf, x) = +Inf +// Max(x, NaN) = Max(NaN, x) = NaN +// Max(+0, ±0) = Max(±0, +0) = +0 +// Max(-0, -0) = -0 +// +// Note that this differs from the built-in function max when called +// with NaN and +Inf. +func Max(x, y float64) float64 { + if haveArchMax { + return archMax(x, y) + } + return max(x, y) +} + +func max(x, y float64) float64 { + // special cases + switch { + case IsInf(x, 1) || IsInf(y, 1): + return Inf(1) + case IsNaN(x) || IsNaN(y): + return NaN() + case x == 0 && x == y: + if Signbit(x) { + return y + } + return x + } + if x > y { + return x + } + return y +} + +// Min returns the smaller of x or y. +// +// Special cases are: +// +// Min(x, -Inf) = Min(-Inf, x) = -Inf +// Min(x, NaN) = Min(NaN, x) = NaN +// Min(-0, ±0) = Min(±0, -0) = -0 +// +// Note that this differs from the built-in function min when called +// with NaN and -Inf. +func Min(x, y float64) float64 { + if haveArchMin { + return archMin(x, y) + } + return min(x, y) +} + +func min(x, y float64) float64 { + // special cases + switch { + case IsInf(x, -1) || IsInf(y, -1): + return Inf(-1) + case IsNaN(x) || IsNaN(y): + return NaN() + case x == 0 && x == y: + if Signbit(x) { + return x + } + return y + } + if x < y { + return x + } + return y +} diff --git a/go/src/math/dim_amd64.s b/go/src/math/dim_amd64.s new file mode 100644 index 0000000000000000000000000000000000000000..253f03b97e713314a6ffa395f7a92b69e16ee634 --- /dev/null +++ b/go/src/math/dim_amd64.s @@ -0,0 +1,98 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define PosInf 0x7FF0000000000000 +#define NaN 0x7FF8000000000001 +#define NegInf 0xFFF0000000000000 + +// func ·archMax(x, y float64) float64 +TEXT ·archMax(SB),NOSPLIT,$0 + // +Inf special cases + MOVQ $PosInf, AX + MOVQ x+0(FP), R8 + CMPQ AX, R8 + JEQ isPosInf + MOVQ y+8(FP), R9 + CMPQ AX, R9 + JEQ isPosInf + // NaN special cases + MOVQ $~(1<<63), DX // bit mask + MOVQ $PosInf, AX + MOVQ R8, BX + ANDQ DX, BX // x = |x| + CMPQ AX, BX + JLT isMaxNaN + MOVQ R9, CX + ANDQ DX, CX // y = |y| + CMPQ AX, CX + JLT isMaxNaN + // ±0 special cases + ORQ CX, BX + JEQ isMaxZero + + MOVQ R8, X0 + MOVQ R9, X1 + MAXSD X1, X0 + MOVSD X0, ret+16(FP) + RET +isMaxNaN: // return NaN + MOVQ $NaN, AX +isPosInf: // return +Inf + MOVQ AX, ret+16(FP) + RET +isMaxZero: + MOVQ $(1<<63), AX // -0.0 + CMPQ AX, R8 + JEQ +3(PC) + MOVQ R8, ret+16(FP) // return 0 + RET + MOVQ R9, ret+16(FP) // return other 0 + RET + +// func archMin(x, y float64) float64 +TEXT ·archMin(SB),NOSPLIT,$0 + // -Inf special cases + MOVQ $NegInf, AX + MOVQ x+0(FP), R8 + CMPQ AX, R8 + JEQ isNegInf + MOVQ y+8(FP), R9 + CMPQ AX, R9 + JEQ isNegInf + // NaN special cases + MOVQ $~(1<<63), DX + MOVQ $PosInf, AX + MOVQ R8, BX + ANDQ DX, BX // x = |x| + CMPQ AX, BX + JLT isMinNaN + MOVQ R9, CX + ANDQ DX, CX // y = |y| + CMPQ AX, CX + JLT isMinNaN + // ±0 special cases + ORQ CX, BX + JEQ isMinZero + + MOVQ R8, X0 + MOVQ R9, X1 + MINSD X1, X0 + MOVSD X0, ret+16(FP) + RET +isMinNaN: // return NaN + MOVQ $NaN, AX +isNegInf: // return -Inf + MOVQ AX, ret+16(FP) + RET +isMinZero: + MOVQ $(1<<63), AX // -0.0 + CMPQ AX, R8 + JEQ +3(PC) + MOVQ R9, ret+16(FP) // return other 0 + RET + MOVQ R8, ret+16(FP) // return -0 + RET + diff --git a/go/src/math/dim_arm64.s b/go/src/math/dim_arm64.s new file mode 100644 index 0000000000000000000000000000000000000000..f112003dc0f615a23e1ebecbb9ef946fa953e6e1 --- /dev/null +++ b/go/src/math/dim_arm64.s @@ -0,0 +1,49 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define PosInf 0x7FF0000000000000 +#define NaN 0x7FF8000000000001 +#define NegInf 0xFFF0000000000000 + +// func ·archMax(x, y float64) float64 +TEXT ·archMax(SB),NOSPLIT,$0 + // +Inf special cases + MOVD $PosInf, R0 + MOVD x+0(FP), R1 + CMP R0, R1 + BEQ isPosInf + MOVD y+8(FP), R2 + CMP R0, R2 + BEQ isPosInf + // normal case + FMOVD R1, F0 + FMOVD R2, F1 + FMAXD F0, F1, F0 + FMOVD F0, ret+16(FP) + RET +isPosInf: // return +Inf + MOVD R0, ret+16(FP) + RET + +// func archMin(x, y float64) float64 +TEXT ·archMin(SB),NOSPLIT,$0 + // -Inf special cases + MOVD $NegInf, R0 + MOVD x+0(FP), R1 + CMP R0, R1 + BEQ isNegInf + MOVD y+8(FP), R2 + CMP R0, R2 + BEQ isNegInf + // normal case + FMOVD R1, F0 + FMOVD R2, F1 + FMIND F0, F1, F0 + FMOVD F0, ret+16(FP) + RET +isNegInf: // return -Inf + MOVD R0, ret+16(FP) + RET diff --git a/go/src/math/dim_asm.go b/go/src/math/dim_asm.go new file mode 100644 index 0000000000000000000000000000000000000000..a1d23dd0962b07cc72b983e37218abaf5f6085ef --- /dev/null +++ b/go/src/math/dim_asm.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build amd64 || arm64 || loong64 || riscv64 || s390x + +package math + +const haveArchMax = true + +func archMax(x, y float64) float64 + +const haveArchMin = true + +func archMin(x, y float64) float64 diff --git a/go/src/math/dim_loong64.s b/go/src/math/dim_loong64.s new file mode 100644 index 0000000000000000000000000000000000000000..1484bf7638112348f83105834010a63a70ec99cf --- /dev/null +++ b/go/src/math/dim_loong64.s @@ -0,0 +1,77 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define PosInf 0x7FF0000000000000 +#define NaN 0x7FF8000000000001 +#define NegInf 0xFFF0000000000000 + +TEXT ·archMax(SB),NOSPLIT,$0 + MOVD x+0(FP), F0 + MOVD y+8(FP), F1 + FCLASSD F0, F2 + FCLASSD F1, F3 + + // combine x and y categories together to judge + MOVV F2, R4 + MOVV F3, R5 + OR R5, R4 + + // +Inf special cases + AND $64, R4, R5 + BNE R5, isPosInf + + // NaN special cases + AND $2, R4, R5 + BNE R5, isMaxNaN + + // normal case + FMAXD F0, F1, F0 + MOVD F0, ret+16(FP) + RET + +isMaxNaN: + MOVV $NaN, R6 + MOVV R6, ret+16(FP) + RET + +isPosInf: + MOVV $PosInf, R6 + MOVV R6, ret+16(FP) + RET + +TEXT ·archMin(SB),NOSPLIT,$0 + MOVD x+0(FP), F0 + MOVD y+8(FP), F1 + FCLASSD F0, F2 + FCLASSD F1, F3 + + // combine x and y categories together to judge + MOVV F2, R4 + MOVV F3, R5 + OR R5, R4 + + // -Inf special cases + AND $4, R4, R5 + BNE R5, isNegInf + + // NaN special cases + AND $2, R4, R5 + BNE R5, isMinNaN + + // normal case + FMIND F0, F1, F0 + MOVD F0, ret+16(FP) + RET + +isMinNaN: + MOVV $NaN, R6 + MOVV R6, ret+16(FP) + RET + +isNegInf: + MOVV $NegInf, R6 + MOVV R6, ret+16(FP) + RET diff --git a/go/src/math/dim_noasm.go b/go/src/math/dim_noasm.go new file mode 100644 index 0000000000000000000000000000000000000000..6f4917b8e8247b58152ee5d8123f9e7e600e82ea --- /dev/null +++ b/go/src/math/dim_noasm.go @@ -0,0 +1,19 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !amd64 && !arm64 && !loong64 && !riscv64 && !s390x + +package math + +const haveArchMax = false + +func archMax(x, y float64) float64 { + panic("not implemented") +} + +const haveArchMin = false + +func archMin(x, y float64) float64 { + panic("not implemented") +} diff --git a/go/src/math/dim_riscv64.s b/go/src/math/dim_riscv64.s new file mode 100644 index 0000000000000000000000000000000000000000..5b2fd3d0633f47514e570c90797d7f7039f76c2b --- /dev/null +++ b/go/src/math/dim_riscv64.s @@ -0,0 +1,70 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Values returned from an FCLASS instruction. +#define NegInf 0x001 +#define PosInf 0x080 +#define NaN 0x200 + +// func archMax(x, y float64) float64 +TEXT ·archMax(SB),NOSPLIT,$0 + MOVD x+0(FP), F0 + MOVD y+8(FP), F1 + FCLASSD F0, X5 + FCLASSD F1, X6 + + // +Inf special cases + MOV $PosInf, X7 + BEQ X7, X5, isMaxX + BEQ X7, X6, isMaxY + + // NaN special cases + MOV $NaN, X7 + BEQ X7, X5, isMaxX + BEQ X7, X6, isMaxY + + // normal case + FMAXD F0, F1, F0 + MOVD F0, ret+16(FP) + RET + +isMaxX: // return x + MOVD F0, ret+16(FP) + RET + +isMaxY: // return y + MOVD F1, ret+16(FP) + RET + +// func archMin(x, y float64) float64 +TEXT ·archMin(SB),NOSPLIT,$0 + MOVD x+0(FP), F0 + MOVD y+8(FP), F1 + FCLASSD F0, X5 + FCLASSD F1, X6 + + // -Inf special cases + MOV $NegInf, X7 + BEQ X7, X5, isMinX + BEQ X7, X6, isMinY + + // NaN special cases + MOV $NaN, X7 + BEQ X7, X5, isMinX + BEQ X7, X6, isMinY + + // normal case + FMIND F0, F1, F0 + MOVD F0, ret+16(FP) + RET + +isMinX: // return x + MOVD F0, ret+16(FP) + RET + +isMinY: // return y + MOVD F1, ret+16(FP) + RET diff --git a/go/src/math/dim_s390x.s b/go/src/math/dim_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..12770261f2e78d325f770f7e5af7aaa6f049a76b --- /dev/null +++ b/go/src/math/dim_s390x.s @@ -0,0 +1,96 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Based on dim_amd64.s + +#include "textflag.h" + +#define PosInf 0x7FF0000000000000 +#define NaN 0x7FF8000000000001 +#define NegInf 0xFFF0000000000000 + +// func ·Max(x, y float64) float64 +TEXT ·archMax(SB),NOSPLIT,$0 + // +Inf special cases + MOVD $PosInf, R4 + MOVD x+0(FP), R8 + CMPUBEQ R4, R8, isPosInf + MOVD y+8(FP), R9 + CMPUBEQ R4, R9, isPosInf + // NaN special cases + MOVD $~(1<<63), R5 // bit mask + MOVD $PosInf, R4 + MOVD R8, R2 + AND R5, R2 // x = |x| + CMPUBLT R4, R2, isMaxNaN + MOVD R9, R3 + AND R5, R3 // y = |y| + CMPUBLT R4, R3, isMaxNaN + // ±0 special cases + OR R3, R2 + BEQ isMaxZero + + FMOVD x+0(FP), F1 + FMOVD y+8(FP), F2 + FCMPU F2, F1 + BGT +3(PC) + FMOVD F1, ret+16(FP) + RET + FMOVD F2, ret+16(FP) + RET +isMaxNaN: // return NaN + MOVD $NaN, R4 +isPosInf: // return +Inf + MOVD R4, ret+16(FP) + RET +isMaxZero: + MOVD $(1<<63), R4 // -0.0 + CMPUBEQ R4, R8, +3(PC) + MOVD R8, ret+16(FP) // return 0 + RET + MOVD R9, ret+16(FP) // return other 0 + RET + +// func archMin(x, y float64) float64 +TEXT ·archMin(SB),NOSPLIT,$0 + // -Inf special cases + MOVD $NegInf, R4 + MOVD x+0(FP), R8 + CMPUBEQ R4, R8, isNegInf + MOVD y+8(FP), R9 + CMPUBEQ R4, R9, isNegInf + // NaN special cases + MOVD $~(1<<63), R5 + MOVD $PosInf, R4 + MOVD R8, R2 + AND R5, R2 // x = |x| + CMPUBLT R4, R2, isMinNaN + MOVD R9, R3 + AND R5, R3 // y = |y| + CMPUBLT R4, R3, isMinNaN + // ±0 special cases + OR R3, R2 + BEQ isMinZero + + FMOVD x+0(FP), F1 + FMOVD y+8(FP), F2 + FCMPU F2, F1 + BLT +3(PC) + FMOVD F1, ret+16(FP) + RET + FMOVD F2, ret+16(FP) + RET +isMinNaN: // return NaN + MOVD $NaN, R4 +isNegInf: // return -Inf + MOVD R4, ret+16(FP) + RET +isMinZero: + MOVD $(1<<63), R4 // -0.0 + CMPUBEQ R4, R8, +3(PC) + MOVD R9, ret+16(FP) // return other 0 + RET + MOVD R8, ret+16(FP) // return -0 + RET + diff --git a/go/src/math/erf.go b/go/src/math/erf.go new file mode 100644 index 0000000000000000000000000000000000000000..ba00c7d03edc1101c4705cc6b79649b5c094e556 --- /dev/null +++ b/go/src/math/erf.go @@ -0,0 +1,351 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point error function and complementary error function. +*/ + +// The original C code and the long comment below are +// from FreeBSD's /usr/src/lib/msun/src/s_erf.c and +// came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// double erf(double x) +// double erfc(double x) +// x +// 2 |\ +// erf(x) = --------- | exp(-t*t)dt +// sqrt(pi) \| +// 0 +// +// erfc(x) = 1-erf(x) +// Note that +// erf(-x) = -erf(x) +// erfc(-x) = 2 - erfc(x) +// +// Method: +// 1. For |x| in [0, 0.84375] +// erf(x) = x + x*R(x**2) +// erfc(x) = 1 - erf(x) if x in [-.84375,0.25] +// = 0.5 + ((0.5-x)-x*R) if x in [0.25,0.84375] +// where R = P/Q where P is an odd poly of degree 8 and +// Q is an odd poly of degree 10. +// -57.90 +// | R - (erf(x)-x)/x | <= 2 +// +// +// Remark. The formula is derived by noting +// erf(x) = (2/sqrt(pi))*(x - x**3/3 + x**5/10 - x**7/42 + ....) +// and that +// 2/sqrt(pi) = 1.128379167095512573896158903121545171688 +// is close to one. The interval is chosen because the fix +// point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is +// near 0.6174), and by some experiment, 0.84375 is chosen to +// guarantee the error is less than one ulp for erf. +// +// 2. For |x| in [0.84375,1.25], let s = |x| - 1, and +// c = 0.84506291151 rounded to single (24 bits) +// erf(x) = sign(x) * (c + P1(s)/Q1(s)) +// erfc(x) = (1-c) - P1(s)/Q1(s) if x > 0 +// 1+(c+P1(s)/Q1(s)) if x < 0 +// |P1/Q1 - (erf(|x|)-c)| <= 2**-59.06 +// Remark: here we use the taylor series expansion at x=1. +// erf(1+s) = erf(1) + s*Poly(s) +// = 0.845.. + P1(s)/Q1(s) +// That is, we use rational approximation to approximate +// erf(1+s) - (c = (single)0.84506291151) +// Note that |P1/Q1|< 0.078 for x in [0.84375,1.25] +// where +// P1(s) = degree 6 poly in s +// Q1(s) = degree 6 poly in s +// +// 3. For x in [1.25,1/0.35(~2.857143)], +// erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1) +// erf(x) = 1 - erfc(x) +// where +// R1(z) = degree 7 poly in z, (z=1/x**2) +// S1(z) = degree 8 poly in z +// +// 4. For x in [1/0.35,28] +// erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0 +// = 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6 x >= 28 +// erf(x) = sign(x) *(1 - tiny) (raise inexact) +// erfc(x) = tiny*tiny (raise underflow) if x > 0 +// = 2 - tiny if x<0 +// +// 7. Special case: +// erf(0) = 0, erf(inf) = 1, erf(-inf) = -1, +// erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2, +// erfc/erf(NaN) is NaN + +const ( + erx = 8.45062911510467529297e-01 // 0x3FEB0AC160000000 + // Coefficients for approximation to erf in [0, 0.84375] + efx = 1.28379167095512586316e-01 // 0x3FC06EBA8214DB69 + efx8 = 1.02703333676410069053e+00 // 0x3FF06EBA8214DB69 + pp0 = 1.28379167095512558561e-01 // 0x3FC06EBA8214DB68 + pp1 = -3.25042107247001499370e-01 // 0xBFD4CD7D691CB913 + pp2 = -2.84817495755985104766e-02 // 0xBF9D2A51DBD7194F + pp3 = -5.77027029648944159157e-03 // 0xBF77A291236668E4 + pp4 = -2.37630166566501626084e-05 // 0xBEF8EAD6120016AC + qq1 = 3.97917223959155352819e-01 // 0x3FD97779CDDADC09 + qq2 = 6.50222499887672944485e-02 // 0x3FB0A54C5536CEBA + qq3 = 5.08130628187576562776e-03 // 0x3F74D022C4D36B0F + qq4 = 1.32494738004321644526e-04 // 0x3F215DC9221C1A10 + qq5 = -3.96022827877536812320e-06 // 0xBED09C4342A26120 + // Coefficients for approximation to erf in [0.84375, 1.25] + pa0 = -2.36211856075265944077e-03 // 0xBF6359B8BEF77538 + pa1 = 4.14856118683748331666e-01 // 0x3FDA8D00AD92B34D + pa2 = -3.72207876035701323847e-01 // 0xBFD7D240FBB8C3F1 + pa3 = 3.18346619901161753674e-01 // 0x3FD45FCA805120E4 + pa4 = -1.10894694282396677476e-01 // 0xBFBC63983D3E28EC + pa5 = 3.54783043256182359371e-02 // 0x3FA22A36599795EB + pa6 = -2.16637559486879084300e-03 // 0xBF61BF380A96073F + qa1 = 1.06420880400844228286e-01 // 0x3FBB3E6618EEE323 + qa2 = 5.40397917702171048937e-01 // 0x3FE14AF092EB6F33 + qa3 = 7.18286544141962662868e-02 // 0x3FB2635CD99FE9A7 + qa4 = 1.26171219808761642112e-01 // 0x3FC02660E763351F + qa5 = 1.36370839120290507362e-02 // 0x3F8BEDC26B51DD1C + qa6 = 1.19844998467991074170e-02 // 0x3F888B545735151D + // Coefficients for approximation to erfc in [1.25, 1/0.35] + ra0 = -9.86494403484714822705e-03 // 0xBF843412600D6435 + ra1 = -6.93858572707181764372e-01 // 0xBFE63416E4BA7360 + ra2 = -1.05586262253232909814e+01 // 0xC0251E0441B0E726 + ra3 = -6.23753324503260060396e+01 // 0xC04F300AE4CBA38D + ra4 = -1.62396669462573470355e+02 // 0xC0644CB184282266 + ra5 = -1.84605092906711035994e+02 // 0xC067135CEBCCABB2 + ra6 = -8.12874355063065934246e+01 // 0xC054526557E4D2F2 + ra7 = -9.81432934416914548592e+00 // 0xC023A0EFC69AC25C + sa1 = 1.96512716674392571292e+01 // 0x4033A6B9BD707687 + sa2 = 1.37657754143519042600e+02 // 0x4061350C526AE721 + sa3 = 4.34565877475229228821e+02 // 0x407B290DD58A1A71 + sa4 = 6.45387271733267880336e+02 // 0x40842B1921EC2868 + sa5 = 4.29008140027567833386e+02 // 0x407AD02157700314 + sa6 = 1.08635005541779435134e+02 // 0x405B28A3EE48AE2C + sa7 = 6.57024977031928170135e+00 // 0x401A47EF8E484A93 + sa8 = -6.04244152148580987438e-02 // 0xBFAEEFF2EE749A62 + // Coefficients for approximation to erfc in [1/.35, 28] + rb0 = -9.86494292470009928597e-03 // 0xBF84341239E86F4A + rb1 = -7.99283237680523006574e-01 // 0xBFE993BA70C285DE + rb2 = -1.77579549177547519889e+01 // 0xC031C209555F995A + rb3 = -1.60636384855821916062e+02 // 0xC064145D43C5ED98 + rb4 = -6.37566443368389627722e+02 // 0xC083EC881375F228 + rb5 = -1.02509513161107724954e+03 // 0xC09004616A2E5992 + rb6 = -4.83519191608651397019e+02 // 0xC07E384E9BDC383F + sb1 = 3.03380607434824582924e+01 // 0x403E568B261D5190 + sb2 = 3.25792512996573918826e+02 // 0x40745CAE221B9F0A + sb3 = 1.53672958608443695994e+03 // 0x409802EB189D5118 + sb4 = 3.19985821950859553908e+03 // 0x40A8FFB7688C246A + sb5 = 2.55305040643316442583e+03 // 0x40A3F219CEDF3BE6 + sb6 = 4.74528541206955367215e+02 // 0x407DA874E79FE763 + sb7 = -2.24409524465858183362e+01 // 0xC03670E242712D62 +) + +// Erf returns the error function of x. +// +// Special cases are: +// +// Erf(+Inf) = 1 +// Erf(-Inf) = -1 +// Erf(NaN) = NaN +func Erf(x float64) float64 { + if haveArchErf { + return archErf(x) + } + return erf(x) +} + +func erf(x float64) float64 { + const ( + VeryTiny = 2.848094538889218e-306 // 0x0080000000000000 + Small = 1.0 / (1 << 28) // 2**-28 + ) + // special cases + switch { + case IsNaN(x): + return NaN() + case IsInf(x, 1): + return 1 + case IsInf(x, -1): + return -1 + } + sign := false + if x < 0 { + x = -x + sign = true + } + if x < 0.84375 { // |x| < 0.84375 + var temp float64 + if x < Small { // |x| < 2**-28 + if x < VeryTiny { + temp = 0.125 * (8.0*x + efx8*x) // avoid underflow + } else { + temp = x + efx*x + } + } else { + z := x * x + r := pp0 + z*(pp1+z*(pp2+z*(pp3+z*pp4))) + s := 1 + z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5)))) + y := r / s + temp = x + x*y + } + if sign { + return -temp + } + return temp + } + if x < 1.25 { // 0.84375 <= |x| < 1.25 + s := x - 1 + P := pa0 + s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6))))) + Q := 1 + s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6))))) + if sign { + return -erx - P/Q + } + return erx + P/Q + } + if x >= 6 { // inf > |x| >= 6 + if sign { + return -1 + } + return 1 + } + s := 1 / (x * x) + var R, S float64 + if x < 1/0.35 { // |x| < 1 / 0.35 ~ 2.857143 + R = ra0 + s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7)))))) + S = 1 + s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8))))))) + } else { // |x| >= 1 / 0.35 ~ 2.857143 + R = rb0 + s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6))))) + S = 1 + s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7)))))) + } + z := Float64frombits(Float64bits(x) & 0xffffffff00000000) // pseudo-single (20-bit) precision x + r := Exp(-z*z-0.5625) * Exp((z-x)*(z+x)+R/S) + if sign { + return r/x - 1 + } + return 1 - r/x +} + +// Erfc returns the complementary error function of x. +// +// Special cases are: +// +// Erfc(+Inf) = 0 +// Erfc(-Inf) = 2 +// Erfc(NaN) = NaN +func Erfc(x float64) float64 { + if haveArchErfc { + return archErfc(x) + } + return erfc(x) +} + +func erfc(x float64) float64 { + const Tiny = 1.0 / (1 << 56) // 2**-56 + // special cases + switch { + case IsNaN(x): + return NaN() + case IsInf(x, 1): + return 0 + case IsInf(x, -1): + return 2 + } + sign := false + if x < 0 { + x = -x + sign = true + } + if x < 0.84375 { // |x| < 0.84375 + var temp float64 + if x < Tiny { // |x| < 2**-56 + temp = x + } else { + z := x * x + r := pp0 + z*(pp1+z*(pp2+z*(pp3+z*pp4))) + s := 1 + z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5)))) + y := r / s + if x < 0.25 { // |x| < 1/4 + temp = x + x*y + } else { + temp = 0.5 + (x*y + (x - 0.5)) + } + } + if sign { + return 1 + temp + } + return 1 - temp + } + if x < 1.25 { // 0.84375 <= |x| < 1.25 + s := x - 1 + P := pa0 + s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6))))) + Q := 1 + s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6))))) + if sign { + return 1 + erx + P/Q + } + return 1 - erx - P/Q + + } + if x < 28 { // |x| < 28 + s := 1 / (x * x) + var R, S float64 + if x < 1/0.35 { // |x| < 1 / 0.35 ~ 2.857143 + R = ra0 + s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7)))))) + S = 1 + s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8))))))) + } else { // |x| >= 1 / 0.35 ~ 2.857143 + if sign && x > 6 { + return 2 // x < -6 + } + R = rb0 + s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6))))) + S = 1 + s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7)))))) + } + z := Float64frombits(Float64bits(x) & 0xffffffff00000000) // pseudo-single (20-bit) precision x + r := Exp(-z*z-0.5625) * Exp((z-x)*(z+x)+R/S) + if sign { + return 2 - r/x + } + return r / x + } + if sign { + return 2 + } + return 0 +} diff --git a/go/src/math/erf_s390x.s b/go/src/math/erf_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..99ab436e0945147eb19fe8f444abe58ddea4eecf --- /dev/null +++ b/go/src/math/erf_s390x.s @@ -0,0 +1,293 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA ·erfrodataL13<> + 0(SB)/8, $0.243673229298474689E+01 +DATA ·erfrodataL13<> + 8(SB)/8, $-.654905018503145600E+00 +DATA ·erfrodataL13<> + 16(SB)/8, $0.404669310217538718E+01 +DATA ·erfrodataL13<> + 24(SB)/8, $-.564189219162765367E+00 +DATA ·erfrodataL13<> + 32(SB)/8, $-.200104300906596851E+01 +DATA ·erfrodataL13<> + 40(SB)/8, $0.5 +DATA ·erfrodataL13<> + 48(SB)/8, $0.144070097650207154E+00 +DATA ·erfrodataL13<> + 56(SB)/8, $-.116697735205906191E+00 +DATA ·erfrodataL13<> + 64(SB)/8, $0.256847684882319665E-01 +DATA ·erfrodataL13<> + 72(SB)/8, $-.510805169106229148E-02 +DATA ·erfrodataL13<> + 80(SB)/8, $0.885258164825590267E-03 +DATA ·erfrodataL13<> + 88(SB)/8, $-.133861989591931411E-03 +DATA ·erfrodataL13<> + 96(SB)/8, $0.178294867340272534E-04 +DATA ·erfrodataL13<> + 104(SB)/8, $-.211436095674019218E-05 +DATA ·erfrodataL13<> + 112(SB)/8, $0.225503753499344434E-06 +DATA ·erfrodataL13<> + 120(SB)/8, $-.218247939190783624E-07 +DATA ·erfrodataL13<> + 128(SB)/8, $0.193179206264594029E-08 +DATA ·erfrodataL13<> + 136(SB)/8, $-.157440643541715319E-09 +DATA ·erfrodataL13<> + 144(SB)/8, $0.118878583237342616E-10 +DATA ·erfrodataL13<> + 152(SB)/8, $0.554289288424588473E-13 +DATA ·erfrodataL13<> + 160(SB)/8, $-.277649758489502214E-14 +DATA ·erfrodataL13<> + 168(SB)/8, $-.839318416990049443E-12 +DATA ·erfrodataL13<> + 176(SB)/8, $-2.25 +DATA ·erfrodataL13<> + 184(SB)/8, $.12837916709551258632 +DATA ·erfrodataL13<> + 192(SB)/8, $1.0 +DATA ·erfrodataL13<> + 200(SB)/8, $0.500000000000004237e+00 +DATA ·erfrodataL13<> + 208(SB)/8, $1.0 +DATA ·erfrodataL13<> + 216(SB)/8, $0.416666664838056960e-01 +DATA ·erfrodataL13<> + 224(SB)/8, $0.166666666630345592e+00 +DATA ·erfrodataL13<> + 232(SB)/8, $0.138926439368309441e-02 +DATA ·erfrodataL13<> + 240(SB)/8, $0.833349307718286047e-02 +DATA ·erfrodataL13<> + 248(SB)/8, $-.693147180559945286e+00 +DATA ·erfrodataL13<> + 256(SB)/8, $-.144269504088896339e+01 +DATA ·erfrodataL13<> + 264(SB)/8, $281475245147134.9375 +DATA ·erfrodataL13<> + 272(SB)/8, $0.358256136398192529E+01 +DATA ·erfrodataL13<> + 280(SB)/8, $-.554084396500738270E+00 +DATA ·erfrodataL13<> + 288(SB)/8, $0.203630123025312046E+02 +DATA ·erfrodataL13<> + 296(SB)/8, $-.735750304705934424E+01 +DATA ·erfrodataL13<> + 304(SB)/8, $0.250491598091071797E+02 +DATA ·erfrodataL13<> + 312(SB)/8, $-.118955882760959931E+02 +DATA ·erfrodataL13<> + 320(SB)/8, $0.942903335085524187E+01 +DATA ·erfrodataL13<> + 328(SB)/8, $-.564189522219085689E+00 +DATA ·erfrodataL13<> + 336(SB)/8, $-.503767199403555540E+01 +DATA ·erfrodataL13<> + 344(SB)/8, $0xbbc79ca10c924223 +DATA ·erfrodataL13<> + 352(SB)/8, $0.004099975562609307E+01 +DATA ·erfrodataL13<> + 360(SB)/8, $-.324434353381296556E+00 +DATA ·erfrodataL13<> + 368(SB)/8, $0.945204812084476250E-01 +DATA ·erfrodataL13<> + 376(SB)/8, $-.221407443830058214E-01 +DATA ·erfrodataL13<> + 384(SB)/8, $0.426072376238804349E-02 +DATA ·erfrodataL13<> + 392(SB)/8, $-.692229229127016977E-03 +DATA ·erfrodataL13<> + 400(SB)/8, $0.971111253652087188E-04 +DATA ·erfrodataL13<> + 408(SB)/8, $-.119752226272050504E-04 +DATA ·erfrodataL13<> + 416(SB)/8, $0.131662993588532278E-05 +DATA ·erfrodataL13<> + 424(SB)/8, $0.115776482315851236E-07 +DATA ·erfrodataL13<> + 432(SB)/8, $-.780118522218151687E-09 +DATA ·erfrodataL13<> + 440(SB)/8, $-.130465975877241088E-06 +DATA ·erfrodataL13<> + 448(SB)/8, $-0.25 +GLOBL ·erfrodataL13<> + 0(SB), RODATA, $456 + +// Table of log correction terms +DATA ·erftab2066<> + 0(SB)/8, $0.442737824274138381e-01 +DATA ·erftab2066<> + 8(SB)/8, $0.263602189790660309e-01 +DATA ·erftab2066<> + 16(SB)/8, $0.122565642281703586e-01 +DATA ·erftab2066<> + 24(SB)/8, $0.143757052860721398e-02 +DATA ·erftab2066<> + 32(SB)/8, $-.651375034121276075e-02 +DATA ·erftab2066<> + 40(SB)/8, $-.119317678849450159e-01 +DATA ·erftab2066<> + 48(SB)/8, $-.150868749549871069e-01 +DATA ·erftab2066<> + 56(SB)/8, $-.161992609578469234e-01 +DATA ·erftab2066<> + 64(SB)/8, $-.154492360403337917e-01 +DATA ·erftab2066<> + 72(SB)/8, $-.129850717389178721e-01 +DATA ·erftab2066<> + 80(SB)/8, $-.892902649276657891e-02 +DATA ·erftab2066<> + 88(SB)/8, $-.338202636596794887e-02 +DATA ·erftab2066<> + 96(SB)/8, $0.357266307045684762e-02 +DATA ·erftab2066<> + 104(SB)/8, $0.118665304327406698e-01 +DATA ·erftab2066<> + 112(SB)/8, $0.214434994118118914e-01 +DATA ·erftab2066<> + 120(SB)/8, $0.322580645161290314e-01 +GLOBL ·erftab2066<> + 0(SB), RODATA, $128 + +// Table of +/- 1.0 +DATA ·erftab12067<> + 0(SB)/8, $1.0 +DATA ·erftab12067<> + 8(SB)/8, $-1.0 +GLOBL ·erftab12067<> + 0(SB), RODATA, $16 + +// Erf returns the error function of the argument. +// +// Special cases are: +// Erf(+Inf) = 1 +// Erf(-Inf) = -1 +// Erf(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·erfAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·erfrodataL13<>+0(SB), R5 + LGDR F0, R1 + FMOVD F0, F6 + SRAD $48, R1 + MOVH $16383, R3 + RISBGZ $49, $63, $0, R1, R2 + MOVW R2, R6 + MOVW R3, R7 + CMPBGT R6, R7, L2 + MOVH $12287, R1 + MOVW R1, R7 + CMPBLE R6, R7 ,L12 + MOVH $16367, R1 + MOVW R1, R7 + CMPBGT R6, R7, L5 + FMOVD 448(R5), F4 + FMADD F0, F0, F4 + FMOVD 440(R5), F3 + WFMDB V4, V4, V2 + FMOVD 432(R5), F0 + FMOVD 424(R5), F1 + WFMADB V2, V0, V3, V0 + FMOVD 416(R5), F3 + WFMADB V2, V1, V3, V1 + FMOVD 408(R5), F5 + FMOVD 400(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V1, V3, V1 + FMOVD 392(R5), F5 + FMOVD 384(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V1, V3, V1 + FMOVD 376(R5), F5 + FMOVD 368(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V1, V3, V1 + FMOVD 360(R5), F5 + FMOVD 352(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V1, V3, V2 + WFMADB V4, V0, V2, V0 + WFMADB V6, V0, V6, V0 +L1: + FMOVD F0, ret+8(FP) + RET +L2: + MOVH R1, R1 + MOVH $16407, R3 + SRW $31, R1, R1 + MOVW R2, R6 + MOVW R3, R7 + CMPBLE R6, R7, L6 + MOVW R1, R1 + SLD $3, R1, R1 + MOVD $·erftab12067<>+0(SB), R3 + WORD $0x68013000 //ld %f0,0(%r1,%r3) + MOVH $32751, R1 + MOVW R1, R7 + CMPBGT R6, R7, L7 + FMOVD 344(R5), F2 + FMADD F2, F0, F0 +L7: + WFCEDBS V6, V6, V2 + BEQ L1 + FMOVD F6, F0 + FMOVD F0, ret+8(FP) + RET + +L6: + MOVW R1, R1 + SLD $3, R1, R1 + MOVD $·erftab12067<>+0(SB), R4 + WFMDB V0, V0, V1 + MOVH $0x0, R3 + WORD $0x68014000 //ld %f0,0(%r1,%r4) + MOVH $16399, R1 + MOVW R2, R6 + MOVW R1, R7 + CMPBGT R6, R7, L8 + FMOVD 336(R5), F3 + FMOVD 328(R5), F2 + FMOVD F1, F4 + WFMADB V1, V2, V3, V2 + WORD $0xED405140 //adb %f4,.L30-.L13(%r5) + BYTE $0x00 + BYTE $0x1A + FMOVD 312(R5), F3 + WFMADB V1, V2, V3, V2 + FMOVD 304(R5), F3 + WFMADB V1, V4, V3, V4 + FMOVD 296(R5), F3 + WFMADB V1, V2, V3, V2 + FMOVD 288(R5), F3 + WFMADB V1, V4, V3, V4 + FMOVD 280(R5), F3 + WFMADB V1, V2, V3, V2 + FMOVD 272(R5), F3 + WFMADB V1, V4, V3, V4 +L9: + FMOVD 264(R5), F3 + FMUL F4, F6 + FMOVD 256(R5), F4 + WFMADB V1, V4, V3, V4 + FDIV F6, F2 + LGDR F4, R1 + FSUB F3, F4 + FMOVD 248(R5), F6 + WFMSDB V4, V6, V1, V4 + FMOVD 240(R5), F1 + FMOVD 232(R5), F6 + WFMADB V4, V6, V1, V6 + FMOVD 224(R5), F1 + FMOVD 216(R5), F3 + WFMADB V4, V3, V1, V3 + WFMDB V4, V4, V1 + FMOVD 208(R5), F5 + WFMADB V6, V1, V3, V6 + FMOVD 200(R5), F3 + MOVH R1,R1 + WFMADB V4, V3, V5, V3 + RISBGZ $57, $60, $3, R1, R2 + WFMADB V1, V6, V3, V6 + RISBGN $0, $15, $48, R1, R3 + MOVD $·erftab2066<>+0(SB), R1 + FMOVD 192(R5), F1 + LDGR R3, F3 + WORD $0xED221000 //madb %f2,%f2,0(%r2,%r1) + BYTE $0x20 + BYTE $0x1E + WFMADB V4, V6, V1, V4 + FMUL F3, F2 + FMADD F4, F2, F0 + FMOVD F0, ret+8(FP) + RET +L12: + FMOVD 184(R5), F0 + WFMADB V6, V0, V6, V0 + FMOVD F0, ret+8(FP) + RET +L5: + FMOVD 176(R5), F1 + FMADD F0, F0, F1 + FMOVD 168(R5), F3 + WFMDB V1, V1, V2 + FMOVD 160(R5), F0 + FMOVD 152(R5), F4 + WFMADB V2, V0, V3, V0 + FMOVD 144(R5), F3 + WFMADB V2, V4, V3, V4 + FMOVD 136(R5), F5 + FMOVD 128(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V4, V3, V4 + FMOVD 120(R5), F5 + FMOVD 112(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V4, V3, V4 + FMOVD 104(R5), F5 + FMOVD 96(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V4, V3, V4 + FMOVD 88(R5), F5 + FMOVD 80(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V4, V3, V4 + FMOVD 72(R5), F5 + FMOVD 64(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V4, V3, V4 + FMOVD 56(R5), F5 + FMOVD 48(R5), F3 + WFMADB V2, V0, V5, V0 + WFMADB V2, V4, V3, V2 + FMOVD 40(R5), F4 + WFMADB V1, V0, V2, V0 + FMUL F6, F0 + FMADD F4, F6, F0 + FMOVD F0, ret+8(FP) + RET +L8: + FMOVD 32(R5), F3 + FMOVD 24(R5), F2 + FMOVD F1, F4 + WFMADB V1, V2, V3, V2 + WORD $0xED405010 //adb %f4,.L68-.L13(%r5) + BYTE $0x00 + BYTE $0x1A + FMOVD 8(R5), F3 + WFMADB V1, V2, V3, V2 + FMOVD ·erfrodataL13<>+0(SB), F3 + WFMADB V1, V4, V3, V4 + BR L9 diff --git a/go/src/math/erfc_s390x.s b/go/src/math/erfc_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..e03a7749ff290cafe58fea0d15eca0b0ebeadb81 --- /dev/null +++ b/go/src/math/erfc_s390x.s @@ -0,0 +1,527 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define Neg2p11 0xC000E147AE147AE1 +#define Pos15 0x402E + +// Minimax polynomial coefficients and other constants +DATA ·erfcrodataL38<> + 0(SB)/8, $.234875460637085087E-01 +DATA ·erfcrodataL38<> + 8(SB)/8, $.234469449299256284E-01 +DATA ·erfcrodataL38<> + 16(SB)/8, $-.606918710392844955E-04 +DATA ·erfcrodataL38<> + 24(SB)/8, $-.198827088077636213E-04 +DATA ·erfcrodataL38<> + 32(SB)/8, $.257805645845475331E-06 +DATA ·erfcrodataL38<> + 40(SB)/8, $-.184427218110620284E-09 +DATA ·erfcrodataL38<> + 48(SB)/8, $.122408098288933181E-10 +DATA ·erfcrodataL38<> + 56(SB)/8, $.484691106751495392E-07 +DATA ·erfcrodataL38<> + 64(SB)/8, $-.150147637632890281E-08 +DATA ·erfcrodataL38<> + 72(SB)/8, $23.999999999973521625 +DATA ·erfcrodataL38<> + 80(SB)/8, $27.226017111108365754 +DATA ·erfcrodataL38<> + 88(SB)/8, $-2.0 +DATA ·erfcrodataL38<> + 96(SB)/8, $0.100108802034478228E+00 +DATA ·erfcrodataL38<> + 104(SB)/8, $0.244588413746558125E+00 +DATA ·erfcrodataL38<> + 112(SB)/8, $-.669188879646637174E-01 +DATA ·erfcrodataL38<> + 120(SB)/8, $0.151311447000953551E-01 +DATA ·erfcrodataL38<> + 128(SB)/8, $-.284720833493302061E-02 +DATA ·erfcrodataL38<> + 136(SB)/8, $0.455491239358743212E-03 +DATA ·erfcrodataL38<> + 144(SB)/8, $-.631850539280720949E-04 +DATA ·erfcrodataL38<> + 152(SB)/8, $0.772532660726086679E-05 +DATA ·erfcrodataL38<> + 160(SB)/8, $-.843706007150936940E-06 +DATA ·erfcrodataL38<> + 168(SB)/8, $-.735330214904227472E-08 +DATA ·erfcrodataL38<> + 176(SB)/8, $0.753002008837084967E-09 +DATA ·erfcrodataL38<> + 184(SB)/8, $0.832482036660624637E-07 +DATA ·erfcrodataL38<> + 192(SB)/8, $-0.75 +DATA ·erfcrodataL38<> + 200(SB)/8, $.927765678007128609E-01 +DATA ·erfcrodataL38<> + 208(SB)/8, $.903621209344751506E-01 +DATA ·erfcrodataL38<> + 216(SB)/8, $-.344203375025257265E-02 +DATA ·erfcrodataL38<> + 224(SB)/8, $-.869243428221791329E-03 +DATA ·erfcrodataL38<> + 232(SB)/8, $.174699813107105603E-03 +DATA ·erfcrodataL38<> + 240(SB)/8, $.649481036316130000E-05 +DATA ·erfcrodataL38<> + 248(SB)/8, $-.895265844897118382E-05 +DATA ·erfcrodataL38<> + 256(SB)/8, $.135970046909529513E-05 +DATA ·erfcrodataL38<> + 264(SB)/8, $.277617717014748015E-06 +DATA ·erfcrodataL38<> + 272(SB)/8, $.810628018408232910E-08 +DATA ·erfcrodataL38<> + 280(SB)/8, $.210430084693497985E-07 +DATA ·erfcrodataL38<> + 288(SB)/8, $-.342138077525615091E-08 +DATA ·erfcrodataL38<> + 296(SB)/8, $-.165467946798610800E-06 +DATA ·erfcrodataL38<> + 304(SB)/8, $5.999999999988412824 +DATA ·erfcrodataL38<> + 312(SB)/8, $.468542210149072159E-01 +DATA ·erfcrodataL38<> + 320(SB)/8, $.465343528567604256E-01 +DATA ·erfcrodataL38<> + 328(SB)/8, $-.473338083650201733E-03 +DATA ·erfcrodataL38<> + 336(SB)/8, $-.147220659069079156E-03 +DATA ·erfcrodataL38<> + 344(SB)/8, $.755284723554388339E-05 +DATA ·erfcrodataL38<> + 352(SB)/8, $.116158570631428789E-05 +DATA ·erfcrodataL38<> + 360(SB)/8, $-.155445501551602389E-06 +DATA ·erfcrodataL38<> + 368(SB)/8, $-.616940119847805046E-10 +DATA ·erfcrodataL38<> + 376(SB)/8, $-.728705590727563158E-10 +DATA ·erfcrodataL38<> + 384(SB)/8, $-.983452460354586779E-08 +DATA ·erfcrodataL38<> + 392(SB)/8, $.365156164194346316E-08 +DATA ·erfcrodataL38<> + 400(SB)/8, $11.999999999996530775 +DATA ·erfcrodataL38<> + 408(SB)/8, $0.467773498104726584E-02 +DATA ·erfcrodataL38<> + 416(SB)/8, $0.206669853540920535E-01 +DATA ·erfcrodataL38<> + 424(SB)/8, $0.413339707081841473E-01 +DATA ·erfcrodataL38<> + 432(SB)/8, $0.482229658262131320E-01 +DATA ·erfcrodataL38<> + 440(SB)/8, $0.344449755901841897E-01 +DATA ·erfcrodataL38<> + 448(SB)/8, $0.130890907240765465E-01 +DATA ·erfcrodataL38<> + 456(SB)/8, $-.459266344100642687E-03 +DATA ·erfcrodataL38<> + 464(SB)/8, $-.337888800856913728E-02 +DATA ·erfcrodataL38<> + 472(SB)/8, $-.159103061687062373E-02 +DATA ·erfcrodataL38<> + 480(SB)/8, $-.501128905515922644E-04 +DATA ·erfcrodataL38<> + 488(SB)/8, $0.262775855852903132E-03 +DATA ·erfcrodataL38<> + 496(SB)/8, $0.103860982197462436E-03 +DATA ·erfcrodataL38<> + 504(SB)/8, $-.548835785414200775E-05 +DATA ·erfcrodataL38<> + 512(SB)/8, $-.157075054646618214E-04 +DATA ·erfcrodataL38<> + 520(SB)/8, $-.480056366276045110E-05 +DATA ·erfcrodataL38<> + 528(SB)/8, $0.198263013759701555E-05 +DATA ·erfcrodataL38<> + 536(SB)/8, $-.224394262958888780E-06 +DATA ·erfcrodataL38<> + 544(SB)/8, $-.321853693146683428E-06 +DATA ·erfcrodataL38<> + 552(SB)/8, $0.445073894984683537E-07 +DATA ·erfcrodataL38<> + 560(SB)/8, $0.660425940000555729E-06 +DATA ·erfcrodataL38<> + 568(SB)/8, $2.0 +DATA ·erfcrodataL38<> + 576(SB)/8, $8.63616855509444462538e-78 +DATA ·erfcrodataL38<> + 584(SB)/8, $1.00000000000000222044 +DATA ·erfcrodataL38<> + 592(SB)/8, $0.500000000000004237e+00 +DATA ·erfcrodataL38<> + 600(SB)/8, $0.416666664838056960e-01 +DATA ·erfcrodataL38<> + 608(SB)/8, $0.166666666630345592e+00 +DATA ·erfcrodataL38<> + 616(SB)/8, $0.138926439368309441e-02 +DATA ·erfcrodataL38<> + 624(SB)/8, $0.833349307718286047e-02 +DATA ·erfcrodataL38<> + 632(SB)/8, $-.693147180558298714e+00 +DATA ·erfcrodataL38<> + 640(SB)/8, $-.164659495826017651e-11 +DATA ·erfcrodataL38<> + 648(SB)/8, $.179001151181866548E+00 +DATA ·erfcrodataL38<> + 656(SB)/8, $-.144269504088896339e+01 +DATA ·erfcrodataL38<> + 664(SB)/8, $+281475245147134.9375 +DATA ·erfcrodataL38<> + 672(SB)/8, $.163116780021877404E+00 +DATA ·erfcrodataL38<> + 680(SB)/8, $-.201574395828120710E-01 +DATA ·erfcrodataL38<> + 688(SB)/8, $-.185726336009394125E-02 +DATA ·erfcrodataL38<> + 696(SB)/8, $.199349204957273749E-02 +DATA ·erfcrodataL38<> + 704(SB)/8, $-.554902415532606242E-03 +DATA ·erfcrodataL38<> + 712(SB)/8, $-.638914789660242846E-05 +DATA ·erfcrodataL38<> + 720(SB)/8, $-.424441522653742898E-04 +DATA ·erfcrodataL38<> + 728(SB)/8, $.827967511921486190E-04 +DATA ·erfcrodataL38<> + 736(SB)/8, $.913965446284062654E-05 +DATA ·erfcrodataL38<> + 744(SB)/8, $.277344791076320853E-05 +DATA ·erfcrodataL38<> + 752(SB)/8, $-.467239678927239526E-06 +DATA ·erfcrodataL38<> + 760(SB)/8, $.344814065920419986E-07 +DATA ·erfcrodataL38<> + 768(SB)/8, $-.366013491552527132E-05 +DATA ·erfcrodataL38<> + 776(SB)/8, $.181242810023783439E-05 +DATA ·erfcrodataL38<> + 784(SB)/8, $2.999999999991234567 +DATA ·erfcrodataL38<> + 792(SB)/8, $1.0 +GLOBL ·erfcrodataL38<> + 0(SB), RODATA, $800 + +// Table of log correction terms +DATA ·erfctab2069<> + 0(SB)/8, $0.442737824274138381e-01 +DATA ·erfctab2069<> + 8(SB)/8, $0.263602189790660309e-01 +DATA ·erfctab2069<> + 16(SB)/8, $0.122565642281703586e-01 +DATA ·erfctab2069<> + 24(SB)/8, $0.143757052860721398e-02 +DATA ·erfctab2069<> + 32(SB)/8, $-.651375034121276075e-02 +DATA ·erfctab2069<> + 40(SB)/8, $-.119317678849450159e-01 +DATA ·erfctab2069<> + 48(SB)/8, $-.150868749549871069e-01 +DATA ·erfctab2069<> + 56(SB)/8, $-.161992609578469234e-01 +DATA ·erfctab2069<> + 64(SB)/8, $-.154492360403337917e-01 +DATA ·erfctab2069<> + 72(SB)/8, $-.129850717389178721e-01 +DATA ·erfctab2069<> + 80(SB)/8, $-.892902649276657891e-02 +DATA ·erfctab2069<> + 88(SB)/8, $-.338202636596794887e-02 +DATA ·erfctab2069<> + 96(SB)/8, $0.357266307045684762e-02 +DATA ·erfctab2069<> + 104(SB)/8, $0.118665304327406698e-01 +DATA ·erfctab2069<> + 112(SB)/8, $0.214434994118118914e-01 +DATA ·erfctab2069<> + 120(SB)/8, $0.322580645161290314e-01 +GLOBL ·erfctab2069<> + 0(SB), RODATA, $128 + +// Erfc returns the complementary error function of the argument. +// +// Special cases are: +// Erfc(+Inf) = 0 +// Erfc(-Inf) = 2 +// Erfc(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. +// This assembly implementation handles inputs in the range [-2.11, +15]. +// For all other inputs we call the generic Go implementation. + +TEXT ·erfcAsm(SB), NOSPLIT|NOFRAME, $0-16 + MOVD x+0(FP), R1 + MOVD $Neg2p11, R2 + CMPUBGT R1, R2, usego + + FMOVD x+0(FP), F0 + MOVD $·erfcrodataL38<>+0(SB), R9 + FMOVD F0, F2 + SRAD $48, R1 + MOVH R1, R2 + ANDW $0x7FFF, R1 + MOVH $Pos15, R3 + CMPW R1, R3 + BGT usego + MOVH $0x3FFF, R3 + MOVW R1, R6 + MOVW R3, R7 + CMPBGT R6, R7, L2 + MOVH $0x3FEF, R3 + MOVW R3, R7 + CMPBGT R6, R7, L3 + MOVH $0x2FFF, R2 + MOVW R2, R7 + CMPBGT R6, R7, L4 + FMOVD 792(R9), F0 + WFSDB V2, V0, V2 + FMOVD F2, ret+8(FP) + RET + +L2: + LTDBR F0, F0 + MOVH $0x0, R4 + BLTU L3 + FMOVD F0, F1 +L9: + MOVH $0x400F, R3 + MOVW R1, R6 + MOVW R3, R7 + CMPBGT R6, R7, L10 + FMOVD 784(R9), F3 + FSUB F1, F3 + VLEG $0, 776(R9), V20 + WFDDB V1, V3, V6 + VLEG $0, 768(R9), V18 + FMOVD 760(R9), F7 + FMOVD 752(R9), F5 + VLEG $0, 744(R9), V16 + FMOVD 736(R9), F3 + FMOVD 728(R9), F2 + FMOVD 720(R9), F4 + WFMDB V6, V6, V1 + FMUL F0, F0 + MOVH $0x0, R3 + WFMADB V1, V7, V20, V7 + WFMADB V1, V5, V18, V5 + WFMADB V1, V7, V16, V7 + WFMADB V1, V5, V3, V5 + WFMADB V1, V7, V4, V7 + WFMADB V1, V5, V2, V5 + FMOVD 712(R9), F2 + WFMADB V1, V7, V2, V7 + FMOVD 704(R9), F2 + WFMADB V1, V5, V2, V5 + FMOVD 696(R9), F2 + WFMADB V1, V7, V2, V7 + FMOVD 688(R9), F2 + MOVH $0x0, R1 + WFMADB V1, V5, V2, V5 + FMOVD 680(R9), F2 + WFMADB V1, V7, V2, V7 + FMOVD 672(R9), F2 + WFMADB V1, V5, V2, V1 + FMOVD 664(R9), F3 + WFMADB V6, V7, V1, V7 + FMOVD 656(R9), F5 + FMOVD 648(R9), F2 + WFMADB V0, V5, V3, V5 + WFMADB V6, V7, V2, V7 +L11: + LGDR F5, R6 + WFSDB V0, V0, V2 + WORD $0xED509298 //sdb %f5,.L55-.L38(%r9) + BYTE $0x00 + BYTE $0x1B + FMOVD 640(R9), F6 + FMOVD 632(R9), F4 + WFMSDB V5, V6, V2, V6 + WFMSDB V5, V4, V0, V4 + FMOVD 624(R9), F2 + FADD F6, F4 + FMOVD 616(R9), F0 + FMOVD 608(R9), F6 + WFMADB V4, V0, V2, V0 + FMOVD 600(R9), F3 + WFMDB V4, V4, V2 + MOVH R6,R6 + ADD R6, R3 + WFMADB V4, V3, V6, V3 + FMOVD 592(R9), F6 + WFMADB V0, V2, V3, V0 + FMOVD 584(R9), F3 + WFMADB V4, V6, V3, V6 + RISBGZ $57, $60, $3, R3, R12 + WFMADB V2, V0, V6, V0 + MOVD $·erfctab2069<>+0(SB), R5 + WORD $0x682C5000 //ld %f2,0(%r12,%r5) + FMADD F2, F4, F4 + RISBGN $0, $15, $48, R3, R4 + WFMADB V4, V0, V2, V4 + LDGR R4, F2 + FMADD F4, F2, F2 + MOVW R2, R6 + CMPBLE R6, $0, L20 + MOVW R1, R6 + CMPBEQ R6, $0, L21 + WORD $0xED709240 //mdb %f7,.L66-.L38(%r9) + BYTE $0x00 + BYTE $0x1C +L21: + FMUL F7, F2 +L1: + FMOVD F2, ret+8(FP) + RET +L3: + LTDBR F0, F0 + BLTU L30 + FMOVD 568(R9), F2 + WFSDB V0, V2, V0 +L8: + WFMDB V0, V0, V4 + FMOVD 560(R9), F2 + FMOVD 552(R9), F6 + FMOVD 544(R9), F1 + WFMADB V4, V6, V2, V6 + FMOVD 536(R9), F2 + WFMADB V4, V1, V2, V1 + FMOVD 528(R9), F3 + FMOVD 520(R9), F2 + WFMADB V4, V6, V3, V6 + WFMADB V4, V1, V2, V1 + FMOVD 512(R9), F3 + FMOVD 504(R9), F2 + WFMADB V4, V6, V3, V6 + WFMADB V4, V1, V2, V1 + FMOVD 496(R9), F3 + FMOVD 488(R9), F2 + WFMADB V4, V6, V3, V6 + WFMADB V4, V1, V2, V1 + FMOVD 480(R9), F3 + FMOVD 472(R9), F2 + WFMADB V4, V6, V3, V6 + WFMADB V4, V1, V2, V1 + FMOVD 464(R9), F3 + FMOVD 456(R9), F2 + WFMADB V4, V6, V3, V6 + WFMADB V4, V1, V2, V1 + FMOVD 448(R9), F3 + FMOVD 440(R9), F2 + WFMADB V4, V6, V3, V6 + WFMADB V4, V1, V2, V1 + FMOVD 432(R9), F3 + FMOVD 424(R9), F2 + WFMADB V4, V6, V3, V6 + WFMADB V4, V1, V2, V1 + FMOVD 416(R9), F3 + FMOVD 408(R9), F2 + WFMADB V4, V6, V3, V6 + FMADD F1, F4, F2 + FMADD F6, F0, F2 + MOVW R2, R6 + CMPBGE R6, $0, L1 + FMOVD 568(R9), F0 + WFSDB V2, V0, V2 + BR L1 +L10: + MOVH $0x401F, R3 + MOVW R1, R6 + MOVW R3, R7 + CMPBLE R6, R7, L36 + MOVH $0x402F, R3 + MOVW R3, R7 + CMPBGT R6, R7, L13 + FMOVD 400(R9), F3 + FSUB F1, F3 + VLEG $0, 392(R9), V20 + WFDDB V1, V3, V6 + VLEG $0, 384(R9), V18 + FMOVD 376(R9), F2 + FMOVD 368(R9), F4 + VLEG $0, 360(R9), V16 + FMOVD 352(R9), F7 + FMOVD 344(R9), F3 + FMUL F0, F0 + WFMDB V6, V6, V1 + FMOVD 656(R9), F5 + MOVH $0x0, R3 + WFMADB V1, V2, V20, V2 + WFMADB V1, V4, V18, V4 + WFMADB V1, V2, V16, V2 + WFMADB V1, V4, V7, V4 + WFMADB V1, V2, V3, V2 + FMOVD 336(R9), F3 + WFMADB V1, V4, V3, V4 + FMOVD 328(R9), F3 + WFMADB V1, V2, V3, V2 + FMOVD 320(R9), F3 + WFMADB V1, V4, V3, V1 + FMOVD 312(R9), F7 + WFMADB V6, V2, V1, V2 + MOVH $0x0, R1 + FMOVD 664(R9), F3 + FMADD F2, F6, F7 + WFMADB V0, V5, V3, V5 + BR L11 +L35: + LCDBR F0, F1 + BR L9 +L36: + FMOVD 304(R9), F3 + FSUB F1, F3 + VLEG $0, 296(R9), V20 + WFDDB V1, V3, V6 + FMOVD 288(R9), F5 + FMOVD 280(R9), F1 + FMOVD 272(R9), F2 + VLEG $0, 264(R9), V18 + VLEG $0, 256(R9), V16 + FMOVD 248(R9), F3 + FMOVD 240(R9), F4 + WFMDB V6, V6, V7 + FMUL F0, F0 + MOVH $0x0, R3 + FMADD F5, F7, F1 + WFMADB V7, V2, V20, V2 + WFMADB V7, V1, V18, V1 + WFMADB V7, V2, V16, V2 + WFMADB V7, V1, V3, V1 + WFMADB V7, V2, V4, V2 + FMOVD 232(R9), F4 + WFMADB V7, V1, V4, V1 + FMOVD 224(R9), F4 + WFMADB V7, V2, V4, V2 + FMOVD 216(R9), F4 + WFMADB V7, V1, V4, V1 + FMOVD 208(R9), F4 + MOVH $0x0, R1 + WFMADB V7, V2, V4, V7 + FMOVD 656(R9), F5 + WFMADB V6, V1, V7, V1 + FMOVD 664(R9), F3 + FMOVD 200(R9), F7 + WFMADB V0, V5, V3, V5 + FMADD F1, F6, F7 + BR L11 +L4: + FMOVD 192(R9), F1 + FMADD F0, F0, F1 + FMOVD 184(R9), F3 + WFMDB V1, V1, V0 + FMOVD 176(R9), F4 + FMOVD 168(R9), F6 + WFMADB V0, V4, V3, V4 + FMOVD 160(R9), F3 + WFMADB V0, V6, V3, V6 + FMOVD 152(R9), F5 + FMOVD 144(R9), F3 + WFMADB V0, V4, V5, V4 + WFMADB V0, V6, V3, V6 + FMOVD 136(R9), F5 + FMOVD 128(R9), F3 + WFMADB V0, V4, V5, V4 + WFMADB V0, V6, V3, V6 + FMOVD 120(R9), F5 + FMOVD 112(R9), F3 + WFMADB V0, V4, V5, V4 + WFMADB V0, V6, V3, V6 + FMOVD 104(R9), F5 + FMOVD 96(R9), F3 + WFMADB V0, V4, V5, V4 + WFMADB V0, V6, V3, V0 + FMOVD F2, F6 + FMADD F4, F1, F0 + WORD $0xED609318 //sdb %f6,.L39-.L38(%r9) + BYTE $0x00 + BYTE $0x1B + WFMSDB V2, V0, V6, V2 + FMOVD F2, ret+8(FP) + RET +L30: + WORD $0xED009238 //adb %f0,.L67-.L38(%r9) + BYTE $0x00 + BYTE $0x1A + BR L8 +L20: + FMOVD 88(R9), F0 + WFMADB V7, V2, V0, V2 + LCDBR F2, F2 + FMOVD F2, ret+8(FP) + RET +L13: + MOVH $0x403A, R3 + MOVW R1, R6 + MOVW R3, R7 + CMPBLE R6, R7, L4 + WORD $0xED109050 //cdb %f1,.L128-.L38(%r9) + BYTE $0x00 + BYTE $0x19 + BGE L37 + BVS L37 + FMOVD 72(R9), F6 + FSUB F1, F6 + MOVH $0x1000, R3 + FDIV F1, F6 + MOVH $0x1000, R1 +L17: + WFMDB V6, V6, V1 + FMOVD 64(R9), F2 + FMOVD 56(R9), F4 + FMOVD 48(R9), F3 + WFMADB V1, V3, V2, V3 + FMOVD 40(R9), F2 + WFMADB V1, V2, V4, V2 + FMOVD 32(R9), F4 + WFMADB V1, V3, V4, V3 + FMOVD 24(R9), F4 + WFMADB V1, V2, V4, V2 + FMOVD 16(R9), F4 + WFMADB V1, V3, V4, V3 + FMOVD 8(R9), F4 + WFMADB V1, V2, V4, V1 + FMUL F0, F0 + WFMADB V3, V6, V1, V3 + FMOVD 656(R9), F5 + FMOVD 664(R9), F4 + FMOVD 0(R9), F7 + WFMADB V0, V5, V4, V5 + FMADD F6, F3, F7 + BR L11 +L14: + FMOVD 72(R9), F6 + FSUB F1, F6 + MOVH $0x403A, R3 + FDIV F1, F6 + MOVW R1, R6 + MOVW R3, R7 + CMPBEQ R6, R7, L23 + MOVH $0x0, R3 + MOVH $0x0, R1 + BR L17 +L37: + WFCEDBS V0, V0, V0 + BVS L1 + MOVW R2, R6 + CMPBLE R6, $0, L18 + MOVH $0x7FEF, R2 + MOVW R1, R6 + MOVW R2, R7 + CMPBGT R6, R7, L24 + + WORD $0xA5400010 //iihh %r4,16 + LDGR R4, F2 + FMUL F2, F2 + BR L1 +L23: + MOVH $0x1000, R3 + MOVH $0x1000, R1 + BR L17 +L24: + FMOVD $0, F2 + BR L1 +L18: + MOVH $0x7FEF, R2 + MOVW R1, R6 + MOVW R2, R7 + CMPBGT R6, R7, L25 + WORD $0xA5408010 //iihh %r4,32784 + FMOVD 568(R9), F2 + LDGR R4, F0 + FMADD F2, F0, F2 + BR L1 +L25: + FMOVD 568(R9), F2 + BR L1 +usego: + BR ·erfc(SB) diff --git a/go/src/math/erfinv.go b/go/src/math/erfinv.go new file mode 100644 index 0000000000000000000000000000000000000000..8e630f9736810e13cd32f8701fa38efb5cac3269 --- /dev/null +++ b/go/src/math/erfinv.go @@ -0,0 +1,129 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Inverse of the floating-point error function. +*/ + +// This implementation is based on the rational approximation +// of percentage points of normal distribution available from +// https://www.jstor.org/stable/2347330. + +const ( + // Coefficients for approximation to erf in |x| <= 0.85 + a0 = 1.1975323115670912564578e0 + a1 = 4.7072688112383978012285e1 + a2 = 6.9706266534389598238465e2 + a3 = 4.8548868893843886794648e3 + a4 = 1.6235862515167575384252e4 + a5 = 2.3782041382114385731252e4 + a6 = 1.1819493347062294404278e4 + a7 = 8.8709406962545514830200e2 + b0 = 1.0000000000000000000e0 + b1 = 4.2313330701600911252e1 + b2 = 6.8718700749205790830e2 + b3 = 5.3941960214247511077e3 + b4 = 2.1213794301586595867e4 + b5 = 3.9307895800092710610e4 + b6 = 2.8729085735721942674e4 + b7 = 5.2264952788528545610e3 + // Coefficients for approximation to erf in 0.85 < |x| <= 1-2*exp(-25) + c0 = 1.42343711074968357734e0 + c1 = 4.63033784615654529590e0 + c2 = 5.76949722146069140550e0 + c3 = 3.64784832476320460504e0 + c4 = 1.27045825245236838258e0 + c5 = 2.41780725177450611770e-1 + c6 = 2.27238449892691845833e-2 + c7 = 7.74545014278341407640e-4 + d0 = 1.4142135623730950488016887e0 + d1 = 2.9036514445419946173133295e0 + d2 = 2.3707661626024532365971225e0 + d3 = 9.7547832001787427186894837e-1 + d4 = 2.0945065210512749128288442e-1 + d5 = 2.1494160384252876777097297e-2 + d6 = 7.7441459065157709165577218e-4 + d7 = 1.4859850019840355905497876e-9 + // Coefficients for approximation to erf in 1-2*exp(-25) < |x| < 1 + e0 = 6.65790464350110377720e0 + e1 = 5.46378491116411436990e0 + e2 = 1.78482653991729133580e0 + e3 = 2.96560571828504891230e-1 + e4 = 2.65321895265761230930e-2 + e5 = 1.24266094738807843860e-3 + e6 = 2.71155556874348757815e-5 + e7 = 2.01033439929228813265e-7 + f0 = 1.414213562373095048801689e0 + f1 = 8.482908416595164588112026e-1 + f2 = 1.936480946950659106176712e-1 + f3 = 2.103693768272068968719679e-2 + f4 = 1.112800997078859844711555e-3 + f5 = 2.611088405080593625138020e-5 + f6 = 2.010321207683943062279931e-7 + f7 = 2.891024605872965461538222e-15 +) + +// Erfinv returns the inverse error function of x. +// +// Special cases are: +// +// Erfinv(1) = +Inf +// Erfinv(-1) = -Inf +// Erfinv(x) = NaN if x < -1 or x > 1 +// Erfinv(NaN) = NaN +func Erfinv(x float64) float64 { + // special cases + if IsNaN(x) || x <= -1 || x >= 1 { + if x == -1 || x == 1 { + return Inf(int(x)) + } + return NaN() + } + + sign := false + if x < 0 { + x = -x + sign = true + } + + var ans float64 + if x <= 0.85 { // |x| <= 0.85 + r := 0.180625 - 0.25*x*x + z1 := ((((((a7*r+a6)*r+a5)*r+a4)*r+a3)*r+a2)*r+a1)*r + a0 + z2 := ((((((b7*r+b6)*r+b5)*r+b4)*r+b3)*r+b2)*r+b1)*r + b0 + ans = (x * z1) / z2 + } else { + var z1, z2 float64 + r := Sqrt(Ln2 - Log(1.0-x)) + if r <= 5.0 { + r -= 1.6 + z1 = ((((((c7*r+c6)*r+c5)*r+c4)*r+c3)*r+c2)*r+c1)*r + c0 + z2 = ((((((d7*r+d6)*r+d5)*r+d4)*r+d3)*r+d2)*r+d1)*r + d0 + } else { + r -= 5.0 + z1 = ((((((e7*r+e6)*r+e5)*r+e4)*r+e3)*r+e2)*r+e1)*r + e0 + z2 = ((((((f7*r+f6)*r+f5)*r+f4)*r+f3)*r+f2)*r+f1)*r + f0 + } + ans = z1 / z2 + } + + if sign { + return -ans + } + return ans +} + +// Erfcinv returns the inverse of [Erfc](x). +// +// Special cases are: +// +// Erfcinv(0) = +Inf +// Erfcinv(2) = -Inf +// Erfcinv(x) = NaN if x < 0 or x > 2 +// Erfcinv(NaN) = NaN +func Erfcinv(x float64) float64 { + return Erfinv(1 - x) +} diff --git a/go/src/math/example_test.go b/go/src/math/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a26d8cbe97d8b463cbcb1ea6e57197545a253dbc --- /dev/null +++ b/go/src/math/example_test.go @@ -0,0 +1,245 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math_test + +import ( + "fmt" + "math" +) + +func ExampleAcos() { + fmt.Printf("%.2f", math.Acos(1)) + // Output: 0.00 +} + +func ExampleAcosh() { + fmt.Printf("%.2f", math.Acosh(1)) + // Output: 0.00 +} + +func ExampleAsin() { + fmt.Printf("%.2f", math.Asin(0)) + // Output: 0.00 +} + +func ExampleAsinh() { + fmt.Printf("%.2f", math.Asinh(0)) + // Output: 0.00 +} + +func ExampleAtan() { + fmt.Printf("%.2f", math.Atan(0)) + // Output: 0.00 +} + +func ExampleAtan2() { + fmt.Printf("%.2f", math.Atan2(0, 0)) + // Output: 0.00 +} + +func ExampleAtanh() { + fmt.Printf("%.2f", math.Atanh(0)) + // Output: 0.00 +} + +func ExampleCopysign() { + fmt.Printf("%.2f", math.Copysign(3.2, -1)) + // Output: -3.20 +} + +func ExampleCos() { + fmt.Printf("%.2f", math.Cos(math.Pi/2)) + // Output: 0.00 +} + +func ExampleCosh() { + fmt.Printf("%.2f", math.Cosh(0)) + // Output: 1.00 +} + +func ExampleSin() { + fmt.Printf("%.2f", math.Sin(math.Pi)) + // Output: 0.00 +} + +func ExampleSincos() { + sin, cos := math.Sincos(0) + fmt.Printf("%.2f, %.2f", sin, cos) + // Output: 0.00, 1.00 +} + +func ExampleSinh() { + fmt.Printf("%.2f", math.Sinh(0)) + // Output: 0.00 +} + +func ExampleTan() { + fmt.Printf("%.2f", math.Tan(0)) + // Output: 0.00 +} + +func ExampleTanh() { + fmt.Printf("%.2f", math.Tanh(0)) + // Output: 0.00 +} + +func ExampleSqrt() { + const ( + a = 3 + b = 4 + ) + c := math.Sqrt(a*a + b*b) + fmt.Printf("%.1f", c) + // Output: 5.0 +} + +func ExampleCeil() { + c := math.Ceil(1.49) + fmt.Printf("%.1f", c) + // Output: 2.0 +} + +func ExampleFloor() { + c := math.Floor(1.51) + fmt.Printf("%.1f", c) + // Output: 1.0 +} + +func ExamplePow() { + c := math.Pow(2, 3) + fmt.Printf("%.1f", c) + // Output: 8.0 +} + +func ExamplePow10() { + c := math.Pow10(2) + fmt.Printf("%.1f", c) + // Output: 100.0 +} + +func ExampleRound() { + p := math.Round(10.5) + fmt.Printf("%.1f\n", p) + + n := math.Round(-10.5) + fmt.Printf("%.1f\n", n) + // Output: + // 11.0 + // -11.0 +} + +func ExampleRoundToEven() { + u := math.RoundToEven(11.5) + fmt.Printf("%.1f\n", u) + + d := math.RoundToEven(12.5) + fmt.Printf("%.1f\n", d) + // Output: + // 12.0 + // 12.0 +} + +func ExampleLog() { + x := math.Log(1) + fmt.Printf("%.1f\n", x) + + y := math.Log(2.7183) + fmt.Printf("%.1f\n", y) + // Output: + // 0.0 + // 1.0 +} + +func ExampleLog2() { + fmt.Printf("%.1f", math.Log2(256)) + // Output: 8.0 +} + +func ExampleLog10() { + fmt.Printf("%.1f", math.Log10(100)) + // Output: 2.0 +} + +func ExampleRemainder() { + fmt.Printf("%.1f", math.Remainder(100, 30)) + // Output: 10.0 +} + +func ExampleMod() { + c := math.Mod(7, 4) + fmt.Printf("%.1f", c) + // Output: 3.0 +} + +func ExampleAbs() { + x := math.Abs(-2) + fmt.Printf("%.1f\n", x) + + y := math.Abs(2) + fmt.Printf("%.1f\n", y) + // Output: + // 2.0 + // 2.0 +} +func ExampleDim() { + fmt.Printf("%.2f\n", math.Dim(4, -2)) + fmt.Printf("%.2f\n", math.Dim(-4, 2)) + // Output: + // 6.00 + // 0.00 +} + +func ExampleExp() { + fmt.Printf("%.2f\n", math.Exp(1)) + fmt.Printf("%.2f\n", math.Exp(2)) + fmt.Printf("%.2f\n", math.Exp(-1)) + // Output: + // 2.72 + // 7.39 + // 0.37 +} + +func ExampleExp2() { + fmt.Printf("%.2f\n", math.Exp2(1)) + fmt.Printf("%.2f\n", math.Exp2(-3)) + // Output: + // 2.00 + // 0.12 +} + +func ExampleExpm1() { + fmt.Printf("%.6f\n", math.Expm1(0.01)) + fmt.Printf("%.6f\n", math.Expm1(-1)) + // Output: + // 0.010050 + // -0.632121 +} + +func ExampleTrunc() { + fmt.Printf("%.2f\n", math.Trunc(math.Pi)) + fmt.Printf("%.2f\n", math.Trunc(-1.2345)) + // Output: + // 3.00 + // -1.00 +} + +func ExampleCbrt() { + fmt.Printf("%.2f\n", math.Cbrt(8)) + fmt.Printf("%.2f\n", math.Cbrt(27)) + // Output: + // 2.00 + // 3.00 +} + +func ExampleModf() { + int, frac := math.Modf(3.14) + fmt.Printf("%.2f, %.2f\n", int, frac) + + int, frac = math.Modf(-2.71) + fmt.Printf("%.2f, %.2f\n", int, frac) + // Output: + // 3.00, 0.14 + // -2.00, -0.71 +} diff --git a/go/src/math/exp.go b/go/src/math/exp.go new file mode 100644 index 0000000000000000000000000000000000000000..029a4f8163698fe694c8c9375ae189d80cb31671 --- /dev/null +++ b/go/src/math/exp.go @@ -0,0 +1,199 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Exp returns e**x, the base-e exponential of x. +// +// Special cases are: +// +// Exp(+Inf) = +Inf +// Exp(NaN) = NaN +// +// Very large values overflow to 0 or +Inf. +// Very small values underflow to 1. +func Exp(x float64) float64 { + if haveArchExp { + return archExp(x) + } + return exp(x) +} + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/e_exp.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. +// +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// exp(x) +// Returns the exponential of x. +// +// Method +// 1. Argument reduction: +// Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658. +// Given x, find r and integer k such that +// +// x = k*ln2 + r, |r| <= 0.5*ln2. +// +// Here r will be represented as r = hi-lo for better +// accuracy. +// +// 2. Approximation of exp(r) by a special rational function on +// the interval [0,0.34658]: +// Write +// R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ... +// We use a special Remez algorithm on [0,0.34658] to generate +// a polynomial of degree 5 to approximate R. The maximum error +// of this polynomial approximation is bounded by 2**-59. In +// other words, +// R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5 +// (where z=r*r, and the values of P1 to P5 are listed below) +// and +// | 5 | -59 +// | 2.0+P1*z+...+P5*z - R(z) | <= 2 +// | | +// The computation of exp(r) thus becomes +// 2*r +// exp(r) = 1 + ------- +// R - r +// r*R1(r) +// = 1 + r + ----------- (for better accuracy) +// 2 - R1(r) +// where +// 2 4 10 +// R1(r) = r - (P1*r + P2*r + ... + P5*r ). +// +// 3. Scale back to obtain exp(x): +// From step 1, we have +// exp(x) = 2**k * exp(r) +// +// Special cases: +// exp(INF) is INF, exp(NaN) is NaN; +// exp(-INF) is 0, and +// for finite argument, only exp(0)=1 is exact. +// +// Accuracy: +// according to an error analysis, the error is always less than +// 1 ulp (unit in the last place). +// +// Misc. info. +// For IEEE double +// if x > 7.09782712893383973096e+02 then exp(x) overflow +// if x < -7.45133219101941108420e+02 then exp(x) underflow +// +// Constants: +// The hexadecimal values are the intended ones for the following +// constants. The decimal values may be used, provided that the +// compiler will convert from decimal to binary accurately enough +// to produce the hexadecimal values shown. + +func exp(x float64) float64 { + const ( + Ln2Hi = 6.93147180369123816490e-01 + Ln2Lo = 1.90821492927058770002e-10 + Log2e = 1.44269504088896338700e+00 + + Overflow = 7.09782712893383973096e+02 + Underflow = -7.45133219101941108420e+02 + NearZero = 1.0 / (1 << 28) // 2**-28 + ) + + // special cases + switch { + case IsNaN(x): + return x + case x > Overflow: // handles case where x is +∞ + return Inf(1) + case x < Underflow: // handles case where x is -∞ + return 0 + case -NearZero < x && x < NearZero: + return 1 + x + } + + // reduce; computed as r = hi - lo for extra precision. + var k int + switch { + case x < 0: + k = int(Log2e*x - 0.5) + case x > 0: + k = int(Log2e*x + 0.5) + } + hi := x - float64(k)*Ln2Hi + lo := float64(k) * Ln2Lo + + // compute + return expmulti(hi, lo, k) +} + +// Exp2 returns 2**x, the base-2 exponential of x. +// +// Special cases are the same as [Exp]. +func Exp2(x float64) float64 { + if haveArchExp2 { + return archExp2(x) + } + return exp2(x) +} + +func exp2(x float64) float64 { + const ( + Ln2Hi = 6.93147180369123816490e-01 + Ln2Lo = 1.90821492927058770002e-10 + + Overflow = 1.0239999999999999e+03 + Underflow = -1.0740e+03 + ) + + // special cases + switch { + case IsNaN(x): + return x + case x > Overflow: // handles case where x is +∞ + return Inf(1) + case x < Underflow: // handles case where x is -∞ + return 0 + } + + // argument reduction; x = r×lg(e) + k with |r| ≤ ln(2)/2. + // computed as r = hi - lo for extra precision. + var k int + switch { + case x > 0: + k = int(x + 0.5) + case x < 0: + k = int(x - 0.5) + } + t := x - float64(k) + hi := t * Ln2Hi + lo := -t * Ln2Lo + + // compute + return expmulti(hi, lo, k) +} + +// exp1 returns e**r × 2**k where r = hi - lo and |r| ≤ ln(2)/2. +func expmulti(hi, lo float64, k int) float64 { + const ( + P1 = 1.66666666666666657415e-01 /* 0x3FC55555; 0x55555555 */ + P2 = -2.77777777770155933842e-03 /* 0xBF66C16C; 0x16BEBD93 */ + P3 = 6.61375632143793436117e-05 /* 0x3F11566A; 0xAF25DE2C */ + P4 = -1.65339022054652515390e-06 /* 0xBEBBBD41; 0xC5D26BF1 */ + P5 = 4.13813679705723846039e-08 /* 0x3E663769; 0x72BEA4D0 */ + ) + + r := hi - lo + t := r * r + c := r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))) + y := 1 - ((lo - (r*c)/(2-c)) - hi) + // TODO(rsc): make sure Ldexp can handle boundary k + return Ldexp(y, k) +} diff --git a/go/src/math/exp2_asm.go b/go/src/math/exp2_asm.go new file mode 100644 index 0000000000000000000000000000000000000000..1e7875937432e83b0107ba10740a6a6173863730 --- /dev/null +++ b/go/src/math/exp2_asm.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build arm64 || loong64 + +package math + +const haveArchExp2 = true + +func archExp2(x float64) float64 diff --git a/go/src/math/exp2_noasm.go b/go/src/math/exp2_noasm.go new file mode 100644 index 0000000000000000000000000000000000000000..847138b622ce671b10355597720600a7a79d7377 --- /dev/null +++ b/go/src/math/exp2_noasm.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !arm64 && !loong64 + +package math + +const haveArchExp2 = false + +func archExp2(x float64) float64 { + panic("not implemented") +} diff --git a/go/src/math/exp_amd64.go b/go/src/math/exp_amd64.go new file mode 100644 index 0000000000000000000000000000000000000000..0f701b1d6d8da1fa4bf3c8e14c3c45bb348df9d2 --- /dev/null +++ b/go/src/math/exp_amd64.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build amd64 + +package math + +import "internal/cpu" + +var useFMA = cpu.X86.HasAVX && cpu.X86.HasFMA diff --git a/go/src/math/exp_amd64.s b/go/src/math/exp_amd64.s new file mode 100644 index 0000000000000000000000000000000000000000..02b71c81eb636c06dc396102ac7d3024defcf246 --- /dev/null +++ b/go/src/math/exp_amd64.s @@ -0,0 +1,159 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// The method is based on a paper by Naoki Shibata: "Efficient evaluation +// methods of elementary functions suitable for SIMD computation", Proc. +// of International Supercomputing Conference 2010 (ISC'10), pp. 25 -- 32 +// (May 2010). The paper is available at +// https://link.springer.com/article/10.1007/s00450-010-0108-2 +// +// The original code and the constants below are from the author's +// implementation available at http://freshmeat.net/projects/sleef. +// The README file says, "The software is in public domain. +// You can use the software without any obligation." +// +// This code is a simplified version of the original. + +#define LN2 0.6931471805599453094172321214581766 // log_e(2) +#define LOG2E 1.4426950408889634073599246810018920 // 1/LN2 +#define LN2U 0.69314718055966295651160180568695068359375 // upper half LN2 +#define LN2L 0.28235290563031577122588448175013436025525412068e-12 // lower half LN2 +#define PosInf 0x7FF0000000000000 +#define NegInf 0xFFF0000000000000 +#define Overflow 7.09782712893384e+02 + +DATA exprodata<>+0(SB)/8, $0.5 +DATA exprodata<>+8(SB)/8, $1.0 +DATA exprodata<>+16(SB)/8, $2.0 +DATA exprodata<>+24(SB)/8, $1.6666666666666666667e-1 +DATA exprodata<>+32(SB)/8, $4.1666666666666666667e-2 +DATA exprodata<>+40(SB)/8, $8.3333333333333333333e-3 +DATA exprodata<>+48(SB)/8, $1.3888888888888888889e-3 +DATA exprodata<>+56(SB)/8, $1.9841269841269841270e-4 +DATA exprodata<>+64(SB)/8, $2.4801587301587301587e-5 +GLOBL exprodata<>+0(SB), RODATA, $72 + +// func Exp(x float64) float64 +TEXT ·archExp(SB),NOSPLIT,$0 + // test bits for not-finite + MOVQ x+0(FP), BX + MOVQ $~(1<<63), AX // sign bit mask + MOVQ BX, DX + ANDQ AX, DX + MOVQ $PosInf, AX + CMPQ AX, DX + JLE notFinite + // check if argument will overflow + MOVQ BX, X0 + MOVSD $Overflow, X1 + COMISD X1, X0 + JA overflow + MOVSD $LOG2E, X1 + MULSD X0, X1 + CVTSD2SL X1, BX // BX = exponent + CVTSL2SD BX, X1 + CMPB ·useFMA(SB), $1 + JE avxfma + MOVSD $LN2U, X2 + MULSD X1, X2 + SUBSD X2, X0 + MOVSD $LN2L, X2 + MULSD X1, X2 + SUBSD X2, X0 + // reduce argument + MULSD $0.0625, X0 + // Taylor series evaluation + MOVSD exprodata<>+64(SB), X1 + MULSD X0, X1 + ADDSD exprodata<>+56(SB), X1 + MULSD X0, X1 + ADDSD exprodata<>+48(SB), X1 + MULSD X0, X1 + ADDSD exprodata<>+40(SB), X1 + MULSD X0, X1 + ADDSD exprodata<>+32(SB), X1 + MULSD X0, X1 + ADDSD exprodata<>+24(SB), X1 + MULSD X0, X1 + ADDSD exprodata<>+0(SB), X1 + MULSD X0, X1 + ADDSD exprodata<>+8(SB), X1 + MULSD X1, X0 + MOVSD exprodata<>+16(SB), X1 + ADDSD X0, X1 + MULSD X1, X0 + MOVSD exprodata<>+16(SB), X1 + ADDSD X0, X1 + MULSD X1, X0 + MOVSD exprodata<>+16(SB), X1 + ADDSD X0, X1 + MULSD X1, X0 + MOVSD exprodata<>+16(SB), X1 + ADDSD X0, X1 + MULSD X1, X0 + ADDSD exprodata<>+8(SB), X0 + // return fr * 2**exponent +ldexp: + ADDL $0x3FF, BX // add bias + JLE denormal + CMPL BX, $0x7FF + JGE overflow +lastStep: + SHLQ $52, BX + MOVQ BX, X1 + MULSD X1, X0 + MOVSD X0, ret+8(FP) + RET +notFinite: + // test bits for -Inf + MOVQ $NegInf, AX + CMPQ AX, BX + JNE notNegInf + // -Inf, return 0 +underflow: // return 0 + MOVQ $0, ret+8(FP) + RET +overflow: // return +Inf + MOVQ $PosInf, BX +notNegInf: // NaN or +Inf, return x + MOVQ BX, ret+8(FP) + RET +denormal: + CMPL BX, $-52 + JL underflow + ADDL $0x3FE, BX // add bias - 1 + SHLQ $52, BX + MOVQ BX, X1 + MULSD X1, X0 + MOVQ $1, BX + JMP lastStep + +avxfma: + MOVSD $LN2U, X2 + VFNMADD231SD X2, X1, X0 + MOVSD $LN2L, X2 + VFNMADD231SD X2, X1, X0 + // reduce argument + MULSD $0.0625, X0 + // Taylor series evaluation + MOVSD exprodata<>+64(SB), X1 + VFMADD213SD exprodata<>+56(SB), X0, X1 + VFMADD213SD exprodata<>+48(SB), X0, X1 + VFMADD213SD exprodata<>+40(SB), X0, X1 + VFMADD213SD exprodata<>+32(SB), X0, X1 + VFMADD213SD exprodata<>+24(SB), X0, X1 + VFMADD213SD exprodata<>+0(SB), X0, X1 + VFMADD213SD exprodata<>+8(SB), X0, X1 + MULSD X1, X0 + VADDSD exprodata<>+16(SB), X0, X1 + MULSD X1, X0 + VADDSD exprodata<>+16(SB), X0, X1 + MULSD X1, X0 + VADDSD exprodata<>+16(SB), X0, X1 + MULSD X1, X0 + VADDSD exprodata<>+16(SB), X0, X1 + VFMADD213SD exprodata<>+8(SB), X1, X0 + JMP ldexp diff --git a/go/src/math/exp_arm64.s b/go/src/math/exp_arm64.s new file mode 100644 index 0000000000000000000000000000000000000000..44673abefe4cce681346455a6928746b3354b33a --- /dev/null +++ b/go/src/math/exp_arm64.s @@ -0,0 +1,182 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#define Ln2Hi 6.93147180369123816490e-01 +#define Ln2Lo 1.90821492927058770002e-10 +#define Log2e 1.44269504088896338700e+00 +#define Overflow 7.09782712893383973096e+02 +#define Underflow -7.45133219101941108420e+02 +#define Overflow2 1.0239999999999999e+03 +#define Underflow2 -1.0740e+03 +#define NearZero 0x3e30000000000000 // 2**-28 +#define PosInf 0x7ff0000000000000 +#define FracMask 0x000fffffffffffff +#define C1 0x3cb0000000000000 // 2**-52 +#define P1 1.66666666666666657415e-01 // 0x3FC55555; 0x55555555 +#define P2 -2.77777777770155933842e-03 // 0xBF66C16C; 0x16BEBD93 +#define P3 6.61375632143793436117e-05 // 0x3F11566A; 0xAF25DE2C +#define P4 -1.65339022054652515390e-06 // 0xBEBBBD41; 0xC5D26BF1 +#define P5 4.13813679705723846039e-08 // 0x3E663769; 0x72BEA4D0 + +// Exp returns e**x, the base-e exponential of x. +// This is an assembly implementation of the method used for function Exp in file exp.go. +// +// func Exp(x float64) float64 +TEXT ·archExp(SB),$0-16 + FMOVD x+0(FP), F0 // F0 = x + FCMPD F0, F0 + BNE isNaN // x = NaN, return NaN + FMOVD $Overflow, F1 + FCMPD F1, F0 + BGT overflow // x > Overflow, return PosInf + FMOVD $Underflow, F1 + FCMPD F1, F0 + BLT underflow // x < Underflow, return 0 + MOVD $NearZero, R0 + FMOVD R0, F2 + FABSD F0, F3 + FMOVD $1.0, F1 // F1 = 1.0 + FCMPD F2, F3 + BLT nearzero // fabs(x) < NearZero, return 1 + x + // argument reduction, x = k*ln2 + r, |r| <= 0.5*ln2 + // computed as r = hi - lo for extra precision. + FMOVD $Log2e, F2 + FMOVD $0.5, F3 + FNMSUBD F0, F3, F2, F4 // Log2e*x - 0.5 + FMADDD F0, F3, F2, F3 // Log2e*x + 0.5 + FCMPD $0.0, F0 + FCSELD LT, F4, F3, F3 // F3 = k + FCVTZSD F3, R1 // R1 = int(k) + SCVTFD R1, F3 // F3 = float64(int(k)) + FMOVD $Ln2Hi, F4 // F4 = Ln2Hi + FMOVD $Ln2Lo, F5 // F5 = Ln2Lo + FMSUBD F3, F0, F4, F4 // F4 = hi = x - float64(int(k))*Ln2Hi + FMULD F3, F5 // F5 = lo = float64(int(k)) * Ln2Lo + FSUBD F5, F4, F6 // F6 = r = hi - lo + FMULD F6, F6, F7 // F7 = t = r * r + // compute y + FMOVD $P5, F8 // F8 = P5 + FMOVD $P4, F9 // F9 = P4 + FMADDD F7, F9, F8, F13 // P4+t*P5 + FMOVD $P3, F10 // F10 = P3 + FMADDD F7, F10, F13, F13 // P3+t*(P4+t*P5) + FMOVD $P2, F11 // F11 = P2 + FMADDD F7, F11, F13, F13 // P2+t*(P3+t*(P4+t*P5)) + FMOVD $P1, F12 // F12 = P1 + FMADDD F7, F12, F13, F13 // P1+t*(P2+t*(P3+t*(P4+t*P5))) + FMSUBD F7, F6, F13, F13 // F13 = c = r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))) + FMOVD $2.0, F14 + FSUBD F13, F14 + FMULD F6, F13, F15 + FDIVD F14, F15 // F15 = (r*c)/(2-c) + FSUBD F15, F5, F15 // lo-(r*c)/(2-c) + FSUBD F4, F15, F15 // (lo-(r*c)/(2-c))-hi + FSUBD F15, F1, F16 // F16 = y = 1-((lo-(r*c)/(2-c))-hi) + // inline Ldexp(y, k), benefit: + // 1, no parameter pass overhead. + // 2, skip unnecessary checks for Inf/NaN/Zero + FMOVD F16, R0 + AND $FracMask, R0, R2 // fraction + LSR $52, R0, R5 // exponent + ADD R1, R5 // R1 = int(k) + CMP $1, R5 + BGE normal + ADD $52, R5 // denormal + MOVD $C1, R8 + FMOVD R8, F1 // m = 2**-52 +normal: + ORR R5<<52, R2, R0 + FMOVD R0, F0 + FMULD F1, F0 // return m * x + FMOVD F0, ret+8(FP) + RET +nearzero: + FADDD F1, F0 +isNaN: + FMOVD F0, ret+8(FP) + RET +underflow: + MOVD ZR, ret+8(FP) + RET +overflow: + MOVD $PosInf, R0 + MOVD R0, ret+8(FP) + RET + + +// Exp2 returns 2**x, the base-2 exponential of x. +// This is an assembly implementation of the method used for function Exp2 in file exp.go. +// +// func Exp2(x float64) float64 +TEXT ·archExp2(SB),$0-16 + FMOVD x+0(FP), F0 // F0 = x + FCMPD F0, F0 + BNE isNaN // x = NaN, return NaN + FMOVD $Overflow2, F1 + FCMPD F1, F0 + BGT overflow // x > Overflow, return PosInf + FMOVD $Underflow2, F1 + FCMPD F1, F0 + BLT underflow // x < Underflow, return 0 + // argument reduction; x = r*lg(e) + k with |r| <= ln(2)/2 + // computed as r = hi - lo for extra precision. + FMOVD $0.5, F2 + FSUBD F2, F0, F3 // x + 0.5 + FADDD F2, F0, F4 // x - 0.5 + FCMPD $0.0, F0 + FCSELD LT, F3, F4, F3 // F3 = k + FCVTZSD F3, R1 // R1 = int(k) + SCVTFD R1, F3 // F3 = float64(int(k)) + FSUBD F3, F0, F3 // t = x - float64(int(k)) + FMOVD $Ln2Hi, F4 // F4 = Ln2Hi + FMOVD $Ln2Lo, F5 // F5 = Ln2Lo + FMULD F3, F4 // F4 = hi = t * Ln2Hi + FNMULD F3, F5 // F5 = lo = -t * Ln2Lo + FSUBD F5, F4, F6 // F6 = r = hi - lo + FMULD F6, F6, F7 // F7 = t = r * r + // compute y + FMOVD $P5, F8 // F8 = P5 + FMOVD $P4, F9 // F9 = P4 + FMADDD F7, F9, F8, F13 // P4+t*P5 + FMOVD $P3, F10 // F10 = P3 + FMADDD F7, F10, F13, F13 // P3+t*(P4+t*P5) + FMOVD $P2, F11 // F11 = P2 + FMADDD F7, F11, F13, F13 // P2+t*(P3+t*(P4+t*P5)) + FMOVD $P1, F12 // F12 = P1 + FMADDD F7, F12, F13, F13 // P1+t*(P2+t*(P3+t*(P4+t*P5))) + FMSUBD F7, F6, F13, F13 // F13 = c = r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))) + FMOVD $2.0, F14 + FSUBD F13, F14 + FMULD F6, F13, F15 + FDIVD F14, F15 // F15 = (r*c)/(2-c) + FMOVD $1.0, F1 // F1 = 1.0 + FSUBD F15, F5, F15 // lo-(r*c)/(2-c) + FSUBD F4, F15, F15 // (lo-(r*c)/(2-c))-hi + FSUBD F15, F1, F16 // F16 = y = 1-((lo-(r*c)/(2-c))-hi) + // inline Ldexp(y, k), benefit: + // 1, no parameter pass overhead. + // 2, skip unnecessary checks for Inf/NaN/Zero + FMOVD F16, R0 + AND $FracMask, R0, R2 // fraction + LSR $52, R0, R5 // exponent + ADD R1, R5 // R1 = int(k) + CMP $1, R5 + BGE normal + ADD $52, R5 // denormal + MOVD $C1, R8 + FMOVD R8, F1 // m = 2**-52 +normal: + ORR R5<<52, R2, R0 + FMOVD R0, F0 + FMULD F1, F0 // return m * x +isNaN: + FMOVD F0, ret+8(FP) + RET +underflow: + MOVD ZR, ret+8(FP) + RET +overflow: + MOVD $PosInf, R0 + MOVD R0, ret+8(FP) + RET diff --git a/go/src/math/exp_asm.go b/go/src/math/exp_asm.go new file mode 100644 index 0000000000000000000000000000000000000000..125529fca360a206d082fb950bb4dd18da845ed8 --- /dev/null +++ b/go/src/math/exp_asm.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build amd64 || arm64 || loong64 || s390x + +package math + +const haveArchExp = true + +func archExp(x float64) float64 diff --git a/go/src/math/exp_loong64.s b/go/src/math/exp_loong64.s new file mode 100644 index 0000000000000000000000000000000000000000..bf2823f888510b61562d1b1490dc7bf3dd227e84 --- /dev/null +++ b/go/src/math/exp_loong64.s @@ -0,0 +1,236 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define NearZero 0x3e30000000000000 // 2**-28 +#define PosInf 0x7ff0000000000000 +#define FracMask 0x000fffffffffffff +#define C1 0x3cb0000000000000 // 2**-52 + +DATA exprodata<>+0(SB)/8, $0.0 +DATA exprodata<>+8(SB)/8, $0.5 +DATA exprodata<>+16(SB)/8, $1.0 +DATA exprodata<>+24(SB)/8, $2.0 +DATA exprodata<>+32(SB)/8, $6.93147180369123816490e-01 // Ln2Hi +DATA exprodata<>+40(SB)/8, $1.90821492927058770002e-10 // Ln2Lo +DATA exprodata<>+48(SB)/8, $1.44269504088896338700e+00 // Log2e +DATA exprodata<>+56(SB)/8, $7.09782712893383973096e+02 // Overflow +DATA exprodata<>+64(SB)/8, $-7.45133219101941108420e+02 // Underflow +DATA exprodata<>+72(SB)/8, $1.0239999999999999e+03 // Overflow2 +DATA exprodata<>+80(SB)/8, $-1.0740e+03 // Underflow2 +DATA exprodata<>+88(SB)/8, $3.7252902984619141e-09 // NearZero +GLOBL exprodata<>+0(SB), NOPTR|RODATA, $96 + +DATA expmultirodata<>+0(SB)/8, $1.66666666666666657415e-01 // P1 +DATA expmultirodata<>+8(SB)/8, $-2.77777777770155933842e-03 // P2 +DATA expmultirodata<>+16(SB)/8, $6.61375632143793436117e-05 // P3 +DATA expmultirodata<>+24(SB)/8, $-1.65339022054652515390e-06 // P4 +DATA expmultirodata<>+32(SB)/8, $4.13813679705723846039e-08 // P5 +GLOBL expmultirodata<>+0(SB), NOPTR|RODATA, $40 + +// Exp returns e**x, the base-e exponential of x. +// This is an assembly implementation of the method used for function Exp in file exp.go. +// +// func Exp(x float64) float64 +TEXT ·archExp(SB),$0-16 + MOVD x+0(FP), F0 // F0 = x + + MOVV $exprodata<>+0(SB), R10 + MOVD 56(R10), F1 // Overflow + MOVD 64(R10), F2 // Underflow + MOVD 88(R10), F3 // NearZero + MOVD 16(R10), F17 // 1.0 + + CMPEQD F0, F0, FCC0 + BFPF isNaN // x = NaN, return NaN + + CMPGTD F0, F1, FCC0 + BFPT overflow // x > Overflow, return PosInf + + CMPGTD F2, F0, FCC0 + BFPT underflow // x < Underflow, return 0 + + ABSD F0, F5 + CMPGTD F3, F5, FCC0 + BFPT nearzero // fabs(x) < NearZero, return 1 + x + + // argument reduction, x = k*ln2 + r, |r| <= 0.5*ln2 + // computed as r = hi - lo for extra precision. + MOVD 0(R10), F5 + MOVD 8(R10), F3 + MOVD 48(R10), F2 + CMPGTD F0, F5, FCC0 + BFPT add // x > 0 +sub: + FMSUBD F3, F2, F0, F3 // Log2e*x - 0.5 + JMP 2(PC) +add: + FMADDD F3, F2, F0, F3 // Log2e*x + 0.5 + + FTINTRZVD F3, F4 // float64 -> int64 + MOVV F4, R5 // R5 = int(k) + FFINTDV F4, F3 // int64 -> float64 + + MOVD 32(R10), F4 + MOVD 40(R10), F5 + FNMSUBD F0, F3, F4, F4 + MULD F3, F5, F5 + SUBD F5, F4, F6 + MULD F6, F6, F7 + + // compute c + MOVV $expmultirodata<>+0(SB), R11 + MOVD 32(R11), F8 + MOVD 24(R11), F9 + FMADDD F9, F8, F7, F13 + MOVD 16(R11), F10 + FMADDD F10, F13, F7, F13 + MOVD 8(R11), F11 + FMADDD F11, F13, F7, F13 + MOVD 0(R11), F12 + FMADDD F12, F13, F7, F13 + FNMSUBD F6, F13, F7, F13 + + // compute y + MOVD 24(R10), F14 + SUBD F13, F14, F14 + MULD F6, F13, F15 + DIVD F14, F15, F15 + SUBD F15, F5, F15 + SUBD F4, F15, F15 + SUBD F15, F17, F16 + + // inline Ldexp(y, k), benefit: + // 1, no parameter pass overhead. + // 2, skip unnecessary checks for Inf/NaN/Zero + MOVV F16, R4 + MOVV $FracMask, R9 + AND R9, R4, R6 // fraction + SRLV $52, R4, R7 // exponent + ADDV R5, R7 + MOVV $1, R12 + BGE R7, R12, normal + ADDV $52, R7 // denormal + MOVV $C1, R8 + MOVV R8, F17 +normal: + SLLV $52, R7 + OR R7, R6, R4 + MOVV R4, F0 + MULD F17, F0 // return m * x + MOVD F0, ret+8(FP) + RET +nearzero: + ADDD F17, F0, F0 +isNaN: + MOVD F0, ret+8(FP) + RET +underflow: + MOVV R0, ret+8(FP) + RET +overflow: + MOVV $PosInf, R4 + MOVV R4, ret+8(FP) + RET + + +// Exp2 returns 2**x, the base-2 exponential of x. +// This is an assembly implementation of the method used for function Exp2 in file exp.go. +// +// func Exp2(x float64) float64 +TEXT ·archExp2(SB),$0-16 + MOVD x+0(FP), F0 // F0 = x + + MOVV $exprodata<>+0(SB), R10 + MOVD 72(R10), F1 // Overflow2 + MOVD 80(R10), F2 // Underflow2 + MOVD 88(R10), F3 // NearZero + + CMPEQD F0, F0, FCC0 + BFPF isNaN // x = NaN, return NaN + + CMPGTD F0, F1, FCC0 + BFPT overflow // x > Overflow, return PosInf + + CMPGTD F2, F0, FCC0 + BFPT underflow // x < Underflow, return 0 + + // argument reduction; x = r*lg(e) + k with |r| <= ln(2)/2 + // computed as r = hi - lo for extra precision. + MOVD 0(R10), F10 + MOVD 8(R10), F2 + CMPGTD F0, F10, FCC0 + BFPT add +sub: + SUBD F2, F0, F3 // x - 0.5 + JMP 2(PC) +add: + ADDD F2, F0, F3 // x + 0.5 + + FTINTRZVD F3, F4 + MOVV F4, R5 + FFINTDV F4, F3 + + MOVD 32(R10), F4 + MOVD 40(R10), F5 + SUBD F3, F0, F3 + MULD F3, F4 + FNMSUBD F10, F3, F5, F5 + SUBD F5, F4, F6 + MULD F6, F6, F7 + + // compute c + MOVV $expmultirodata<>+0(SB), R11 + MOVD 32(R11), F8 + MOVD 24(R11), F9 + FMADDD F9, F8, F7, F13 + MOVD 16(R11), F10 + FMADDD F10, F13, F7, F13 + MOVD 8(R11), F11 + FMADDD F11, F13, F7, F13 + MOVD 0(R11), F12 + FMADDD F12, F13, F7, F13 + FNMSUBD F6, F13, F7, F13 + + // compute y + MOVD 24(R10), F14 + SUBD F13, F14, F14 + MULD F6, F13, F15 + DIVD F14, F15 + + MOVD 16(R10), F17 + SUBD F15, F5, F15 + SUBD F4, F15, F15 + SUBD F15, F17, F16 + + // inline Ldexp(y, k), benefit: + // 1, no parameter pass overhead. + // 2, skip unnecessary checks for Inf/NaN/Zero + MOVV F16, R4 + MOVV $FracMask, R9 + SRLV $52, R4, R7 // exponent + AND R9, R4, R6 // fraction + ADDV R5, R7 + MOVV $1, R12 + BGE R7, R12, normal + + ADDV $52, R7 // denormal + MOVV $C1, R8 + MOVV R8, F17 +normal: + SLLV $52, R7 + OR R7, R6, R4 + MOVV R4, F0 + MULD F17, F0 +isNaN: + MOVD F0, ret+8(FP) + RET +underflow: + MOVV R0, ret+8(FP) + RET +overflow: + MOVV $PosInf, R4 + MOVV R4, ret+8(FP) + RET diff --git a/go/src/math/exp_noasm.go b/go/src/math/exp_noasm.go new file mode 100644 index 0000000000000000000000000000000000000000..bf5e84b736b26f700f6f7fb5c1569c28dfa4f17f --- /dev/null +++ b/go/src/math/exp_noasm.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !amd64 && !arm64 && !loong64 && !s390x + +package math + +const haveArchExp = false + +func archExp(x float64) float64 { + panic("not implemented") +} diff --git a/go/src/math/exp_s390x.s b/go/src/math/exp_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..baf0e985a1e2939410df95508eda904cf5613864 --- /dev/null +++ b/go/src/math/exp_s390x.s @@ -0,0 +1,177 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial approximation and other constants +DATA ·exprodataL22<> + 0(SB)/8, $800.0E+00 +DATA ·exprodataL22<> + 8(SB)/8, $1.0000000000000022e+00 +DATA ·exprodataL22<> + 16(SB)/8, $0.500000000000004237e+00 +DATA ·exprodataL22<> + 24(SB)/8, $0.166666666630345592e+00 +DATA ·exprodataL22<> + 32(SB)/8, $0.138926439368309441e-02 +DATA ·exprodataL22<> + 40(SB)/8, $0.833349307718286047e-02 +DATA ·exprodataL22<> + 48(SB)/8, $0.416666664838056960e-01 +DATA ·exprodataL22<> + 56(SB)/8, $-.231904681384629956E-16 +DATA ·exprodataL22<> + 64(SB)/8, $-.693147180559945286E+00 +DATA ·exprodataL22<> + 72(SB)/8, $0.144269504088896339E+01 +DATA ·exprodataL22<> + 80(SB)/8, $704.0E+00 +GLOBL ·exprodataL22<> + 0(SB), RODATA, $88 + +DATA ·expxinf<> + 0(SB)/8, $0x7ff0000000000000 +GLOBL ·expxinf<> + 0(SB), RODATA, $8 +DATA ·expx4ff<> + 0(SB)/8, $0x4ff0000000000000 +GLOBL ·expx4ff<> + 0(SB), RODATA, $8 +DATA ·expx2ff<> + 0(SB)/8, $0x2ff0000000000000 +GLOBL ·expx2ff<> + 0(SB), RODATA, $8 +DATA ·expxaddexp<> + 0(SB)/8, $0xc2f0000100003fef +GLOBL ·expxaddexp<> + 0(SB), RODATA, $8 + +// Log multipliers table +DATA ·exptexp<> + 0(SB)/8, $0.442737824274138381E-01 +DATA ·exptexp<> + 8(SB)/8, $0.263602189790660309E-01 +DATA ·exptexp<> + 16(SB)/8, $0.122565642281703586E-01 +DATA ·exptexp<> + 24(SB)/8, $0.143757052860721398E-02 +DATA ·exptexp<> + 32(SB)/8, $-.651375034121276075E-02 +DATA ·exptexp<> + 40(SB)/8, $-.119317678849450159E-01 +DATA ·exptexp<> + 48(SB)/8, $-.150868749549871069E-01 +DATA ·exptexp<> + 56(SB)/8, $-.161992609578469234E-01 +DATA ·exptexp<> + 64(SB)/8, $-.154492360403337917E-01 +DATA ·exptexp<> + 72(SB)/8, $-.129850717389178721E-01 +DATA ·exptexp<> + 80(SB)/8, $-.892902649276657891E-02 +DATA ·exptexp<> + 88(SB)/8, $-.338202636596794887E-02 +DATA ·exptexp<> + 96(SB)/8, $0.357266307045684762E-02 +DATA ·exptexp<> + 104(SB)/8, $0.118665304327406698E-01 +DATA ·exptexp<> + 112(SB)/8, $0.214434994118118914E-01 +DATA ·exptexp<> + 120(SB)/8, $0.322580645161290314E-01 +GLOBL ·exptexp<> + 0(SB), RODATA, $128 + +// Exp returns e**x, the base-e exponential of x. +// +// Special cases are: +// Exp(+Inf) = +Inf +// Exp(NaN) = NaN +// Very large values overflow to 0 or +Inf. +// Very small values underflow to 1. +// The algorithm used is minimax polynomial approximation using a table of +// polynomial coefficients determined with a Remez exchange algorithm. + +TEXT ·expAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·exprodataL22<>+0(SB), R5 + LTDBR F0, F0 + BLTU L20 + FMOVD F0, F2 +L2: + WORD $0xED205050 //cdb %f2,.L23-.L22(%r5) + BYTE $0x00 + BYTE $0x19 + BGE L16 + BVS L16 + WFCEDBS V2, V2, V2 + BVS LEXITTAGexp + MOVD $·expxaddexp<>+0(SB), R1 + FMOVD 72(R5), F6 + FMOVD 0(R1), F2 + WFMSDB V0, V6, V2, V6 + FMOVD 64(R5), F4 + FADD F6, F2 + FMOVD 56(R5), F1 + FMADD F4, F2, F0 + FMOVD 48(R5), F3 + WFMADB V2, V1, V0, V2 + FMOVD 40(R5), F1 + FMOVD 32(R5), F4 + FMUL F0, F0 + WFMADB V2, V4, V1, V4 + LGDR F6, R1 + FMOVD 24(R5), F1 + WFMADB V2, V3, V1, V3 + FMOVD 16(R5), F1 + WFMADB V0, V4, V3, V4 + FMOVD 8(R5), F3 + WFMADB V2, V1, V3, V1 + RISBGZ $57, $60, $3, R1, R3 + WFMADB V0, V4, V1, V0 + MOVD $·exptexp<>+0(SB), R2 + WORD $0x68432000 //ld %f4,0(%r3,%r2) + FMADD F4, F2, F2 + SLD $48, R1, R2 + WFMADB V2, V0, V4, V2 + LDGR R2, F0 + FMADD F0, F2, F0 + FMOVD F0, ret+8(FP) + RET +L16: + WFCEDBS V2, V2, V4 + BVS LEXITTAGexp + WORD $0xED205000 //cdb %f2,.L33-.L22(%r5) + BYTE $0x00 + BYTE $0x19 + BLT L6 + WFCEDBS V2, V0, V0 + BVS L13 + MOVD $·expxinf<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET +L20: + LCDBR F0, F2 + BR L2 +L6: + MOVD $·expxaddexp<>+0(SB), R1 + FMOVD 72(R5), F3 + FMOVD 0(R1), F4 + WFMSDB V0, V3, V4, V3 + FMOVD 64(R5), F6 + FADD F3, F4 + FMOVD 56(R5), F5 + WFMADB V4, V6, V0, V6 + FMOVD 32(R5), F1 + WFMADB V4, V5, V6, V4 + FMOVD 40(R5), F5 + FMUL F6, F6 + WFMADB V4, V1, V5, V1 + FMOVD 48(R5), F7 + LGDR F3, R1 + FMOVD 24(R5), F5 + WFMADB V4, V7, V5, V7 + FMOVD 16(R5), F5 + WFMADB V6, V1, V7, V1 + FMOVD 8(R5), F7 + WFMADB V4, V5, V7, V5 + RISBGZ $57, $60, $3, R1, R3 + WFMADB V6, V1, V5, V6 + MOVD $·exptexp<>+0(SB), R2 + WFCHDBS V2, V0, V0 + WORD $0x68132000 //ld %f1,0(%r3,%r2) + FMADD F1, F4, F4 + MOVD $0x4086000000000000, R2 + WFMADB V4, V6, V1, V4 + BEQ L21 + ADDW $0xF000, R1 + RISBGN $0, $15, $48, R1, R2 + LDGR R2, F0 + FMADD F0, F4, F0 + MOVD $·expx4ff<>+0(SB), R3 + FMOVD 0(R3), F2 + FMUL F2, F0 + FMOVD F0, ret+8(FP) + RET +L13: + FMOVD $0, F0 + FMOVD F0, ret+8(FP) + RET +L21: + ADDW $0x1000, R1 + RISBGN $0, $15, $48, R1, R2 + LDGR R2, F0 + FMADD F0, F4, F0 + MOVD $·expx2ff<>+0(SB), R3 + FMOVD 0(R3), F2 + FMUL F2, F0 + FMOVD F0, ret+8(FP) + RET +LEXITTAGexp: + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/expm1.go b/go/src/math/expm1.go new file mode 100644 index 0000000000000000000000000000000000000000..f8e45d9becf2be550498dd58d2b3efb56cfd107d --- /dev/null +++ b/go/src/math/expm1.go @@ -0,0 +1,244 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/s_expm1.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// expm1(x) +// Returns exp(x)-1, the exponential of x minus 1. +// +// Method +// 1. Argument reduction: +// Given x, find r and integer k such that +// +// x = k*ln2 + r, |r| <= 0.5*ln2 ~ 0.34658 +// +// Here a correction term c will be computed to compensate +// the error in r when rounded to a floating-point number. +// +// 2. Approximating expm1(r) by a special rational function on +// the interval [0,0.34658]: +// Since +// r*(exp(r)+1)/(exp(r)-1) = 2+ r**2/6 - r**4/360 + ... +// we define R1(r*r) by +// r*(exp(r)+1)/(exp(r)-1) = 2+ r**2/6 * R1(r*r) +// That is, +// R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r) +// = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r)) +// = 1 - r**2/60 + r**4/2520 - r**6/100800 + ... +// We use a special Reme algorithm on [0,0.347] to generate +// a polynomial of degree 5 in r*r to approximate R1. The +// maximum error of this polynomial approximation is bounded +// by 2**-61. In other words, +// R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5 +// where Q1 = -1.6666666666666567384E-2, +// Q2 = 3.9682539681370365873E-4, +// Q3 = -9.9206344733435987357E-6, +// Q4 = 2.5051361420808517002E-7, +// Q5 = -6.2843505682382617102E-9; +// (where z=r*r, and the values of Q1 to Q5 are listed below) +// with error bounded by +// | 5 | -61 +// | 1.0+Q1*z+...+Q5*z - R1(z) | <= 2 +// | | +// +// expm1(r) = exp(r)-1 is then computed by the following +// specific way which minimize the accumulation rounding error: +// 2 3 +// r r [ 3 - (R1 + R1*r/2) ] +// expm1(r) = r + --- + --- * [--------------------] +// 2 2 [ 6 - r*(3 - R1*r/2) ] +// +// To compensate the error in the argument reduction, we use +// expm1(r+c) = expm1(r) + c + expm1(r)*c +// ~ expm1(r) + c + r*c +// Thus c+r*c will be added in as the correction terms for +// expm1(r+c). Now rearrange the term to avoid optimization +// screw up: +// ( 2 2 ) +// ({ ( r [ R1 - (3 - R1*r/2) ] ) } r ) +// expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- ) +// ({ ( 2 [ 6 - r*(3 - R1*r/2) ] ) } 2 ) +// ( ) +// +// = r - E +// 3. Scale back to obtain expm1(x): +// From step 1, we have +// expm1(x) = either 2**k*[expm1(r)+1] - 1 +// = or 2**k*[expm1(r) + (1-2**-k)] +// 4. Implementation notes: +// (A). To save one multiplication, we scale the coefficient Qi +// to Qi*2**i, and replace z by (x**2)/2. +// (B). To achieve maximum accuracy, we compute expm1(x) by +// (i) if x < -56*ln2, return -1.0, (raise inexact if x!=inf) +// (ii) if k=0, return r-E +// (iii) if k=-1, return 0.5*(r-E)-0.5 +// (iv) if k=1 if r < -0.25, return 2*((r+0.5)- E) +// else return 1.0+2.0*(r-E); +// (v) if (k<-2||k>56) return 2**k(1-(E-r)) - 1 (or exp(x)-1) +// (vi) if k <= 20, return 2**k((1-2**-k)-(E-r)), else +// (vii) return 2**k(1-((E+2**-k)-r)) +// +// Special cases: +// expm1(INF) is INF, expm1(NaN) is NaN; +// expm1(-INF) is -1, and +// for finite argument, only expm1(0)=0 is exact. +// +// Accuracy: +// according to an error analysis, the error is always less than +// 1 ulp (unit in the last place). +// +// Misc. info. +// For IEEE double +// if x > 7.09782712893383973096e+02 then expm1(x) overflow +// +// Constants: +// The hexadecimal values are the intended ones for the following +// constants. The decimal values may be used, provided that the +// compiler will convert from decimal to binary accurately enough +// to produce the hexadecimal values shown. +// + +// Expm1 returns e**x - 1, the base-e exponential of x minus 1. +// It is more accurate than [Exp](x) - 1 when x is near zero. +// +// Special cases are: +// +// Expm1(+Inf) = +Inf +// Expm1(-Inf) = -1 +// Expm1(NaN) = NaN +// +// Very large values overflow to -1 or +Inf. +func Expm1(x float64) float64 { + if haveArchExpm1 { + return archExpm1(x) + } + return expm1(x) +} + +func expm1(x float64) float64 { + const ( + Othreshold = 7.09782712893383973096e+02 // 0x40862E42FEFA39EF + Ln2X56 = 3.88162421113569373274e+01 // 0x4043687a9f1af2b1 + Ln2HalfX3 = 1.03972077083991796413e+00 // 0x3ff0a2b23f3bab73 + Ln2Half = 3.46573590279972654709e-01 // 0x3fd62e42fefa39ef + Ln2Hi = 6.93147180369123816490e-01 // 0x3fe62e42fee00000 + Ln2Lo = 1.90821492927058770002e-10 // 0x3dea39ef35793c76 + InvLn2 = 1.44269504088896338700e+00 // 0x3ff71547652b82fe + Tiny = 1.0 / (1 << 54) // 2**-54 = 0x3c90000000000000 + // scaled coefficients related to expm1 + Q1 = -3.33333333333331316428e-02 // 0xBFA11111111110F4 + Q2 = 1.58730158725481460165e-03 // 0x3F5A01A019FE5585 + Q3 = -7.93650757867487942473e-05 // 0xBF14CE199EAADBB7 + Q4 = 4.00821782732936239552e-06 // 0x3ED0CFCA86E65239 + Q5 = -2.01099218183624371326e-07 // 0xBE8AFDB76E09C32D + ) + + // special cases + switch { + case IsInf(x, 1) || IsNaN(x): + return x + case IsInf(x, -1): + return -1 + } + + absx := x + sign := false + if x < 0 { + absx = -absx + sign = true + } + + // filter out huge argument + if absx >= Ln2X56 { // if |x| >= 56 * ln2 + if sign { + return -1 // x < -56*ln2, return -1 + } + if absx >= Othreshold { // if |x| >= 709.78... + return Inf(1) + } + } + + // argument reduction + var c float64 + var k int + if absx > Ln2Half { // if |x| > 0.5 * ln2 + var hi, lo float64 + if absx < Ln2HalfX3 { // and |x| < 1.5 * ln2 + if !sign { + hi = x - Ln2Hi + lo = Ln2Lo + k = 1 + } else { + hi = x + Ln2Hi + lo = -Ln2Lo + k = -1 + } + } else { + if !sign { + k = int(InvLn2*x + 0.5) + } else { + k = int(InvLn2*x - 0.5) + } + t := float64(k) + hi = x - t*Ln2Hi // t * Ln2Hi is exact here + lo = t * Ln2Lo + } + x = hi - lo + c = (hi - x) - lo + } else if absx < Tiny { // when |x| < 2**-54, return x + return x + } else { + k = 0 + } + + // x is now in primary range + hfx := 0.5 * x + hxs := x * hfx + r1 := 1 + hxs*(Q1+hxs*(Q2+hxs*(Q3+hxs*(Q4+hxs*Q5)))) + t := 3 - r1*hfx + e := hxs * ((r1 - t) / (6.0 - x*t)) + if k == 0 { + return x - (x*e - hxs) // c is 0 + } + e = (x*(e-c) - c) + e -= hxs + switch { + case k == -1: + return 0.5*(x-e) - 0.5 + case k == 1: + if x < -0.25 { + return -2 * (e - (x + 0.5)) + } + return 1 + 2*(x-e) + case k <= -2 || k > 56: // suffice to return exp(x)-1 + y := 1 - (e - x) + y = Float64frombits(Float64bits(y) + uint64(k)<<52) // add k to y's exponent + return y - 1 + } + if k < 20 { + t := Float64frombits(0x3ff0000000000000 - (0x20000000000000 >> uint(k))) // t=1-2**-k + y := t - (e - x) + y = Float64frombits(Float64bits(y) + uint64(k)<<52) // add k to y's exponent + return y + } + t = Float64frombits(uint64(0x3ff-k) << 52) // 2**-k + y := x - (e + t) + y++ + y = Float64frombits(Float64bits(y) + uint64(k)<<52) // add k to y's exponent + return y +} diff --git a/go/src/math/expm1_s390x.s b/go/src/math/expm1_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..c193edc7cb8794127d8c393ef2ebdfbe44b95380 --- /dev/null +++ b/go/src/math/expm1_s390x.s @@ -0,0 +1,194 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial approximation and other constants +DATA ·expm1rodataL22<> + 0(SB)/8, $-1.0 +DATA ·expm1rodataL22<> + 8(SB)/8, $800.0E+00 +DATA ·expm1rodataL22<> + 16(SB)/8, $1.0 +DATA ·expm1rodataL22<> + 24(SB)/8, $-.231904681384629956E-16 +DATA ·expm1rodataL22<> + 32(SB)/8, $0.50000000000000029671E+00 +DATA ·expm1rodataL22<> + 40(SB)/8, $0.16666666666666676570E+00 +DATA ·expm1rodataL22<> + 48(SB)/8, $0.83333333323590973444E-02 +DATA ·expm1rodataL22<> + 56(SB)/8, $0.13889096526400683566E-02 +DATA ·expm1rodataL22<> + 64(SB)/8, $0.41666666661701152924E-01 +DATA ·expm1rodataL22<> + 72(SB)/8, $0.19841562053987360264E-03 +DATA ·expm1rodataL22<> + 80(SB)/8, $-.693147180559945286E+00 +DATA ·expm1rodataL22<> + 88(SB)/8, $0.144269504088896339E+01 +DATA ·expm1rodataL22<> + 96(SB)/8, $704.0E+00 +GLOBL ·expm1rodataL22<> + 0(SB), RODATA, $104 + +DATA ·expm1xmone<> + 0(SB)/8, $0xbff0000000000000 +GLOBL ·expm1xmone<> + 0(SB), RODATA, $8 +DATA ·expm1xinf<> + 0(SB)/8, $0x7ff0000000000000 +GLOBL ·expm1xinf<> + 0(SB), RODATA, $8 +DATA ·expm1x4ff<> + 0(SB)/8, $0x4ff0000000000000 +GLOBL ·expm1x4ff<> + 0(SB), RODATA, $8 +DATA ·expm1x2ff<> + 0(SB)/8, $0x2ff0000000000000 +GLOBL ·expm1x2ff<> + 0(SB), RODATA, $8 +DATA ·expm1xaddexp<> + 0(SB)/8, $0xc2f0000100003ff0 +GLOBL ·expm1xaddexp<> + 0(SB), RODATA, $8 + +// Log multipliers table +DATA ·expm1tab<> + 0(SB)/8, $0.0 +DATA ·expm1tab<> + 8(SB)/8, $-.171540871271399150E-01 +DATA ·expm1tab<> + 16(SB)/8, $-.306597931864376363E-01 +DATA ·expm1tab<> + 24(SB)/8, $-.410200970469965021E-01 +DATA ·expm1tab<> + 32(SB)/8, $-.486343079978231466E-01 +DATA ·expm1tab<> + 40(SB)/8, $-.538226193725835820E-01 +DATA ·expm1tab<> + 48(SB)/8, $-.568439602538111520E-01 +DATA ·expm1tab<> + 56(SB)/8, $-.579091847395528847E-01 +DATA ·expm1tab<> + 64(SB)/8, $-.571909584179366341E-01 +DATA ·expm1tab<> + 72(SB)/8, $-.548312665987204407E-01 +DATA ·expm1tab<> + 80(SB)/8, $-.509471843643441085E-01 +DATA ·expm1tab<> + 88(SB)/8, $-.456353588448863359E-01 +DATA ·expm1tab<> + 96(SB)/8, $-.389755254243262365E-01 +DATA ·expm1tab<> + 104(SB)/8, $-.310332908285244231E-01 +DATA ·expm1tab<> + 112(SB)/8, $-.218623539150173528E-01 +DATA ·expm1tab<> + 120(SB)/8, $-.115062908917949451E-01 +GLOBL ·expm1tab<> + 0(SB), RODATA, $128 + +// Expm1 returns e**x - 1, the base-e exponential of x minus 1. +// It is more accurate than Exp(x) - 1 when x is near zero. +// +// Special cases are: +// Expm1(+Inf) = +Inf +// Expm1(-Inf) = -1 +// Expm1(NaN) = NaN +// Very large values overflow to -1 or +Inf. +// The algorithm used is minimax polynomial approximation using a table of +// polynomial coefficients determined with a Remez exchange algorithm. + +TEXT ·expm1Asm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·expm1rodataL22<>+0(SB), R5 + LTDBR F0, F0 + BLTU L20 + FMOVD F0, F2 +L2: + WORD $0xED205060 //cdb %f2,.L23-.L22(%r5) + BYTE $0x00 + BYTE $0x19 + BGE L16 + BVS L16 + WFCEDBS V2, V2, V2 + BVS LEXITTAGexpm1 + MOVD $·expm1xaddexp<>+0(SB), R1 + FMOVD 88(R5), F1 + FMOVD 0(R1), F2 + WFMSDB V0, V1, V2, V1 + FMOVD 80(R5), F6 + WFADB V1, V2, V4 + FMOVD 72(R5), F2 + FMADD F6, F4, F0 + FMOVD 64(R5), F3 + FMOVD 56(R5), F6 + FMOVD 48(R5), F5 + FMADD F2, F0, F6 + WFMADB V0, V5, V3, V5 + WFMDB V0, V0, V2 + LGDR F1, R1 + WFMADB V6, V2, V5, V6 + FMOVD 40(R5), F3 + FMOVD 32(R5), F5 + WFMADB V0, V3, V5, V3 + FMOVD 24(R5), F5 + WFMADB V2, V6, V3, V2 + FMADD F5, F4, F0 + FMOVD 16(R5), F6 + WFMADB V0, V2, V6, V2 + RISBGZ $57, $60, $3, R1, R3 + LCDBR F2, F2 + MOVD $·expm1tab<>+0(SB), R2 + WORD $0x68432000 //ld %f4,0(%r3,%r2) + FMADD F4, F0, F0 + SLD $48, R1, R2 + WFMSDB V2, V0, V4, V0 + LDGR R2, F4 + LCDBR F0, F0 + FSUB F4, F6 + WFMSDB V0, V4, V6, V0 + FMOVD F0, ret+8(FP) + RET +L16: + WFCEDBS V2, V2, V4 + BVS LEXITTAGexpm1 + WORD $0xED205008 //cdb %f2,.L34-.L22(%r5) + BYTE $0x00 + BYTE $0x19 + BLT L6 + WFCEDBS V2, V0, V0 + BVS L7 + MOVD $·expm1xinf<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET +L20: + LCDBR F0, F2 + BR L2 +L6: + MOVD $·expm1xaddexp<>+0(SB), R1 + FMOVD 88(R5), F5 + FMOVD 0(R1), F4 + WFMSDB V0, V5, V4, V5 + FMOVD 80(R5), F3 + WFADB V5, V4, V1 + VLEG $0, 48(R5), V16 + WFMADB V1, V3, V0, V3 + FMOVD 56(R5), F4 + FMOVD 64(R5), F7 + FMOVD 72(R5), F6 + WFMADB V3, V16, V7, V16 + WFMADB V3, V6, V4, V6 + WFMDB V3, V3, V4 + MOVD $·expm1tab<>+0(SB), R2 + WFMADB V6, V4, V16, V6 + VLEG $0, 32(R5), V16 + FMOVD 40(R5), F7 + WFMADB V3, V7, V16, V7 + VLEG $0, 24(R5), V16 + WFMADB V4, V6, V7, V4 + WFMADB V1, V16, V3, V1 + FMOVD 16(R5), F6 + FMADD F4, F1, F6 + LGDR F5, R1 + LCDBR F6, F6 + RISBGZ $57, $60, $3, R1, R3 + WORD $0x68432000 //ld %f4,0(%r3,%r2) + FMADD F4, F1, F1 + MOVD $0x4086000000000000, R2 + FMSUB F1, F6, F4 + LCDBR F4, F4 + WFCHDBS V2, V0, V0 + BEQ L21 + ADDW $0xF000, R1 + RISBGN $0, $15, $48, R1, R2 + LDGR R2, F0 + FMADD F0, F4, F0 + MOVD $·expm1x4ff<>+0(SB), R3 + FMOVD 0(R5), F4 + FMOVD 0(R3), F2 + WFMADB V2, V0, V4, V0 + FMOVD F0, ret+8(FP) + RET +L7: + MOVD $·expm1xmone<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET +L21: + ADDW $0x1000, R1 + RISBGN $0, $15, $48, R1, R2 + LDGR R2, F0 + FMADD F0, F4, F0 + MOVD $·expm1x2ff<>+0(SB), R3 + FMOVD 0(R5), F4 + FMOVD 0(R3), F2 + WFMADB V2, V0, V4, V0 + FMOVD F0, ret+8(FP) + RET +LEXITTAGexpm1: + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/export_s390x_test.go b/go/src/math/export_s390x_test.go new file mode 100644 index 0000000000000000000000000000000000000000..827bf1c8f60f3846d72836782a6a1d968e076252 --- /dev/null +++ b/go/src/math/export_s390x_test.go @@ -0,0 +1,31 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Export internal functions and variable for testing. +var Log10NoVec = log10 +var CosNoVec = cos +var CoshNoVec = cosh +var SinNoVec = sin +var SinhNoVec = sinh +var TanhNoVec = tanh +var Log1pNovec = log1p +var AtanhNovec = atanh +var AcosNovec = acos +var AcoshNovec = acosh +var AsinNovec = asin +var AsinhNovec = asinh +var ErfNovec = erf +var ErfcNovec = erfc +var AtanNovec = atan +var Atan2Novec = atan2 +var CbrtNovec = cbrt +var LogNovec = log +var TanNovec = tan +var ExpNovec = exp +var Expm1Novec = expm1 +var PowNovec = pow +var HypotNovec = hypot +var HasVX = hasVX diff --git a/go/src/math/export_test.go b/go/src/math/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..53d9205b9d1693d745e12695cb3d05fe576aef32 --- /dev/null +++ b/go/src/math/export_test.go @@ -0,0 +1,14 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Export internal functions for testing. +var ExpGo = exp +var Exp2Go = exp2 +var HypotGo = hypot +var SqrtGo = sqrt +var TrigReduce = trigReduce + +const ReduceThreshold = reduceThreshold diff --git a/go/src/math/floor.go b/go/src/math/floor.go new file mode 100644 index 0000000000000000000000000000000000000000..20a764112478c8713157ea63703dab451f367873 --- /dev/null +++ b/go/src/math/floor.go @@ -0,0 +1,158 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Floor returns the greatest integer value less than or equal to x. +// +// Special cases are: +// +// Floor(±0) = ±0 +// Floor(±Inf) = ±Inf +// Floor(NaN) = NaN +func Floor(x float64) float64 { + if haveArchFloor { + return archFloor(x) + } + return floor(x) +} + +func floor(x float64) float64 { + if x == 0 || IsNaN(x) || IsInf(x, 0) { + return x + } + if x < 0 { + d, fract := Modf(-x) + if fract != 0.0 { + d = d + 1 + } + return -d + } + d, _ := Modf(x) + return d +} + +// Ceil returns the least integer value greater than or equal to x. +// +// Special cases are: +// +// Ceil(±0) = ±0 +// Ceil(±Inf) = ±Inf +// Ceil(NaN) = NaN +func Ceil(x float64) float64 { + if haveArchCeil { + return archCeil(x) + } + return ceil(x) +} + +func ceil(x float64) float64 { + return -Floor(-x) +} + +// Trunc returns the integer value of x. +// +// Special cases are: +// +// Trunc(±0) = ±0 +// Trunc(±Inf) = ±Inf +// Trunc(NaN) = NaN +func Trunc(x float64) float64 { + if haveArchTrunc { + return archTrunc(x) + } + return trunc(x) +} + +func trunc(x float64) float64 { + if Abs(x) < 1 { + return Copysign(0, x) + } + + b := Float64bits(x) + e := uint(b>>shift)&mask - bias + + // Keep the top 12+e bits, the integer part; clear the rest. + if e < 64-12 { + b &^= 1<<(64-12-e) - 1 + } + return Float64frombits(b) +} + +// Round returns the nearest integer, rounding half away from zero. +// +// Special cases are: +// +// Round(±0) = ±0 +// Round(±Inf) = ±Inf +// Round(NaN) = NaN +func Round(x float64) float64 { + // Round is a faster implementation of: + // + // func Round(x float64) float64 { + // t := Trunc(x) + // if Abs(x-t) >= 0.5 { + // return t + Copysign(1, x) + // } + // return t + // } + bits := Float64bits(x) + e := uint(bits>>shift) & mask + if e < bias { + // Round abs(x) < 1 including denormals. + bits &= signMask // +-0 + if e == bias-1 { + bits |= uvone // +-1 + } + } else if e < bias+shift { + // Round any abs(x) >= 1 containing a fractional component [0,1). + // + // Numbers with larger exponents are returned unchanged since they + // must be either an integer, infinity, or NaN. + const half = 1 << (shift - 1) + e -= bias + bits += half >> e + bits &^= fracMask >> e + } + return Float64frombits(bits) +} + +// RoundToEven returns the nearest integer, rounding ties to even. +// +// Special cases are: +// +// RoundToEven(±0) = ±0 +// RoundToEven(±Inf) = ±Inf +// RoundToEven(NaN) = NaN +func RoundToEven(x float64) float64 { + // RoundToEven is a faster implementation of: + // + // func RoundToEven(x float64) float64 { + // t := math.Trunc(x) + // odd := math.Remainder(t, 2) != 0 + // if d := math.Abs(x - t); d > 0.5 || (d == 0.5 && odd) { + // return t + math.Copysign(1, x) + // } + // return t + // } + bits := Float64bits(x) + e := uint(bits>>shift) & mask + if e >= bias { + // Round abs(x) >= 1. + // - Large numbers without fractional components, infinity, and NaN are unchanged. + // - Add 0.499.. or 0.5 before truncating depending on whether the truncated + // number is even or odd (respectively). + const halfMinusULP = (1 << (shift - 1)) - 1 + e -= bias + bits += (halfMinusULP + (bits>>(shift-e))&1) >> e + bits &^= fracMask >> e + } else if e == bias-1 && bits&fracMask != 0 { + // Round 0.5 < abs(x) < 1. + bits = bits&signMask | uvone // +-1 + } else { + // Round abs(x) <= 0.5 including denormals. + bits &= signMask // +-0 + } + return Float64frombits(bits) +} diff --git a/go/src/math/floor_386.s b/go/src/math/floor_386.s new file mode 100644 index 0000000000000000000000000000000000000000..1990cb0c8c00d56c2dffa7e9eab5613afd95f2b4 --- /dev/null +++ b/go/src/math/floor_386.s @@ -0,0 +1,46 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func archCeil(x float64) float64 +TEXT ·archCeil(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 // F0=x + FSTCW -2(SP) // save old Control Word + MOVW -2(SP), AX + ANDW $0xf3ff, AX + ORW $0x0800, AX // Rounding Control set to +Inf + MOVW AX, -4(SP) // store new Control Word + FLDCW -4(SP) // load new Control Word + FRNDINT // F0=Ceil(x) + FLDCW -2(SP) // load old Control Word + FMOVDP F0, ret+8(FP) + RET + +// func archFloor(x float64) float64 +TEXT ·archFloor(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 // F0=x + FSTCW -2(SP) // save old Control Word + MOVW -2(SP), AX + ANDW $0xf3ff, AX + ORW $0x0400, AX // Rounding Control set to -Inf + MOVW AX, -4(SP) // store new Control Word + FLDCW -4(SP) // load new Control Word + FRNDINT // F0=Floor(x) + FLDCW -2(SP) // load old Control Word + FMOVDP F0, ret+8(FP) + RET + +// func archTrunc(x float64) float64 +TEXT ·archTrunc(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 // F0=x + FSTCW -2(SP) // save old Control Word + MOVW -2(SP), AX + ORW $0x0c00, AX // Rounding Control set to truncate + MOVW AX, -4(SP) // store new Control Word + FLDCW -4(SP) // load new Control Word + FRNDINT // F0=Trunc(x) + FLDCW -2(SP) // load old Control Word + FMOVDP F0, ret+8(FP) + RET diff --git a/go/src/math/floor_amd64.s b/go/src/math/floor_amd64.s new file mode 100644 index 0000000000000000000000000000000000000000..088049958ab4c7bf392bc119bcb710c48f7b0422 --- /dev/null +++ b/go/src/math/floor_amd64.s @@ -0,0 +1,76 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define Big 0x4330000000000000 // 2**52 + +// func archFloor(x float64) float64 +TEXT ·archFloor(SB),NOSPLIT,$0 + MOVQ x+0(FP), AX + MOVQ $~(1<<63), DX // sign bit mask + ANDQ AX,DX // DX = |x| + SUBQ $1,DX + MOVQ $(Big - 1), CX // if |x| >= 2**52-1 or IsNaN(x) or |x| == 0, return x + CMPQ DX,CX + JAE isBig_floor + MOVQ AX, X0 // X0 = x + CVTTSD2SQ X0, AX + CVTSQ2SD AX, X1 // X1 = float(int(x)) + CMPSD X1, X0, 1 // compare LT; X0 = 0xffffffffffffffff or 0 + MOVSD $(-1.0), X2 + ANDPD X2, X0 // if x < float(int(x)) {X0 = -1} else {X0 = 0} + ADDSD X1, X0 + MOVSD X0, ret+8(FP) + RET +isBig_floor: + MOVQ AX, ret+8(FP) // return x + RET + +// func archCeil(x float64) float64 +TEXT ·archCeil(SB),NOSPLIT,$0 + MOVQ x+0(FP), AX + MOVQ $~(1<<63), DX // sign bit mask + MOVQ AX, BX // BX = copy of x + ANDQ DX, BX // BX = |x| + MOVQ $Big, CX // if |x| >= 2**52 or IsNaN(x), return x + CMPQ BX, CX + JAE isBig_ceil + MOVQ AX, X0 // X0 = x + MOVQ DX, X2 // X2 = sign bit mask + CVTTSD2SQ X0, AX + ANDNPD X0, X2 // X2 = sign + CVTSQ2SD AX, X1 // X1 = float(int(x)) + CMPSD X1, X0, 2 // compare LE; X0 = 0xffffffffffffffff or 0 + ORPD X2, X1 // if X1 = 0.0, incorporate sign + MOVSD $1.0, X3 + ANDNPD X3, X0 + ORPD X2, X0 // if float(int(x)) <= x {X0 = 1} else {X0 = -0} + ADDSD X1, X0 + MOVSD X0, ret+8(FP) + RET +isBig_ceil: + MOVQ AX, ret+8(FP) + RET + +// func archTrunc(x float64) float64 +TEXT ·archTrunc(SB),NOSPLIT,$0 + MOVQ x+0(FP), AX + MOVQ $~(1<<63), DX // sign bit mask + MOVQ AX, BX // BX = copy of x + ANDQ DX, BX // BX = |x| + MOVQ $Big, CX // if |x| >= 2**52 or IsNaN(x), return x + CMPQ BX, CX + JAE isBig_trunc + MOVQ AX, X0 + MOVQ DX, X2 // X2 = sign bit mask + CVTTSD2SQ X0, AX + ANDNPD X0, X2 // X2 = sign + CVTSQ2SD AX, X0 // X0 = float(int(x)) + ORPD X2, X0 // if X0 = 0.0, incorporate sign + MOVSD X0, ret+8(FP) + RET +isBig_trunc: + MOVQ AX, ret+8(FP) // return x + RET diff --git a/go/src/math/floor_arm64.s b/go/src/math/floor_arm64.s new file mode 100644 index 0000000000000000000000000000000000000000..d9c5df7b2472dbff1566042612a18e5181871718 --- /dev/null +++ b/go/src/math/floor_arm64.s @@ -0,0 +1,26 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func archFloor(x float64) float64 +TEXT ·archFloor(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FRINTMD F0, F0 + FMOVD F0, ret+8(FP) + RET + +// func archCeil(x float64) float64 +TEXT ·archCeil(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FRINTPD F0, F0 + FMOVD F0, ret+8(FP) + RET + +// func archTrunc(x float64) float64 +TEXT ·archTrunc(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FRINTZD F0, F0 + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/floor_asm.go b/go/src/math/floor_asm.go new file mode 100644 index 0000000000000000000000000000000000000000..1b06b8def9c65095e15373f35933499542b283a9 --- /dev/null +++ b/go/src/math/floor_asm.go @@ -0,0 +1,19 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build 386 || amd64 || arm64 || loong64 || ppc64 || ppc64le || riscv64 || s390x || wasm + +package math + +const haveArchFloor = true + +func archFloor(x float64) float64 + +const haveArchCeil = true + +func archCeil(x float64) float64 + +const haveArchTrunc = true + +func archTrunc(x float64) float64 diff --git a/go/src/math/floor_loong64.s b/go/src/math/floor_loong64.s new file mode 100644 index 0000000000000000000000000000000000000000..0df7deee60588d8ef76696da393222e4fa3605f1 --- /dev/null +++ b/go/src/math/floor_loong64.s @@ -0,0 +1,41 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// +// derived from math/floor_riscv64.s + +#include "textflag.h" + +#define ROUNDFN(NAME, FUNC) \ +TEXT NAME(SB),NOSPLIT,$0; \ + MOVD x+0(FP), F0; \ + MOVV F0, R11; \ + /* 1023: bias of exponent, [-2^53, 2^53]: exactly integer represent range */; \ + MOVV $1023+53, R12; \ + /* Drop all fraction bits */; \ + SRLV $52, R11, R11; \ + /* Remove sign bit */; \ + AND $0x7FF, R11, R11; \ + BLTU R12, R11, isExtremum; \ +normal:; \ + FUNC F0, F2; \ + MOVV F2, R10; \ + BEQ R10, R0, is0; \ + FFINTDV F2, F0; \ +/* Return either input is +-Inf, NaN(0x7FF) or out of precision limitation */; \ +isExtremum:; \ + MOVD F0, ret+8(FP); \ + RET; \ +is0:; \ + FCOPYSGD F0, F2, F2; \ + MOVD F2, ret+8(FP); \ + RET + +// func archFloor(x float64) float64 +ROUNDFN(·archFloor, FTINTRMVD) + +// func archCeil(x float64) float64 +ROUNDFN(·archCeil, FTINTRPVD) + +// func archTrunc(x float64) float64 +ROUNDFN(·archTrunc, FTINTRZVD) diff --git a/go/src/math/floor_noasm.go b/go/src/math/floor_noasm.go new file mode 100644 index 0000000000000000000000000000000000000000..34bd292f0e7751db536d61efca8b81230bc98416 --- /dev/null +++ b/go/src/math/floor_noasm.go @@ -0,0 +1,25 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !386 && !amd64 && !arm64 && !loong64 && !ppc64 && !ppc64le && !riscv64 && !s390x && !wasm + +package math + +const haveArchFloor = false + +func archFloor(x float64) float64 { + panic("not implemented") +} + +const haveArchCeil = false + +func archCeil(x float64) float64 { + panic("not implemented") +} + +const haveArchTrunc = false + +func archTrunc(x float64) float64 { + panic("not implemented") +} diff --git a/go/src/math/floor_ppc64x.s b/go/src/math/floor_ppc64x.s new file mode 100644 index 0000000000000000000000000000000000000000..e9c5d49f4a5aaf6dfd2a438ad2ec98acc8e5cfc9 --- /dev/null +++ b/go/src/math/floor_ppc64x.s @@ -0,0 +1,25 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build ppc64 || ppc64le + +#include "textflag.h" + +TEXT ·archFloor(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FRIM F0, F0 + FMOVD F0, ret+8(FP) + RET + +TEXT ·archCeil(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FRIP F0, F0 + FMOVD F0, ret+8(FP) + RET + +TEXT ·archTrunc(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FRIZ F0, F0 + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/floor_riscv64.s b/go/src/math/floor_riscv64.s new file mode 100644 index 0000000000000000000000000000000000000000..d9fe0ed8e2828ac860448943c3fca6065baf17e3 --- /dev/null +++ b/go/src/math/floor_riscv64.s @@ -0,0 +1,48 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// RISC-V offered floating-point (FP) rounding by FP conversion instructions (FCVT) +// with rounding mode field. +// As Go spec expects FP rounding result in FP, we have to use FCVT integer +// back to FP (fp -> int -> fp). +// RISC-V only set Inexact flag during invalid FP-integer conversion without changing any data, +// on the other hand, RISC-V sets out of integer represent range yet valid FP into NaN. +// When it comes to integer-FP conversion, invalid FP like NaN, +-Inf will be +// converted into the closest valid FP, for example: +// +// `Floor(-Inf) -> int64(0x7fffffffffffffff) -> float64(9.22e+18)` +// `Floor(18446744073709549568.0) -> int64(0x7fffffffffffffff) -> float64(9.22e+18)` +// +// This ISA conversion limitation requires we skip all invalid or out of range FP +// before any normal rounding operations. + +#define ROUNDFN(NAME, MODE) \ +TEXT NAME(SB),NOSPLIT,$0; \ + MOVD x+0(FP), F10; \ + FMVXD F10, X10; \ + /* Drop all fraction bits */;\ + SRL $52, X10, X12; \ + /* Remove sign bit */; \ + AND $0x7FF, X12, X12;\ + /* Return either input is +-Inf, NaN(0x7FF) or out of precision limitation */;\ + /* 1023: bias of exponent, [-2^53, 2^53]: exactly integer represent range */;\ + MOV $1023+53, X11; \ + BLTU X11, X12, 4(PC);\ + FCVTLD.MODE F10, X11; \ + FCVTDL X11, F11; \ + /* RISC-V rounds negative values to +0, restore original sign */;\ + FSGNJD F10, F11, F10; \ + MOVD F10, ret+8(FP); \ + RET + +// func archFloor(x float64) float64 +ROUNDFN(·archFloor, RDN) + +// func archCeil(x float64) float64 +ROUNDFN(·archCeil, RUP) + +// func archTrunc(x float64) float64 +ROUNDFN(·archTrunc, RTZ) diff --git a/go/src/math/floor_s390x.s b/go/src/math/floor_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..b5dd462e526926bfb6d61911a898c37907f05c25 --- /dev/null +++ b/go/src/math/floor_s390x.s @@ -0,0 +1,26 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func archFloor(x float64) float64 +TEXT ·archFloor(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FIDBR $7, F0, F0 + FMOVD F0, ret+8(FP) + RET + +// func archCeil(x float64) float64 +TEXT ·archCeil(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FIDBR $6, F0, F0 + FMOVD F0, ret+8(FP) + RET + +// func archTrunc(x float64) float64 +TEXT ·archTrunc(SB),NOSPLIT,$0 + FMOVD x+0(FP), F0 + FIDBR $5, F0, F0 + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/floor_wasm.s b/go/src/math/floor_wasm.s new file mode 100644 index 0000000000000000000000000000000000000000..3751471574610c5c2c85793b7c8a01f77ef89ffc --- /dev/null +++ b/go/src/math/floor_wasm.s @@ -0,0 +1,26 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +TEXT ·archFloor(SB),NOSPLIT,$0 + Get SP + F64Load x+0(FP) + F64Floor + F64Store ret+8(FP) + RET + +TEXT ·archCeil(SB),NOSPLIT,$0 + Get SP + F64Load x+0(FP) + F64Ceil + F64Store ret+8(FP) + RET + +TEXT ·archTrunc(SB),NOSPLIT,$0 + Get SP + F64Load x+0(FP) + F64Trunc + F64Store ret+8(FP) + RET diff --git a/go/src/math/fma.go b/go/src/math/fma.go new file mode 100644 index 0000000000000000000000000000000000000000..c806b914dab5b60cced29e1e284db32177747a83 --- /dev/null +++ b/go/src/math/fma.go @@ -0,0 +1,182 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +import "math/bits" + +func zero(x uint64) uint64 { + if x == 0 { + return 1 + } + return 0 + // branchless: + // return ((x>>1 | x&1) - 1) >> 63 +} + +func nonzero(x uint64) uint64 { + if x != 0 { + return 1 + } + return 0 + // branchless: + // return 1 - ((x>>1|x&1)-1)>>63 +} + +func shl(u1, u2 uint64, n uint) (r1, r2 uint64) { + r1 = u1<>(64-n) | u2<<(n-64) + r2 = u2 << n + return +} + +func shr(u1, u2 uint64, n uint) (r1, r2 uint64) { + r2 = u2>>n | u1<<(64-n) | u1>>(n-64) + r1 = u1 >> n + return +} + +// shrcompress compresses the bottom n+1 bits of the two-word +// value into a single bit. the result is equal to the value +// shifted to the right by n, except the result's 0th bit is +// set to the bitwise OR of the bottom n+1 bits. +func shrcompress(u1, u2 uint64, n uint) (r1, r2 uint64) { + // TODO: Performance here is really sensitive to the + // order/placement of these branches. n == 0 is common + // enough to be in the fast path. Perhaps more measurement + // needs to be done to find the optimal order/placement? + switch { + case n == 0: + return u1, u2 + case n == 64: + return 0, u1 | nonzero(u2) + case n >= 128: + return 0, nonzero(u1 | u2) + case n < 64: + r1, r2 = shr(u1, u2, n) + r2 |= nonzero(u2 & (1<> 63) + exp = int32(b>>52) & mask + mantissa = b & fracMask + + if exp == 0 { + // Normalize value if subnormal. + shift := uint(bits.LeadingZeros64(mantissa) - 11) + mantissa <<= shift + exp = 1 - int32(shift) + } else { + // Add implicit 1 bit + mantissa |= 1 << 52 + } + return +} + +// FMA returns x * y + z, computed with only one rounding. +// (That is, FMA returns the fused multiply-add of x, y, and z.) +func FMA(x, y, z float64) float64 { + bx, by, bz := Float64bits(x), Float64bits(y), Float64bits(z) + + // Inf or NaN or zero involved. At most one rounding will occur. + if x == 0.0 || y == 0.0 || bx&uvinf == uvinf || by&uvinf == uvinf { + return x*y + z + } + // Handle z == 0.0 separately. + // Adding zero usually does not change the original value. + // However, there is an exception with negative zero. (e.g. (-0) + (+0) = (+0)) + // This applies when x * y is negative and underflows. + if z == 0.0 { + return x * y + } + // Handle non-finite z separately. Evaluating x*y+z where + // x and y are finite, but z is infinite, should always result in z. + if bz&uvinf == uvinf { + return z + } + + // Inputs are (sub)normal. + // Split x, y, z into sign, exponent, mantissa. + xs, xe, xm := split(bx) + ys, ye, ym := split(by) + zs, ze, zm := split(bz) + + // Compute product p = x*y as sign, exponent, two-word mantissa. + // Start with exponent. "is normal" bit isn't subtracted yet. + pe := xe + ye - bias + 1 + + // pm1:pm2 is the double-word mantissa for the product p. + // Shift left to leave top bit in product. Effectively + // shifts the 106-bit product to the left by 21. + pm1, pm2 := bits.Mul64(xm<<10, ym<<11) + zm1, zm2 := zm<<10, uint64(0) + ps := xs ^ ys // product sign + + // normalize to 62nd bit + is62zero := uint((^pm1 >> 62) & 1) + pm1, pm2 = shl(pm1, pm2, is62zero) + pe -= int32(is62zero) + + // Swap addition operands so |p| >= |z| + if pe < ze || pe == ze && pm1 < zm1 { + ps, pe, pm1, pm2, zs, ze, zm1, zm2 = zs, ze, zm1, zm2, ps, pe, pm1, pm2 + } + + // Special case: if p == -z the result is always +0 since neither operand is zero. + if ps != zs && pe == ze && pm1 == zm1 && pm2 == zm2 { + return 0 + } + + // Align significands + zm1, zm2 = shrcompress(zm1, zm2, uint(pe-ze)) + + // Compute resulting significands, normalizing if necessary. + var m, c uint64 + if ps == zs { + // Adding (pm1:pm2) + (zm1:zm2) + pm2, c = bits.Add64(pm2, zm2, 0) + pm1, _ = bits.Add64(pm1, zm1, c) + pe -= int32(^pm1 >> 63) + pm1, m = shrcompress(pm1, pm2, uint(64+pm1>>63)) + } else { + // Subtracting (pm1:pm2) - (zm1:zm2) + // TODO: should we special-case cancellation? + pm2, c = bits.Sub64(pm2, zm2, 0) + pm1, _ = bits.Sub64(pm1, zm1, c) + nz := lz(pm1, pm2) + pe -= nz + m, pm2 = shl(pm1, pm2, uint(nz-1)) + m |= nonzero(pm2) + } + + // Round and break ties to even + if pe > 1022+bias || pe == 1022+bias && (m+1<<9)>>63 == 1 { + // rounded value overflows exponent range + return Float64frombits(uint64(ps)<<63 | uvinf) + } + if pe < 0 { + n := uint(-pe) + m = m>>n | nonzero(m&(1<> 10) & ^zero((m&(1<<10-1))^1<<9) + pe &= -int32(nonzero(m)) + return Float64frombits(uint64(ps)<<63 + uint64(pe)<<52 + m) +} diff --git a/go/src/math/frexp.go b/go/src/math/frexp.go new file mode 100644 index 0000000000000000000000000000000000000000..e194947e646af437a251de11271f5635dbebcde7 --- /dev/null +++ b/go/src/math/frexp.go @@ -0,0 +1,39 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Frexp breaks f into a normalized fraction +// and an integral power of two. +// It returns frac and exp satisfying f == frac × 2**exp, +// with the absolute value of frac in the interval [½, 1). +// +// Special cases are: +// +// Frexp(±0) = ±0, 0 +// Frexp(±Inf) = ±Inf, 0 +// Frexp(NaN) = NaN, 0 +func Frexp(f float64) (frac float64, exp int) { + if haveArchFrexp { + return archFrexp(f) + } + return frexp(f) +} + +func frexp(f float64) (frac float64, exp int) { + // special cases + switch { + case f == 0: + return f, 0 // correctly return -0 + case IsInf(f, 0) || IsNaN(f): + return f, 0 + } + f, exp = normalize(f) + x := Float64bits(f) + exp += int((x>>shift)&mask) - bias + 1 + x &^= mask << shift + x |= (-1 + bias) << shift + frac = Float64frombits(x) + return +} diff --git a/go/src/math/gamma.go b/go/src/math/gamma.go new file mode 100644 index 0000000000000000000000000000000000000000..86c67232580154070c44634d7bdbc6021d66db7f --- /dev/null +++ b/go/src/math/gamma.go @@ -0,0 +1,222 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code, the long comment, and the constants +// below are from http://netlib.sandia.gov/cephes/cprob/gamma.c. +// The go code is a simplified version of the original C. +// +// tgamma.c +// +// Gamma function +// +// SYNOPSIS: +// +// double x, y, tgamma(); +// extern int signgam; +// +// y = tgamma( x ); +// +// DESCRIPTION: +// +// Returns gamma function of the argument. The result is +// correctly signed, and the sign (+1 or -1) is also +// returned in a global (extern) variable named signgam. +// This variable is also filled in by the logarithmic gamma +// function lgamma(). +// +// Arguments |x| <= 34 are reduced by recurrence and the function +// approximated by a rational function of degree 6/7 in the +// interval (2,3). Large arguments are handled by Stirling's +// formula. Large negative arguments are made positive using +// a reflection formula. +// +// ACCURACY: +// +// Relative error: +// arithmetic domain # trials peak rms +// DEC -34, 34 10000 1.3e-16 2.5e-17 +// IEEE -170,-33 20000 2.3e-15 3.3e-16 +// IEEE -33, 33 20000 9.4e-16 2.2e-16 +// IEEE 33, 171.6 20000 2.3e-15 3.2e-16 +// +// Error for arguments outside the test range will be larger +// owing to error amplification by the exponential function. +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov + +var _gamP = [...]float64{ + 1.60119522476751861407e-04, + 1.19135147006586384913e-03, + 1.04213797561761569935e-02, + 4.76367800457137231464e-02, + 2.07448227648435975150e-01, + 4.94214826801497100753e-01, + 9.99999999999999996796e-01, +} +var _gamQ = [...]float64{ + -2.31581873324120129819e-05, + 5.39605580493303397842e-04, + -4.45641913851797240494e-03, + 1.18139785222060435552e-02, + 3.58236398605498653373e-02, + -2.34591795718243348568e-01, + 7.14304917030273074085e-02, + 1.00000000000000000320e+00, +} +var _gamS = [...]float64{ + 7.87311395793093628397e-04, + -2.29549961613378126380e-04, + -2.68132617805781232825e-03, + 3.47222221605458667310e-03, + 8.33333333333482257126e-02, +} + +// Gamma function computed by Stirling's formula. +// The pair of results must be multiplied together to get the actual answer. +// The multiplication is left to the caller so that, if careful, the caller can avoid +// infinity for 172 <= x <= 180. +// The polynomial is valid for 33 <= x <= 172; larger values are only used +// in reciprocal and produce denormalized floats. The lower precision there +// masks any imprecision in the polynomial. +func stirling(x float64) (float64, float64) { + if x > 200 { + return Inf(1), 1 + } + const ( + SqrtTwoPi = 2.506628274631000502417 + MaxStirling = 143.01608 + ) + w := 1 / x + w = 1 + w*((((_gamS[0]*w+_gamS[1])*w+_gamS[2])*w+_gamS[3])*w+_gamS[4]) + y1 := Exp(x) + y2 := 1.0 + if x > MaxStirling { // avoid Pow() overflow + v := Pow(x, 0.5*x-0.25) + y1, y2 = v, v/y1 + } else { + y1 = Pow(x, x-0.5) / y1 + } + return y1, SqrtTwoPi * w * y2 +} + +// Gamma returns the Gamma function of x. +// +// Special cases are: +// +// Gamma(+Inf) = +Inf +// Gamma(+0) = +Inf +// Gamma(-0) = -Inf +// Gamma(x) = NaN for integer x < 0 +// Gamma(-Inf) = NaN +// Gamma(NaN) = NaN +func Gamma(x float64) float64 { + const Euler = 0.57721566490153286060651209008240243104215933593992 // A001620 + // special cases + switch { + case isNegInt(x) || IsInf(x, -1) || IsNaN(x): + return NaN() + case IsInf(x, 1): + return Inf(1) + case x == 0: + if Signbit(x) { + return Inf(-1) + } + return Inf(1) + } + q := Abs(x) + p := Floor(q) + if q > 33 { + if x >= 0 { + y1, y2 := stirling(x) + return y1 * y2 + } + // Note: x is negative but (checked above) not a negative integer, + // so x must be small enough to be in range for conversion to int64. + // If |x| were >= 2⁶³ it would have to be an integer. + signgam := 1 + if ip := int64(p); ip&1 == 0 { + signgam = -1 + } + z := q - p + if z > 0.5 { + p = p + 1 + z = q - p + } + z = q * Sin(Pi*z) + if z == 0 { + return Inf(signgam) + } + sq1, sq2 := stirling(q) + absz := Abs(z) + d := absz * sq1 * sq2 + if IsInf(d, 0) { + z = Pi / absz / sq1 / sq2 + } else { + z = Pi / d + } + return float64(signgam) * z + } + + // Reduce argument + z := 1.0 + for x >= 3 { + x = x - 1 + z = z * x + } + for x < 0 { + if x > -1e-09 { + goto small + } + z = z / x + x = x + 1 + } + for x < 2 { + if x < 1e-09 { + goto small + } + z = z / x + x = x + 1 + } + + if x == 2 { + return z + } + + x = x - 2 + p = (((((x*_gamP[0]+_gamP[1])*x+_gamP[2])*x+_gamP[3])*x+_gamP[4])*x+_gamP[5])*x + _gamP[6] + q = ((((((x*_gamQ[0]+_gamQ[1])*x+_gamQ[2])*x+_gamQ[3])*x+_gamQ[4])*x+_gamQ[5])*x+_gamQ[6])*x + _gamQ[7] + return z * p / q + +small: + if x == 0 { + return Inf(1) + } + return z / ((1 + Euler*x) * x) +} + +func isNegInt(x float64) bool { + if x < 0 { + _, xf := Modf(x) + return xf == 0 + } + return false +} diff --git a/go/src/math/huge_test.go b/go/src/math/huge_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2eadb7f89a8a8cbe3fd2ded3ccb1abc6624fa5db --- /dev/null +++ b/go/src/math/huge_test.go @@ -0,0 +1,126 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math_test + +import ( + . "math" + "testing" +) + +// Inputs to test trig_reduce +var trigHuge = []float64{ + 1 << 28, + 1 << 29, + 1 << 30, + 1 << 35, + 1 << 120, + 1 << 240, + 1 << 480, + 1234567891234567 << 180, + 1234567891234567 << 300, + MaxFloat64, +} + +// Results for trigHuge[i] calculated with https://github.com/robpike/ivy +// using 4096 bits of working precision. Values requiring less than +// 102 decimal digits (1 << 120, 1 << 240, 1 << 480, 1234567891234567 << 180) +// were confirmed via https://keisan.casio.com/ +var cosHuge = []float64{ + -0.16556897949057876, + -0.94517382606089662, + 0.78670712294118812, + -0.76466301249635305, + -0.92587902285483787, + 0.93601042593353793, + -0.28282777640193788, + -0.14616431394103619, + -0.79456058210671406, + -0.99998768942655994, +} + +var sinHuge = []float64{ + -0.98619821183697566, + 0.32656766301856334, + -0.61732641504604217, + -0.64443035102329113, + 0.37782010936075202, + -0.35197227524865778, + 0.95917070894368716, + 0.98926032637023618, + -0.60718488235646949, + 0.00496195478918406, +} + +var tanHuge = []float64{ + 5.95641897939639421, + -0.34551069233430392, + -0.78469661331920043, + 0.84276385870875983, + -0.40806638884180424, + -0.37603456702698076, + -3.39135965054779932, + -6.76813854009065030, + 0.76417695016604922, + -0.00496201587444489, +} + +// Check that trig values of huge angles return accurate results. +// This confirms that argument reduction works for very large values +// up to MaxFloat64. +func TestHugeCos(t *testing.T) { + for i := 0; i < len(trigHuge); i++ { + f1 := cosHuge[i] + f2 := Cos(trigHuge[i]) + if !close(f1, f2) { + t.Errorf("Cos(%g) = %g, want %g", trigHuge[i], f2, f1) + } + f3 := Cos(-trigHuge[i]) + if !close(f1, f3) { + t.Errorf("Cos(%g) = %g, want %g", -trigHuge[i], f3, f1) + } + } +} + +func TestHugeSin(t *testing.T) { + for i := 0; i < len(trigHuge); i++ { + f1 := sinHuge[i] + f2 := Sin(trigHuge[i]) + if !close(f1, f2) { + t.Errorf("Sin(%g) = %g, want %g", trigHuge[i], f2, f1) + } + f3 := Sin(-trigHuge[i]) + if !close(-f1, f3) { + t.Errorf("Sin(%g) = %g, want %g", -trigHuge[i], f3, -f1) + } + } +} + +func TestHugeSinCos(t *testing.T) { + for i := 0; i < len(trigHuge); i++ { + f1, g1 := sinHuge[i], cosHuge[i] + f2, g2 := Sincos(trigHuge[i]) + if !close(f1, f2) || !close(g1, g2) { + t.Errorf("Sincos(%g) = %g, %g, want %g, %g", trigHuge[i], f2, g2, f1, g1) + } + f3, g3 := Sincos(-trigHuge[i]) + if !close(-f1, f3) || !close(g1, g3) { + t.Errorf("Sincos(%g) = %g, %g, want %g, %g", -trigHuge[i], f3, g3, -f1, g1) + } + } +} + +func TestHugeTan(t *testing.T) { + for i := 0; i < len(trigHuge); i++ { + f1 := tanHuge[i] + f2 := Tan(trigHuge[i]) + if !close(f1, f2) { + t.Errorf("Tan(%g) = %g, want %g", trigHuge[i], f2, f1) + } + f3 := Tan(-trigHuge[i]) + if !close(-f1, f3) { + t.Errorf("Tan(%g) = %g, want %g", -trigHuge[i], f3, -f1) + } + } +} diff --git a/go/src/math/hypot.go b/go/src/math/hypot.go new file mode 100644 index 0000000000000000000000000000000000000000..03c3602acfe2851ff068ab08ec247116dab0e756 --- /dev/null +++ b/go/src/math/hypot.go @@ -0,0 +1,44 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Hypot -- sqrt(p*p + q*q), but overflows only if the result does. +*/ + +// Hypot returns [Sqrt](p*p + q*q), taking care to avoid +// unnecessary overflow and underflow. +// +// Special cases are: +// +// Hypot(±Inf, q) = +Inf +// Hypot(p, ±Inf) = +Inf +// Hypot(NaN, q) = NaN +// Hypot(p, NaN) = NaN +func Hypot(p, q float64) float64 { + if haveArchHypot { + return archHypot(p, q) + } + return hypot(p, q) +} + +func hypot(p, q float64) float64 { + p, q = Abs(p), Abs(q) + // special cases + switch { + case IsInf(p, 1) || IsInf(q, 1): + return Inf(1) + case IsNaN(p) || IsNaN(q): + return NaN() + } + if p < q { + p, q = q, p + } + if p == 0 { + return 0 + } + q = q / p + return p * Sqrt(1+q*q) +} diff --git a/go/src/math/hypot_386.s b/go/src/math/hypot_386.s new file mode 100644 index 0000000000000000000000000000000000000000..80a8fd3fd02a01ae4b15337e0f6e89ae9b730545 --- /dev/null +++ b/go/src/math/hypot_386.s @@ -0,0 +1,59 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func archHypot(p, q float64) float64 +TEXT ·archHypot(SB),NOSPLIT,$0 +// test bits for not-finite + MOVL p_hi+4(FP), AX // high word p + ANDL $0x7ff00000, AX + CMPL AX, $0x7ff00000 + JEQ not_finite + MOVL q_hi+12(FP), AX // high word q + ANDL $0x7ff00000, AX + CMPL AX, $0x7ff00000 + JEQ not_finite + FMOVD p+0(FP), F0 // F0=p + FABS // F0=|p| + FMOVD q+8(FP), F0 // F0=q, F1=|p| + FABS // F0=|q|, F1=|p| + FUCOMI F0, F1 // compare F0 to F1 + JCC 2(PC) // jump if F0 >= F1 + FXCHD F0, F1 // F0=|p| (larger), F1=|q| (smaller) + FTST // compare F0 to 0 + FSTSW AX + ANDW $0x4000, AX + JNE 10(PC) // jump if F0 = 0 + FXCHD F0, F1 // F0=q (smaller), F1=p (larger) + FDIVD F1, F0 // F0=q(=q/p), F1=p + FMULD F0, F0 // F0=q*q, F1=p + FLD1 // F0=1, F1=q*q, F2=p + FADDDP F0, F1 // F0=1+q*q, F1=p + FSQRT // F0=sqrt(1+q*q), F1=p + FMULDP F0, F1 // F0=p*sqrt(1+q*q) + FMOVDP F0, ret+16(FP) + RET + FMOVDP F0, F1 // F0=0 + FMOVDP F0, ret+16(FP) + RET +not_finite: +// test bits for -Inf or +Inf + MOVL p_hi+4(FP), AX // high word p + ORL p_lo+0(FP), AX // low word p + ANDL $0x7fffffff, AX + CMPL AX, $0x7ff00000 + JEQ is_inf + MOVL q_hi+12(FP), AX // high word q + ORL q_lo+8(FP), AX // low word q + ANDL $0x7fffffff, AX + CMPL AX, $0x7ff00000 + JEQ is_inf + MOVL $0x7ff80000, ret_hi+20(FP) // return NaN = 0x7FF8000000000001 + MOVL $0x00000001, ret_lo+16(FP) + RET +is_inf: + MOVL AX, ret_hi+20(FP) // return +Inf = 0x7FF0000000000000 + MOVL $0x00000000, ret_lo+16(FP) + RET diff --git a/go/src/math/hypot_amd64.s b/go/src/math/hypot_amd64.s new file mode 100644 index 0000000000000000000000000000000000000000..fe326c928173f51cdacdff63c55c534645b995f9 --- /dev/null +++ b/go/src/math/hypot_amd64.s @@ -0,0 +1,52 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define PosInf 0x7FF0000000000000 +#define NaN 0x7FF8000000000001 + +// func archHypot(p, q float64) float64 +TEXT ·archHypot(SB),NOSPLIT,$0 + // test bits for special cases + MOVQ p+0(FP), BX + MOVQ $~(1<<63), AX + ANDQ AX, BX // p = |p| + MOVQ q+8(FP), CX + ANDQ AX, CX // q = |q| + MOVQ $PosInf, AX + CMPQ AX, BX + JLE isInfOrNaN + CMPQ AX, CX + JLE isInfOrNaN + // hypot = max * sqrt(1 + (min/max)**2) + MOVQ BX, X0 + MOVQ CX, X1 + ORQ CX, BX + JEQ isZero + MOVAPD X0, X2 + MAXSD X1, X0 + MINSD X2, X1 + DIVSD X0, X1 + MULSD X1, X1 + ADDSD $1.0, X1 + SQRTSD X1, X1 + MULSD X1, X0 + MOVSD X0, ret+16(FP) + RET +isInfOrNaN: + CMPQ AX, BX + JEQ isInf + CMPQ AX, CX + JEQ isInf + MOVQ $NaN, AX + MOVQ AX, ret+16(FP) // return NaN + RET +isInf: + MOVQ AX, ret+16(FP) // return +Inf + RET +isZero: + MOVQ $0, AX + MOVQ AX, ret+16(FP) // return 0 + RET diff --git a/go/src/math/hypot_asm.go b/go/src/math/hypot_asm.go new file mode 100644 index 0000000000000000000000000000000000000000..852691037f6f4bc4a8e848d17bebc682181073eb --- /dev/null +++ b/go/src/math/hypot_asm.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build 386 || amd64 + +package math + +const haveArchHypot = true + +func archHypot(p, q float64) float64 diff --git a/go/src/math/hypot_noasm.go b/go/src/math/hypot_noasm.go new file mode 100644 index 0000000000000000000000000000000000000000..8b64812a1c197e048839bf23858ff4bafbd3aaa7 --- /dev/null +++ b/go/src/math/hypot_noasm.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !386 && !amd64 + +package math + +const haveArchHypot = false + +func archHypot(p, q float64) float64 { + panic("not implemented") +} diff --git a/go/src/math/j0.go b/go/src/math/j0.go new file mode 100644 index 0000000000000000000000000000000000000000..a311e18d62d4d3c60127159719bb0df1187745a6 --- /dev/null +++ b/go/src/math/j0.go @@ -0,0 +1,429 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Bessel function of the first and second kinds of order zero. +*/ + +// The original C code and the long comment below are +// from FreeBSD's /usr/src/lib/msun/src/e_j0.c and +// came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_j0(x), __ieee754_y0(x) +// Bessel function of the first and second kinds of order zero. +// Method -- j0(x): +// 1. For tiny x, we use j0(x) = 1 - x**2/4 + x**4/64 - ... +// 2. Reduce x to |x| since j0(x)=j0(-x), and +// for x in (0,2) +// j0(x) = 1-z/4+ z**2*R0/S0, where z = x*x; +// (precision: |j0-1+z/4-z**2R0/S0 |<2**-63.67 ) +// for x in (2,inf) +// j0(x) = sqrt(2/(pi*x))*(p0(x)*cos(x0)-q0(x)*sin(x0)) +// where x0 = x-pi/4. It is better to compute sin(x0),cos(x0) +// as follow: +// cos(x0) = cos(x)cos(pi/4)+sin(x)sin(pi/4) +// = 1/sqrt(2) * (cos(x) + sin(x)) +// sin(x0) = sin(x)cos(pi/4)-cos(x)sin(pi/4) +// = 1/sqrt(2) * (sin(x) - cos(x)) +// (To avoid cancellation, use +// sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) +// to compute the worse one.) +// +// 3 Special cases +// j0(nan)= nan +// j0(0) = 1 +// j0(inf) = 0 +// +// Method -- y0(x): +// 1. For x<2. +// Since +// y0(x) = 2/pi*(j0(x)*(ln(x/2)+Euler) + x**2/4 - ...) +// therefore y0(x)-2/pi*j0(x)*ln(x) is an even function. +// We use the following function to approximate y0, +// y0(x) = U(z)/V(z) + (2/pi)*(j0(x)*ln(x)), z= x**2 +// where +// U(z) = u00 + u01*z + ... + u06*z**6 +// V(z) = 1 + v01*z + ... + v04*z**4 +// with absolute approximation error bounded by 2**-72. +// Note: For tiny x, U/V = u0 and j0(x)~1, hence +// y0(tiny) = u0 + (2/pi)*ln(tiny), (choose tiny<2**-27) +// 2. For x>=2. +// y0(x) = sqrt(2/(pi*x))*(p0(x)*cos(x0)+q0(x)*sin(x0)) +// where x0 = x-pi/4. It is better to compute sin(x0),cos(x0) +// by the method mentioned above. +// 3. Special cases: y0(0)=-inf, y0(x<0)=NaN, y0(inf)=0. +// + +// J0 returns the order-zero Bessel function of the first kind. +// +// Special cases are: +// +// J0(±Inf) = 0 +// J0(0) = 1 +// J0(NaN) = NaN +func J0(x float64) float64 { + const ( + Huge = 1e300 + TwoM27 = 1.0 / (1 << 27) // 2**-27 0x3e40000000000000 + TwoM13 = 1.0 / (1 << 13) // 2**-13 0x3f20000000000000 + Two129 = 1 << 129 // 2**129 0x4800000000000000 + // R0/S0 on [0, 2] + R02 = 1.56249999999999947958e-02 // 0x3F8FFFFFFFFFFFFD + R03 = -1.89979294238854721751e-04 // 0xBF28E6A5B61AC6E9 + R04 = 1.82954049532700665670e-06 // 0x3EBEB1D10C503919 + R05 = -4.61832688532103189199e-09 // 0xBE33D5E773D63FCE + S01 = 1.56191029464890010492e-02 // 0x3F8FFCE882C8C2A4 + S02 = 1.16926784663337450260e-04 // 0x3F1EA6D2DD57DBF4 + S03 = 5.13546550207318111446e-07 // 0x3EA13B54CE84D5A9 + S04 = 1.16614003333790000205e-09 // 0x3E1408BCF4745D8F + ) + // special cases + switch { + case IsNaN(x): + return x + case IsInf(x, 0): + return 0 + case x == 0: + return 1 + } + + x = Abs(x) + if x >= 2 { + s, c := Sincos(x) + ss := s - c + cc := s + c + + // make sure x+x does not overflow + if x < MaxFloat64/2 { + z := -Cos(x + x) + if s*c < 0 { + cc = z / ss + } else { + ss = z / cc + } + } + + // j0(x) = 1/sqrt(pi) * (P(0,x)*cc - Q(0,x)*ss) / sqrt(x) + // y0(x) = 1/sqrt(pi) * (P(0,x)*ss + Q(0,x)*cc) / sqrt(x) + + var z float64 + if x > Two129 { // |x| > ~6.8056e+38 + z = (1 / SqrtPi) * cc / Sqrt(x) + } else { + u := pzero(x) + v := qzero(x) + z = (1 / SqrtPi) * (u*cc - v*ss) / Sqrt(x) + } + return z // |x| >= 2.0 + } + if x < TwoM13 { // |x| < ~1.2207e-4 + if x < TwoM27 { + return 1 // |x| < ~7.4506e-9 + } + return 1 - 0.25*x*x // ~7.4506e-9 < |x| < ~1.2207e-4 + } + z := x * x + r := z * (R02 + z*(R03+z*(R04+z*R05))) + s := 1 + z*(S01+z*(S02+z*(S03+z*S04))) + if x < 1 { + return 1 + z*(-0.25+(r/s)) // |x| < 1.00 + } + u := 0.5 * x + return (1+u)*(1-u) + z*(r/s) // 1.0 < |x| < 2.0 +} + +// Y0 returns the order-zero Bessel function of the second kind. +// +// Special cases are: +// +// Y0(+Inf) = 0 +// Y0(0) = -Inf +// Y0(x < 0) = NaN +// Y0(NaN) = NaN +func Y0(x float64) float64 { + const ( + TwoM27 = 1.0 / (1 << 27) // 2**-27 0x3e40000000000000 + Two129 = 1 << 129 // 2**129 0x4800000000000000 + U00 = -7.38042951086872317523e-02 // 0xBFB2E4D699CBD01F + U01 = 1.76666452509181115538e-01 // 0x3FC69D019DE9E3FC + U02 = -1.38185671945596898896e-02 // 0xBF8C4CE8B16CFA97 + U03 = 3.47453432093683650238e-04 // 0x3F36C54D20B29B6B + U04 = -3.81407053724364161125e-06 // 0xBECFFEA773D25CAD + U05 = 1.95590137035022920206e-08 // 0x3E5500573B4EABD4 + U06 = -3.98205194132103398453e-11 // 0xBDC5E43D693FB3C8 + V01 = 1.27304834834123699328e-02 // 0x3F8A127091C9C71A + V02 = 7.60068627350353253702e-05 // 0x3F13ECBBF578C6C1 + V03 = 2.59150851840457805467e-07 // 0x3E91642D7FF202FD + V04 = 4.41110311332675467403e-10 // 0x3DFE50183BD6D9EF + ) + // special cases + switch { + case x < 0 || IsNaN(x): + return NaN() + case IsInf(x, 1): + return 0 + case x == 0: + return Inf(-1) + } + + if x >= 2 { // |x| >= 2.0 + + // y0(x) = sqrt(2/(pi*x))*(p0(x)*sin(x0)+q0(x)*cos(x0)) + // where x0 = x-pi/4 + // Better formula: + // cos(x0) = cos(x)cos(pi/4)+sin(x)sin(pi/4) + // = 1/sqrt(2) * (sin(x) + cos(x)) + // sin(x0) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) + // = 1/sqrt(2) * (sin(x) - cos(x)) + // To avoid cancellation, use + // sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) + // to compute the worse one. + + s, c := Sincos(x) + ss := s - c + cc := s + c + + // j0(x) = 1/sqrt(pi) * (P(0,x)*cc - Q(0,x)*ss) / sqrt(x) + // y0(x) = 1/sqrt(pi) * (P(0,x)*ss + Q(0,x)*cc) / sqrt(x) + + // make sure x+x does not overflow + if x < MaxFloat64/2 { + z := -Cos(x + x) + if s*c < 0 { + cc = z / ss + } else { + ss = z / cc + } + } + var z float64 + if x > Two129 { // |x| > ~6.8056e+38 + z = (1 / SqrtPi) * ss / Sqrt(x) + } else { + u := pzero(x) + v := qzero(x) + z = (1 / SqrtPi) * (u*ss + v*cc) / Sqrt(x) + } + return z // |x| >= 2.0 + } + if x <= TwoM27 { + return U00 + (2/Pi)*Log(x) // |x| < ~7.4506e-9 + } + z := x * x + u := U00 + z*(U01+z*(U02+z*(U03+z*(U04+z*(U05+z*U06))))) + v := 1 + z*(V01+z*(V02+z*(V03+z*V04))) + return u/v + (2/Pi)*J0(x)*Log(x) // ~7.4506e-9 < |x| < 2.0 +} + +// The asymptotic expansions of pzero is +// 1 - 9/128 s**2 + 11025/98304 s**4 - ..., where s = 1/x. +// For x >= 2, We approximate pzero by +// pzero(x) = 1 + (R/S) +// where R = pR0 + pR1*s**2 + pR2*s**4 + ... + pR5*s**10 +// S = 1 + pS0*s**2 + ... + pS4*s**10 +// and +// | pzero(x)-1-R/S | <= 2 ** ( -60.26) + +// for x in [inf, 8]=1/[0,0.125] +var p0R8 = [6]float64{ + 0.00000000000000000000e+00, // 0x0000000000000000 + -7.03124999999900357484e-02, // 0xBFB1FFFFFFFFFD32 + -8.08167041275349795626e+00, // 0xC02029D0B44FA779 + -2.57063105679704847262e+02, // 0xC07011027B19E863 + -2.48521641009428822144e+03, // 0xC0A36A6ECD4DCAFC + -5.25304380490729545272e+03, // 0xC0B4850B36CC643D +} +var p0S8 = [5]float64{ + 1.16534364619668181717e+02, // 0x405D223307A96751 + 3.83374475364121826715e+03, // 0x40ADF37D50596938 + 4.05978572648472545552e+04, // 0x40E3D2BB6EB6B05F + 1.16752972564375915681e+05, // 0x40FC810F8F9FA9BD + 4.76277284146730962675e+04, // 0x40E741774F2C49DC +} + +// for x in [8,4.5454]=1/[0.125,0.22001] +var p0R5 = [6]float64{ + -1.14125464691894502584e-11, // 0xBDA918B147E495CC + -7.03124940873599280078e-02, // 0xBFB1FFFFE69AFBC6 + -4.15961064470587782438e+00, // 0xC010A370F90C6BBF + -6.76747652265167261021e+01, // 0xC050EB2F5A7D1783 + -3.31231299649172967747e+02, // 0xC074B3B36742CC63 + -3.46433388365604912451e+02, // 0xC075A6EF28A38BD7 +} +var p0S5 = [5]float64{ + 6.07539382692300335975e+01, // 0x404E60810C98C5DE + 1.05125230595704579173e+03, // 0x40906D025C7E2864 + 5.97897094333855784498e+03, // 0x40B75AF88FBE1D60 + 9.62544514357774460223e+03, // 0x40C2CCB8FA76FA38 + 2.40605815922939109441e+03, // 0x40A2CC1DC70BE864 +} + +// for x in [4.547,2.8571]=1/[0.2199,0.35001] +var p0R3 = [6]float64{ + -2.54704601771951915620e-09, // 0xBE25E1036FE1AA86 + -7.03119616381481654654e-02, // 0xBFB1FFF6F7C0E24B + -2.40903221549529611423e+00, // 0xC00345B2AEA48074 + -2.19659774734883086467e+01, // 0xC035F74A4CB94E14 + -5.80791704701737572236e+01, // 0xC04D0A22420A1A45 + -3.14479470594888503854e+01, // 0xC03F72ACA892D80F +} +var p0S3 = [5]float64{ + 3.58560338055209726349e+01, // 0x4041ED9284077DD3 + 3.61513983050303863820e+02, // 0x40769839464A7C0E + 1.19360783792111533330e+03, // 0x4092A66E6D1061D6 + 1.12799679856907414432e+03, // 0x40919FFCB8C39B7E + 1.73580930813335754692e+02, // 0x4065B296FC379081 +} + +// for x in [2.8570,2]=1/[0.3499,0.5] +var p0R2 = [6]float64{ + -8.87534333032526411254e-08, // 0xBE77D316E927026D + -7.03030995483624743247e-02, // 0xBFB1FF62495E1E42 + -1.45073846780952986357e+00, // 0xBFF736398A24A843 + -7.63569613823527770791e+00, // 0xC01E8AF3EDAFA7F3 + -1.11931668860356747786e+01, // 0xC02662E6C5246303 + -3.23364579351335335033e+00, // 0xC009DE81AF8FE70F +} +var p0S2 = [5]float64{ + 2.22202997532088808441e+01, // 0x40363865908B5959 + 1.36206794218215208048e+02, // 0x4061069E0EE8878F + 2.70470278658083486789e+02, // 0x4070E78642EA079B + 1.53875394208320329881e+02, // 0x40633C033AB6FAFF + 1.46576176948256193810e+01, // 0x402D50B344391809 +} + +func pzero(x float64) float64 { + var p *[6]float64 + var q *[5]float64 + if x >= 8 { + p = &p0R8 + q = &p0S8 + } else if x >= 4.5454 { + p = &p0R5 + q = &p0S5 + } else if x >= 2.8571 { + p = &p0R3 + q = &p0S3 + } else if x >= 2 { + p = &p0R2 + q = &p0S2 + } + z := 1 / (x * x) + r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5])))) + s := 1 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*q[4])))) + return 1 + r/s +} + +// For x >= 8, the asymptotic expansions of qzero is +// -1/8 s + 75/1024 s**3 - ..., where s = 1/x. +// We approximate pzero by +// qzero(x) = s*(-1.25 + (R/S)) +// where R = qR0 + qR1*s**2 + qR2*s**4 + ... + qR5*s**10 +// S = 1 + qS0*s**2 + ... + qS5*s**12 +// and +// | qzero(x)/s +1.25-R/S | <= 2**(-61.22) + +// for x in [inf, 8]=1/[0,0.125] +var q0R8 = [6]float64{ + 0.00000000000000000000e+00, // 0x0000000000000000 + 7.32421874999935051953e-02, // 0x3FB2BFFFFFFFFE2C + 1.17682064682252693899e+01, // 0x402789525BB334D6 + 5.57673380256401856059e+02, // 0x40816D6315301825 + 8.85919720756468632317e+03, // 0x40C14D993E18F46D + 3.70146267776887834771e+04, // 0x40E212D40E901566 +} +var q0S8 = [6]float64{ + 1.63776026895689824414e+02, // 0x406478D5365B39BC + 8.09834494656449805916e+03, // 0x40BFA2584E6B0563 + 1.42538291419120476348e+05, // 0x4101665254D38C3F + 8.03309257119514397345e+05, // 0x412883DA83A52B43 + 8.40501579819060512818e+05, // 0x4129A66B28DE0B3D + -3.43899293537866615225e+05, // 0xC114FD6D2C9530C5 +} + +// for x in [8,4.5454]=1/[0.125,0.22001] +var q0R5 = [6]float64{ + 1.84085963594515531381e-11, // 0x3DB43D8F29CC8CD9 + 7.32421766612684765896e-02, // 0x3FB2BFFFD172B04C + 5.83563508962056953777e+00, // 0x401757B0B9953DD3 + 1.35111577286449829671e+02, // 0x4060E3920A8788E9 + 1.02724376596164097464e+03, // 0x40900CF99DC8C481 + 1.98997785864605384631e+03, // 0x409F17E953C6E3A6 +} +var q0S5 = [6]float64{ + 8.27766102236537761883e+01, // 0x4054B1B3FB5E1543 + 2.07781416421392987104e+03, // 0x40A03BA0DA21C0CE + 1.88472887785718085070e+04, // 0x40D267D27B591E6D + 5.67511122894947329769e+04, // 0x40EBB5E397E02372 + 3.59767538425114471465e+04, // 0x40E191181F7A54A0 + -5.35434275601944773371e+03, // 0xC0B4EA57BEDBC609 +} + +// for x in [4.547,2.8571]=1/[0.2199,0.35001] +var q0R3 = [6]float64{ + 4.37741014089738620906e-09, // 0x3E32CD036ADECB82 + 7.32411180042911447163e-02, // 0x3FB2BFEE0E8D0842 + 3.34423137516170720929e+00, // 0x400AC0FC61149CF5 + 4.26218440745412650017e+01, // 0x40454F98962DAEDD + 1.70808091340565596283e+02, // 0x406559DBE25EFD1F + 1.66733948696651168575e+02, // 0x4064D77C81FA21E0 +} +var q0S3 = [6]float64{ + 4.87588729724587182091e+01, // 0x40486122BFE343A6 + 7.09689221056606015736e+02, // 0x40862D8386544EB3 + 3.70414822620111362994e+03, // 0x40ACF04BE44DFC63 + 6.46042516752568917582e+03, // 0x40B93C6CD7C76A28 + 2.51633368920368957333e+03, // 0x40A3A8AAD94FB1C0 + -1.49247451836156386662e+02, // 0xC062A7EB201CF40F +} + +// for x in [2.8570,2]=1/[0.3499,0.5] +var q0R2 = [6]float64{ + 1.50444444886983272379e-07, // 0x3E84313B54F76BDB + 7.32234265963079278272e-02, // 0x3FB2BEC53E883E34 + 1.99819174093815998816e+00, // 0x3FFFF897E727779C + 1.44956029347885735348e+01, // 0x402CFDBFAAF96FE5 + 3.16662317504781540833e+01, // 0x403FAA8E29FBDC4A + 1.62527075710929267416e+01, // 0x403040B171814BB4 +} +var q0S2 = [6]float64{ + 3.03655848355219184498e+01, // 0x403E5D96F7C07AED + 2.69348118608049844624e+02, // 0x4070D591E4D14B40 + 8.44783757595320139444e+02, // 0x408A664522B3BF22 + 8.82935845112488550512e+02, // 0x408B977C9C5CC214 + 2.12666388511798828631e+02, // 0x406A95530E001365 + -5.31095493882666946917e+00, // 0xC0153E6AF8B32931 +} + +func qzero(x float64) float64 { + var p, q *[6]float64 + if x >= 8 { + p = &q0R8 + q = &q0S8 + } else if x >= 4.5454 { + p = &q0R5 + q = &q0S5 + } else if x >= 2.8571 { + p = &q0R3 + q = &q0S3 + } else if x >= 2 { + p = &q0R2 + q = &q0S2 + } + z := 1 / (x * x) + r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5])))) + s := 1 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*(q[4]+z*q[5]))))) + return (-0.125 + r/s) / x +} diff --git a/go/src/math/j1.go b/go/src/math/j1.go new file mode 100644 index 0000000000000000000000000000000000000000..cc19e75b95002a6ce3de86d17bb1e73639de8d9b --- /dev/null +++ b/go/src/math/j1.go @@ -0,0 +1,424 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Bessel function of the first and second kinds of order one. +*/ + +// The original C code and the long comment below are +// from FreeBSD's /usr/src/lib/msun/src/e_j1.c and +// came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_j1(x), __ieee754_y1(x) +// Bessel function of the first and second kinds of order one. +// Method -- j1(x): +// 1. For tiny x, we use j1(x) = x/2 - x**3/16 + x**5/384 - ... +// 2. Reduce x to |x| since j1(x)=-j1(-x), and +// for x in (0,2) +// j1(x) = x/2 + x*z*R0/S0, where z = x*x; +// (precision: |j1/x - 1/2 - R0/S0 |<2**-61.51 ) +// for x in (2,inf) +// j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1)) +// y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x1)+q1(x)*cos(x1)) +// where x1 = x-3*pi/4. It is better to compute sin(x1),cos(x1) +// as follow: +// cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) +// = 1/sqrt(2) * (sin(x) - cos(x)) +// sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) +// = -1/sqrt(2) * (sin(x) + cos(x)) +// (To avoid cancellation, use +// sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) +// to compute the worse one.) +// +// 3 Special cases +// j1(nan)= nan +// j1(0) = 0 +// j1(inf) = 0 +// +// Method -- y1(x): +// 1. screen out x<=0 cases: y1(0)=-inf, y1(x<0)=NaN +// 2. For x<2. +// Since +// y1(x) = 2/pi*(j1(x)*(ln(x/2)+Euler)-1/x-x/2+5/64*x**3-...) +// therefore y1(x)-2/pi*j1(x)*ln(x)-1/x is an odd function. +// We use the following function to approximate y1, +// y1(x) = x*U(z)/V(z) + (2/pi)*(j1(x)*ln(x)-1/x), z= x**2 +// where for x in [0,2] (abs err less than 2**-65.89) +// U(z) = U0[0] + U0[1]*z + ... + U0[4]*z**4 +// V(z) = 1 + v0[0]*z + ... + v0[4]*z**5 +// Note: For tiny x, 1/x dominate y1 and hence +// y1(tiny) = -2/pi/tiny, (choose tiny<2**-54) +// 3. For x>=2. +// y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x1)+q1(x)*cos(x1)) +// where x1 = x-3*pi/4. It is better to compute sin(x1),cos(x1) +// by method mentioned above. + +// J1 returns the order-one Bessel function of the first kind. +// +// Special cases are: +// +// J1(±Inf) = 0 +// J1(NaN) = NaN +func J1(x float64) float64 { + const ( + TwoM27 = 1.0 / (1 << 27) // 2**-27 0x3e40000000000000 + Two129 = 1 << 129 // 2**129 0x4800000000000000 + // R0/S0 on [0, 2] + R00 = -6.25000000000000000000e-02 // 0xBFB0000000000000 + R01 = 1.40705666955189706048e-03 // 0x3F570D9F98472C61 + R02 = -1.59955631084035597520e-05 // 0xBEF0C5C6BA169668 + R03 = 4.96727999609584448412e-08 // 0x3E6AAAFA46CA0BD9 + S01 = 1.91537599538363460805e-02 // 0x3F939D0B12637E53 + S02 = 1.85946785588630915560e-04 // 0x3F285F56B9CDF664 + S03 = 1.17718464042623683263e-06 // 0x3EB3BFF8333F8498 + S04 = 5.04636257076217042715e-09 // 0x3E35AC88C97DFF2C + S05 = 1.23542274426137913908e-11 // 0x3DAB2ACFCFB97ED8 + ) + // special cases + switch { + case IsNaN(x): + return x + case IsInf(x, 0) || x == 0: + return 0 + } + + sign := false + if x < 0 { + x = -x + sign = true + } + if x >= 2 { + s, c := Sincos(x) + ss := -s - c + cc := s - c + + // make sure x+x does not overflow + if x < MaxFloat64/2 { + z := Cos(x + x) + if s*c > 0 { + cc = z / ss + } else { + ss = z / cc + } + } + + // j1(x) = 1/sqrt(pi) * (P(1,x)*cc - Q(1,x)*ss) / sqrt(x) + // y1(x) = 1/sqrt(pi) * (P(1,x)*ss + Q(1,x)*cc) / sqrt(x) + + var z float64 + if x > Two129 { + z = (1 / SqrtPi) * cc / Sqrt(x) + } else { + u := pone(x) + v := qone(x) + z = (1 / SqrtPi) * (u*cc - v*ss) / Sqrt(x) + } + if sign { + return -z + } + return z + } + if x < TwoM27 { // |x|<2**-27 + return 0.5 * x // inexact if x!=0 necessary + } + z := x * x + r := z * (R00 + z*(R01+z*(R02+z*R03))) + s := 1.0 + z*(S01+z*(S02+z*(S03+z*(S04+z*S05)))) + r *= x + z = 0.5*x + r/s + if sign { + return -z + } + return z +} + +// Y1 returns the order-one Bessel function of the second kind. +// +// Special cases are: +// +// Y1(+Inf) = 0 +// Y1(0) = -Inf +// Y1(x < 0) = NaN +// Y1(NaN) = NaN +func Y1(x float64) float64 { + const ( + TwoM54 = 1.0 / (1 << 54) // 2**-54 0x3c90000000000000 + Two129 = 1 << 129 // 2**129 0x4800000000000000 + U00 = -1.96057090646238940668e-01 // 0xBFC91866143CBC8A + U01 = 5.04438716639811282616e-02 // 0x3FA9D3C776292CD1 + U02 = -1.91256895875763547298e-03 // 0xBF5F55E54844F50F + U03 = 2.35252600561610495928e-05 // 0x3EF8AB038FA6B88E + U04 = -9.19099158039878874504e-08 // 0xBE78AC00569105B8 + V00 = 1.99167318236649903973e-02 // 0x3F94650D3F4DA9F0 + V01 = 2.02552581025135171496e-04 // 0x3F2A8C896C257764 + V02 = 1.35608801097516229404e-06 // 0x3EB6C05A894E8CA6 + V03 = 6.22741452364621501295e-09 // 0x3E3ABF1D5BA69A86 + V04 = 1.66559246207992079114e-11 // 0x3DB25039DACA772A + ) + // special cases + switch { + case x < 0 || IsNaN(x): + return NaN() + case IsInf(x, 1): + return 0 + case x == 0: + return Inf(-1) + } + + if x >= 2 { + s, c := Sincos(x) + ss := -s - c + cc := s - c + + // make sure x+x does not overflow + if x < MaxFloat64/2 { + z := Cos(x + x) + if s*c > 0 { + cc = z / ss + } else { + ss = z / cc + } + } + // y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x0)+q1(x)*cos(x0)) + // where x0 = x-3pi/4 + // Better formula: + // cos(x0) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) + // = 1/sqrt(2) * (sin(x) - cos(x)) + // sin(x0) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) + // = -1/sqrt(2) * (cos(x) + sin(x)) + // To avoid cancellation, use + // sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) + // to compute the worse one. + + var z float64 + if x > Two129 { + z = (1 / SqrtPi) * ss / Sqrt(x) + } else { + u := pone(x) + v := qone(x) + z = (1 / SqrtPi) * (u*ss + v*cc) / Sqrt(x) + } + return z + } + if x <= TwoM54 { // x < 2**-54 + return -(2 / Pi) / x + } + z := x * x + u := U00 + z*(U01+z*(U02+z*(U03+z*U04))) + v := 1 + z*(V00+z*(V01+z*(V02+z*(V03+z*V04)))) + return x*(u/v) + (2/Pi)*(J1(x)*Log(x)-1/x) +} + +// For x >= 8, the asymptotic expansions of pone is +// 1 + 15/128 s**2 - 4725/2**15 s**4 - ..., where s = 1/x. +// We approximate pone by +// pone(x) = 1 + (R/S) +// where R = pr0 + pr1*s**2 + pr2*s**4 + ... + pr5*s**10 +// S = 1 + ps0*s**2 + ... + ps4*s**10 +// and +// | pone(x)-1-R/S | <= 2**(-60.06) + +// for x in [inf, 8]=1/[0,0.125] +var p1R8 = [6]float64{ + 0.00000000000000000000e+00, // 0x0000000000000000 + 1.17187499999988647970e-01, // 0x3FBDFFFFFFFFFCCE + 1.32394806593073575129e+01, // 0x402A7A9D357F7FCE + 4.12051854307378562225e+02, // 0x4079C0D4652EA590 + 3.87474538913960532227e+03, // 0x40AE457DA3A532CC + 7.91447954031891731574e+03, // 0x40BEEA7AC32782DD +} +var p1S8 = [5]float64{ + 1.14207370375678408436e+02, // 0x405C8D458E656CAC + 3.65093083420853463394e+03, // 0x40AC85DC964D274F + 3.69562060269033463555e+04, // 0x40E20B8697C5BB7F + 9.76027935934950801311e+04, // 0x40F7D42CB28F17BB + 3.08042720627888811578e+04, // 0x40DE1511697A0B2D +} + +// for x in [8,4.5454] = 1/[0.125,0.22001] +var p1R5 = [6]float64{ + 1.31990519556243522749e-11, // 0x3DAD0667DAE1CA7D + 1.17187493190614097638e-01, // 0x3FBDFFFFE2C10043 + 6.80275127868432871736e+00, // 0x401B36046E6315E3 + 1.08308182990189109773e+02, // 0x405B13B9452602ED + 5.17636139533199752805e+02, // 0x40802D16D052D649 + 5.28715201363337541807e+02, // 0x408085B8BB7E0CB7 +} +var p1S5 = [5]float64{ + 5.92805987221131331921e+01, // 0x404DA3EAA8AF633D + 9.91401418733614377743e+02, // 0x408EFB361B066701 + 5.35326695291487976647e+03, // 0x40B4E9445706B6FB + 7.84469031749551231769e+03, // 0x40BEA4B0B8A5BB15 + 1.50404688810361062679e+03, // 0x40978030036F5E51 +} + +// for x in[4.5453,2.8571] = 1/[0.2199,0.35001] +var p1R3 = [6]float64{ + 3.02503916137373618024e-09, // 0x3E29FC21A7AD9EDD + 1.17186865567253592491e-01, // 0x3FBDFFF55B21D17B + 3.93297750033315640650e+00, // 0x400F76BCE85EAD8A + 3.51194035591636932736e+01, // 0x40418F489DA6D129 + 9.10550110750781271918e+01, // 0x4056C3854D2C1837 + 4.85590685197364919645e+01, // 0x4048478F8EA83EE5 +} +var p1S3 = [5]float64{ + 3.47913095001251519989e+01, // 0x40416549A134069C + 3.36762458747825746741e+02, // 0x40750C3307F1A75F + 1.04687139975775130551e+03, // 0x40905B7C5037D523 + 8.90811346398256432622e+02, // 0x408BD67DA32E31E9 + 1.03787932439639277504e+02, // 0x4059F26D7C2EED53 +} + +// for x in [2.8570,2] = 1/[0.3499,0.5] +var p1R2 = [6]float64{ + 1.07710830106873743082e-07, // 0x3E7CE9D4F65544F4 + 1.17176219462683348094e-01, // 0x3FBDFF42BE760D83 + 2.36851496667608785174e+00, // 0x4002F2B7F98FAEC0 + 1.22426109148261232917e+01, // 0x40287C377F71A964 + 1.76939711271687727390e+01, // 0x4031B1A8177F8EE2 + 5.07352312588818499250e+00, // 0x40144B49A574C1FE +} +var p1S2 = [5]float64{ + 2.14364859363821409488e+01, // 0x40356FBD8AD5ECDC + 1.25290227168402751090e+02, // 0x405F529314F92CD5 + 2.32276469057162813669e+02, // 0x406D08D8D5A2DBD9 + 1.17679373287147100768e+02, // 0x405D6B7ADA1884A9 + 8.36463893371618283368e+00, // 0x4020BAB1F44E5192 +} + +func pone(x float64) float64 { + var p *[6]float64 + var q *[5]float64 + if x >= 8 { + p = &p1R8 + q = &p1S8 + } else if x >= 4.5454 { + p = &p1R5 + q = &p1S5 + } else if x >= 2.8571 { + p = &p1R3 + q = &p1S3 + } else if x >= 2 { + p = &p1R2 + q = &p1S2 + } + z := 1 / (x * x) + r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5])))) + s := 1.0 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*q[4])))) + return 1 + r/s +} + +// For x >= 8, the asymptotic expansions of qone is +// 3/8 s - 105/1024 s**3 - ..., where s = 1/x. +// We approximate qone by +// qone(x) = s*(0.375 + (R/S)) +// where R = qr1*s**2 + qr2*s**4 + ... + qr5*s**10 +// S = 1 + qs1*s**2 + ... + qs6*s**12 +// and +// | qone(x)/s -0.375-R/S | <= 2**(-61.13) + +// for x in [inf, 8] = 1/[0,0.125] +var q1R8 = [6]float64{ + 0.00000000000000000000e+00, // 0x0000000000000000 + -1.02539062499992714161e-01, // 0xBFBA3FFFFFFFFDF3 + -1.62717534544589987888e+01, // 0xC0304591A26779F7 + -7.59601722513950107896e+02, // 0xC087BCD053E4B576 + -1.18498066702429587167e+04, // 0xC0C724E740F87415 + -4.84385124285750353010e+04, // 0xC0E7A6D065D09C6A +} +var q1S8 = [6]float64{ + 1.61395369700722909556e+02, // 0x40642CA6DE5BCDE5 + 7.82538599923348465381e+03, // 0x40BE9162D0D88419 + 1.33875336287249578163e+05, // 0x4100579AB0B75E98 + 7.19657723683240939863e+05, // 0x4125F65372869C19 + 6.66601232617776375264e+05, // 0x412457D27719AD5C + -2.94490264303834643215e+05, // 0xC111F9690EA5AA18 +} + +// for x in [8,4.5454] = 1/[0.125,0.22001] +var q1R5 = [6]float64{ + -2.08979931141764104297e-11, // 0xBDB6FA431AA1A098 + -1.02539050241375426231e-01, // 0xBFBA3FFFCB597FEF + -8.05644828123936029840e+00, // 0xC0201CE6CA03AD4B + -1.83669607474888380239e+02, // 0xC066F56D6CA7B9B0 + -1.37319376065508163265e+03, // 0xC09574C66931734F + -2.61244440453215656817e+03, // 0xC0A468E388FDA79D +} +var q1S5 = [6]float64{ + 8.12765501384335777857e+01, // 0x405451B2FF5A11B2 + 1.99179873460485964642e+03, // 0x409F1F31E77BF839 + 1.74684851924908907677e+04, // 0x40D10F1F0D64CE29 + 4.98514270910352279316e+04, // 0x40E8576DAABAD197 + 2.79480751638918118260e+04, // 0x40DB4B04CF7C364B + -4.71918354795128470869e+03, // 0xC0B26F2EFCFFA004 +} + +// for x in [4.5454,2.8571] = 1/[0.2199,0.35001] ??? +var q1R3 = [6]float64{ + -5.07831226461766561369e-09, // 0xBE35CFA9D38FC84F + -1.02537829820837089745e-01, // 0xBFBA3FEB51AEED54 + -4.61011581139473403113e+00, // 0xC01270C23302D9FF + -5.78472216562783643212e+01, // 0xC04CEC71C25D16DA + -2.28244540737631695038e+02, // 0xC06C87D34718D55F + -2.19210128478909325622e+02, // 0xC06B66B95F5C1BF6 +} +var q1S3 = [6]float64{ + 4.76651550323729509273e+01, // 0x4047D523CCD367E4 + 6.73865112676699709482e+02, // 0x40850EEBC031EE3E + 3.38015286679526343505e+03, // 0x40AA684E448E7C9A + 5.54772909720722782367e+03, // 0x40B5ABBAA61D54A6 + 1.90311919338810798763e+03, // 0x409DBC7A0DD4DF4B + -1.35201191444307340817e+02, // 0xC060E670290A311F +} + +// for x in [2.8570,2] = 1/[0.3499,0.5] +var q1R2 = [6]float64{ + -1.78381727510958865572e-07, // 0xBE87F12644C626D2 + -1.02517042607985553460e-01, // 0xBFBA3E8E9148B010 + -2.75220568278187460720e+00, // 0xC006048469BB4EDA + -1.96636162643703720221e+01, // 0xC033A9E2C168907F + -4.23253133372830490089e+01, // 0xC04529A3DE104AAA + -2.13719211703704061733e+01, // 0xC0355F3639CF6E52 +} +var q1S2 = [6]float64{ + 2.95333629060523854548e+01, // 0x403D888A78AE64FF + 2.52981549982190529136e+02, // 0x406F9F68DB821CBA + 7.57502834868645436472e+02, // 0x4087AC05CE49A0F7 + 7.39393205320467245656e+02, // 0x40871B2548D4C029 + 1.55949003336666123687e+02, // 0x40637E5E3C3ED8D4 + -4.95949898822628210127e+00, // 0xC013D686E71BE86B +} + +func qone(x float64) float64 { + var p, q *[6]float64 + if x >= 8 { + p = &q1R8 + q = &q1S8 + } else if x >= 4.5454 { + p = &q1R5 + q = &q1S5 + } else if x >= 2.8571 { + p = &q1R3 + q = &q1S3 + } else if x >= 2 { + p = &q1R2 + q = &q1S2 + } + z := 1 / (x * x) + r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5])))) + s := 1 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*(q[4]+z*q[5]))))) + return (0.375 + r/s) / x +} diff --git a/go/src/math/jn.go b/go/src/math/jn.go new file mode 100644 index 0000000000000000000000000000000000000000..3491692a96ca7f3e570a2545d1cca7353ad6524a --- /dev/null +++ b/go/src/math/jn.go @@ -0,0 +1,306 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Bessel function of the first and second kinds of order n. +*/ + +// The original C code and the long comment below are +// from FreeBSD's /usr/src/lib/msun/src/e_jn.c and +// came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_jn(n, x), __ieee754_yn(n, x) +// floating point Bessel's function of the 1st and 2nd kind +// of order n +// +// Special cases: +// y0(0)=y1(0)=yn(n,0) = -inf with division by zero signal; +// y0(-ve)=y1(-ve)=yn(n,-ve) are NaN with invalid signal. +// Note 2. About jn(n,x), yn(n,x) +// For n=0, j0(x) is called, +// for n=1, j1(x) is called, +// for nx, a continued fraction approximation to +// j(n,x)/j(n-1,x) is evaluated and then backward +// recursion is used starting from a supposed value +// for j(n,x). The resulting value of j(0,x) is +// compared with the actual value to correct the +// supposed value of j(n,x). +// +// yn(n,x) is similar in all respects, except +// that forward recursion is used for all +// values of n>1. + +// Jn returns the order-n Bessel function of the first kind. +// +// Special cases are: +// +// Jn(n, ±Inf) = 0 +// Jn(n, NaN) = NaN +func Jn(n int, x float64) float64 { + const ( + TwoM29 = 1.0 / (1 << 29) // 2**-29 0x3e10000000000000 + Two302 = 1 << 302 // 2**302 0x52D0000000000000 + ) + // special cases + switch { + case IsNaN(x): + return x + case IsInf(x, 0): + return 0 + } + // J(-n, x) = (-1)**n * J(n, x), J(n, -x) = (-1)**n * J(n, x) + // Thus, J(-n, x) = J(n, -x) + + if n == 0 { + return J0(x) + } + if x == 0 { + return 0 + } + if n < 0 { + n, x = -n, -x + } + if n == 1 { + return J1(x) + } + sign := false + if x < 0 { + x = -x + if n&1 == 1 { + sign = true // odd n and negative x + } + } + var b float64 + if float64(n) <= x { + // Safe to use J(n+1,x)=2n/x *J(n,x)-J(n-1,x) + if x >= Two302 { // x > 2**302 + + // (x >> n**2) + // Jn(x) = cos(x-(2n+1)*pi/4)*sqrt(2/x*pi) + // Yn(x) = sin(x-(2n+1)*pi/4)*sqrt(2/x*pi) + // Let s=sin(x), c=cos(x), + // xn=x-(2n+1)*pi/4, sqt2 = sqrt(2),then + // + // n sin(xn)*sqt2 cos(xn)*sqt2 + // ---------------------------------- + // 0 s-c c+s + // 1 -s-c -c+s + // 2 -s+c -c-s + // 3 s+c c-s + + var temp float64 + switch s, c := Sincos(x); n & 3 { + case 0: + temp = c + s + case 1: + temp = -c + s + case 2: + temp = -c - s + case 3: + temp = c - s + } + b = (1 / SqrtPi) * temp / Sqrt(x) + } else { + b = J1(x) + for i, a := 1, J0(x); i < n; i++ { + a, b = b, b*(float64(i+i)/x)-a // avoid underflow + } + } + } else { + if x < TwoM29 { // x < 2**-29 + // x is tiny, return the first Taylor expansion of J(n,x) + // J(n,x) = 1/n!*(x/2)**n - ... + + if n > 33 { // underflow + b = 0 + } else { + temp := x * 0.5 + b = temp + a := 1.0 + for i := 2; i <= n; i++ { + a *= float64(i) // a = n! + b *= temp // b = (x/2)**n + } + b /= a + } + } else { + // use backward recurrence + // x x**2 x**2 + // J(n,x)/J(n-1,x) = ---- ------ ------ ..... + // 2n - 2(n+1) - 2(n+2) + // + // 1 1 1 + // (for large x) = ---- ------ ------ ..... + // 2n 2(n+1) 2(n+2) + // -- - ------ - ------ - + // x x x + // + // Let w = 2n/x and h=2/x, then the above quotient + // is equal to the continued fraction: + // 1 + // = ----------------------- + // 1 + // w - ----------------- + // 1 + // w+h - --------- + // w+2h - ... + // + // To determine how many terms needed, let + // Q(0) = w, Q(1) = w(w+h) - 1, + // Q(k) = (w+k*h)*Q(k-1) - Q(k-2), + // When Q(k) > 1e4 good for single + // When Q(k) > 1e9 good for double + // When Q(k) > 1e17 good for quadruple + + // determine k + w := float64(n+n) / x + h := 2 / x + q0 := w + z := w + h + q1 := w*z - 1 + k := 1 + for q1 < 1e9 { + k++ + z += h + q0, q1 = q1, z*q1-q0 + } + m := n + n + t := 0.0 + for i := 2 * (n + k); i >= m; i -= 2 { + t = 1 / (float64(i)/x - t) + } + a := t + b = 1 + // estimate log((2/x)**n*n!) = n*log(2/x)+n*ln(n) + // Hence, if n*(log(2n/x)) > ... + // single 8.8722839355e+01 + // double 7.09782712893383973096e+02 + // long double 1.1356523406294143949491931077970765006170e+04 + // then recurrent value may overflow and the result is + // likely underflow to zero + + tmp := float64(n) + v := 2 / x + tmp = tmp * Log(Abs(v*tmp)) + if tmp < 7.09782712893383973096e+02 { + for i := n - 1; i > 0; i-- { + di := float64(i + i) + a, b = b, b*di/x-a + } + } else { + for i := n - 1; i > 0; i-- { + di := float64(i + i) + a, b = b, b*di/x-a + // scale b to avoid spurious overflow + if b > 1e100 { + a /= b + t /= b + b = 1 + } + } + } + b = t * J0(x) / b + } + } + if sign { + return -b + } + return b +} + +// Yn returns the order-n Bessel function of the second kind. +// +// Special cases are: +// +// Yn(n, +Inf) = 0 +// Yn(n ≥ 0, 0) = -Inf +// Yn(n < 0, 0) = +Inf if n is odd, -Inf if n is even +// Yn(n, x < 0) = NaN +// Yn(n, NaN) = NaN +func Yn(n int, x float64) float64 { + const Two302 = 1 << 302 // 2**302 0x52D0000000000000 + // special cases + switch { + case x < 0 || IsNaN(x): + return NaN() + case IsInf(x, 1): + return 0 + } + + if n == 0 { + return Y0(x) + } + if x == 0 { + if n < 0 && n&1 == 1 { + return Inf(1) + } + return Inf(-1) + } + sign := false + if n < 0 { + n = -n + if n&1 == 1 { + sign = true // sign true if n < 0 && |n| odd + } + } + if n == 1 { + if sign { + return -Y1(x) + } + return Y1(x) + } + var b float64 + if x >= Two302 { // x > 2**302 + // (x >> n**2) + // Jn(x) = cos(x-(2n+1)*pi/4)*sqrt(2/x*pi) + // Yn(x) = sin(x-(2n+1)*pi/4)*sqrt(2/x*pi) + // Let s=sin(x), c=cos(x), + // xn=x-(2n+1)*pi/4, sqt2 = sqrt(2),then + // + // n sin(xn)*sqt2 cos(xn)*sqt2 + // ---------------------------------- + // 0 s-c c+s + // 1 -s-c -c+s + // 2 -s+c -c-s + // 3 s+c c-s + + var temp float64 + switch s, c := Sincos(x); n & 3 { + case 0: + temp = s - c + case 1: + temp = -s - c + case 2: + temp = -s + c + case 3: + temp = s + c + } + b = (1 / SqrtPi) * temp / Sqrt(x) + } else { + a := Y0(x) + b = Y1(x) + // quit if b is -inf + for i := 1; i < n && !IsInf(b, -1); i++ { + a, b = b, (float64(i+i)/x)*b-a + } + } + if sign { + return -b + } + return b +} diff --git a/go/src/math/ldexp.go b/go/src/math/ldexp.go new file mode 100644 index 0000000000000000000000000000000000000000..fad099dfa26e6f18aad278766f159d2130384b5c --- /dev/null +++ b/go/src/math/ldexp.go @@ -0,0 +1,51 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Ldexp is the inverse of [Frexp]. +// It returns frac × 2**exp. +// +// Special cases are: +// +// Ldexp(±0, exp) = ±0 +// Ldexp(±Inf, exp) = ±Inf +// Ldexp(NaN, exp) = NaN +func Ldexp(frac float64, exp int) float64 { + if haveArchLdexp { + return archLdexp(frac, exp) + } + return ldexp(frac, exp) +} + +func ldexp(frac float64, exp int) float64 { + // special cases + switch { + case frac == 0: + return frac // correctly return -0 + case IsInf(frac, 0) || IsNaN(frac): + return frac + } + frac, e := normalize(frac) + exp += e + x := Float64bits(frac) + exp += int(x>>shift)&mask - bias + if exp < -1075 { + return Copysign(0, frac) // underflow + } + if exp > 1023 { // overflow + if frac < 0 { + return Inf(-1) + } + return Inf(1) + } + var m float64 = 1 + if exp < -1022 { // denormal + exp += 53 + m = 1.0 / (1 << 53) // 2**-53 + } + x &^= mask << shift + x |= uint64(exp+bias) << shift + return m * Float64frombits(x) +} diff --git a/go/src/math/lgamma.go b/go/src/math/lgamma.go new file mode 100644 index 0000000000000000000000000000000000000000..5a7ea2a58c7cf0a918b78938369090b2d518591f --- /dev/null +++ b/go/src/math/lgamma.go @@ -0,0 +1,366 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point logarithm of the Gamma function. +*/ + +// The original C code and the long comment below are +// from FreeBSD's /usr/src/lib/msun/src/e_lgamma_r.c and +// came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_lgamma_r(x, signgamp) +// Reentrant version of the logarithm of the Gamma function +// with user provided pointer for the sign of Gamma(x). +// +// Method: +// 1. Argument Reduction for 0 < x <= 8 +// Since gamma(1+s)=s*gamma(s), for x in [0,8], we may +// reduce x to a number in [1.5,2.5] by +// lgamma(1+s) = log(s) + lgamma(s) +// for example, +// lgamma(7.3) = log(6.3) + lgamma(6.3) +// = log(6.3*5.3) + lgamma(5.3) +// = log(6.3*5.3*4.3*3.3*2.3) + lgamma(2.3) +// 2. Polynomial approximation of lgamma around its +// minimum (ymin=1.461632144968362245) to maintain monotonicity. +// On [ymin-0.23, ymin+0.27] (i.e., [1.23164,1.73163]), use +// Let z = x-ymin; +// lgamma(x) = -1.214862905358496078218 + z**2*poly(z) +// poly(z) is a 14 degree polynomial. +// 2. Rational approximation in the primary interval [2,3] +// We use the following approximation: +// s = x-2.0; +// lgamma(x) = 0.5*s + s*P(s)/Q(s) +// with accuracy +// |P/Q - (lgamma(x)-0.5s)| < 2**-61.71 +// Our algorithms are based on the following observation +// +// zeta(2)-1 2 zeta(3)-1 3 +// lgamma(2+s) = s*(1-Euler) + --------- * s - --------- * s + ... +// 2 3 +// +// where Euler = 0.5772156649... is the Euler constant, which +// is very close to 0.5. +// +// 3. For x>=8, we have +// lgamma(x)~(x-0.5)log(x)-x+0.5*log(2pi)+1/(12x)-1/(360x**3)+.... +// (better formula: +// lgamma(x)~(x-0.5)*(log(x)-1)-.5*(log(2pi)-1) + ...) +// Let z = 1/x, then we approximation +// f(z) = lgamma(x) - (x-0.5)(log(x)-1) +// by +// 3 5 11 +// w = w0 + w1*z + w2*z + w3*z + ... + w6*z +// where +// |w - f(z)| < 2**-58.74 +// +// 4. For negative x, since (G is gamma function) +// -x*G(-x)*G(x) = pi/sin(pi*x), +// we have +// G(x) = pi/(sin(pi*x)*(-x)*G(-x)) +// since G(-x) is positive, sign(G(x)) = sign(sin(pi*x)) for x<0 +// Hence, for x<0, signgam = sign(sin(pi*x)) and +// lgamma(x) = log(|Gamma(x)|) +// = log(pi/(|x*sin(pi*x)|)) - lgamma(-x); +// Note: one should avoid computing pi*(-x) directly in the +// computation of sin(pi*(-x)). +// +// 5. Special Cases +// lgamma(2+s) ~ s*(1-Euler) for tiny s +// lgamma(1)=lgamma(2)=0 +// lgamma(x) ~ -log(x) for tiny x +// lgamma(0) = lgamma(inf) = inf +// lgamma(-integer) = +-inf +// +// + +var _lgamA = [...]float64{ + 7.72156649015328655494e-02, // 0x3FB3C467E37DB0C8 + 3.22467033424113591611e-01, // 0x3FD4A34CC4A60FAD + 6.73523010531292681824e-02, // 0x3FB13E001A5562A7 + 2.05808084325167332806e-02, // 0x3F951322AC92547B + 7.38555086081402883957e-03, // 0x3F7E404FB68FEFE8 + 2.89051383673415629091e-03, // 0x3F67ADD8CCB7926B + 1.19270763183362067845e-03, // 0x3F538A94116F3F5D + 5.10069792153511336608e-04, // 0x3F40B6C689B99C00 + 2.20862790713908385557e-04, // 0x3F2CF2ECED10E54D + 1.08011567247583939954e-04, // 0x3F1C5088987DFB07 + 2.52144565451257326939e-05, // 0x3EFA7074428CFA52 + 4.48640949618915160150e-05, // 0x3F07858E90A45837 +} +var _lgamR = [...]float64{ + 1.0, // placeholder + 1.39200533467621045958e+00, // 0x3FF645A762C4AB74 + 7.21935547567138069525e-01, // 0x3FE71A1893D3DCDC + 1.71933865632803078993e-01, // 0x3FC601EDCCFBDF27 + 1.86459191715652901344e-02, // 0x3F9317EA742ED475 + 7.77942496381893596434e-04, // 0x3F497DDACA41A95B + 7.32668430744625636189e-06, // 0x3EDEBAF7A5B38140 +} +var _lgamS = [...]float64{ + -7.72156649015328655494e-02, // 0xBFB3C467E37DB0C8 + 2.14982415960608852501e-01, // 0x3FCB848B36E20878 + 3.25778796408930981787e-01, // 0x3FD4D98F4F139F59 + 1.46350472652464452805e-01, // 0x3FC2BB9CBEE5F2F7 + 2.66422703033638609560e-02, // 0x3F9B481C7E939961 + 1.84028451407337715652e-03, // 0x3F5E26B67368F239 + 3.19475326584100867617e-05, // 0x3F00BFECDD17E945 +} +var _lgamT = [...]float64{ + 4.83836122723810047042e-01, // 0x3FDEF72BC8EE38A2 + -1.47587722994593911752e-01, // 0xBFC2E4278DC6C509 + 6.46249402391333854778e-02, // 0x3FB08B4294D5419B + -3.27885410759859649565e-02, // 0xBFA0C9A8DF35B713 + 1.79706750811820387126e-02, // 0x3F9266E7970AF9EC + -1.03142241298341437450e-02, // 0xBF851F9FBA91EC6A + 6.10053870246291332635e-03, // 0x3F78FCE0E370E344 + -3.68452016781138256760e-03, // 0xBF6E2EFFB3E914D7 + 2.25964780900612472250e-03, // 0x3F6282D32E15C915 + -1.40346469989232843813e-03, // 0xBF56FE8EBF2D1AF1 + 8.81081882437654011382e-04, // 0x3F4CDF0CEF61A8E9 + -5.38595305356740546715e-04, // 0xBF41A6109C73E0EC + 3.15632070903625950361e-04, // 0x3F34AF6D6C0EBBF7 + -3.12754168375120860518e-04, // 0xBF347F24ECC38C38 + 3.35529192635519073543e-04, // 0x3F35FD3EE8C2D3F4 +} +var _lgamU = [...]float64{ + -7.72156649015328655494e-02, // 0xBFB3C467E37DB0C8 + 6.32827064025093366517e-01, // 0x3FE4401E8B005DFF + 1.45492250137234768737e+00, // 0x3FF7475CD119BD6F + 9.77717527963372745603e-01, // 0x3FEF497644EA8450 + 2.28963728064692451092e-01, // 0x3FCD4EAEF6010924 + 1.33810918536787660377e-02, // 0x3F8B678BBF2BAB09 +} +var _lgamV = [...]float64{ + 1.0, + 2.45597793713041134822e+00, // 0x4003A5D7C2BD619C + 2.12848976379893395361e+00, // 0x40010725A42B18F5 + 7.69285150456672783825e-01, // 0x3FE89DFBE45050AF + 1.04222645593369134254e-01, // 0x3FBAAE55D6537C88 + 3.21709242282423911810e-03, // 0x3F6A5ABB57D0CF61 +} +var _lgamW = [...]float64{ + 4.18938533204672725052e-01, // 0x3FDACFE390C97D69 + 8.33333333333329678849e-02, // 0x3FB555555555553B + -2.77777777728775536470e-03, // 0xBF66C16C16B02E5C + 7.93650558643019558500e-04, // 0x3F4A019F98CF38B6 + -5.95187557450339963135e-04, // 0xBF4380CB8C0FE741 + 8.36339918996282139126e-04, // 0x3F4B67BA4CDAD5D1 + -1.63092934096575273989e-03, // 0xBF5AB89D0B9E43E4 +} + +// Lgamma returns the natural logarithm and sign (-1 or +1) of [Gamma](x). +// +// Special cases are: +// +// Lgamma(+Inf) = +Inf +// Lgamma(0) = +Inf +// Lgamma(-integer) = +Inf +// Lgamma(-Inf) = -Inf +// Lgamma(NaN) = NaN +func Lgamma(x float64) (lgamma float64, sign int) { + const ( + Ymin = 1.461632144968362245 + Two52 = 1 << 52 // 0x4330000000000000 ~4.5036e+15 + Two53 = 1 << 53 // 0x4340000000000000 ~9.0072e+15 + Two58 = 1 << 58 // 0x4390000000000000 ~2.8823e+17 + Tiny = 1.0 / (1 << 70) // 0x3b90000000000000 ~8.47033e-22 + Tc = 1.46163214496836224576e+00 // 0x3FF762D86356BE3F + Tf = -1.21486290535849611461e-01 // 0xBFBF19B9BCC38A42 + // Tt = -(tail of Tf) + Tt = -3.63867699703950536541e-18 // 0xBC50C7CAA48A971F + ) + // special cases + sign = 1 + switch { + case IsNaN(x): + lgamma = x + return + case IsInf(x, 0): + lgamma = x + return + case x == 0: + lgamma = Inf(1) + return + } + + neg := false + if x < 0 { + x = -x + neg = true + } + + if x < Tiny { // if |x| < 2**-70, return -log(|x|) + if neg { + sign = -1 + } + lgamma = -Log(x) + return + } + var nadj float64 + if neg { + if x >= Two52 { // |x| >= 2**52, must be -integer + lgamma = Inf(1) + return + } + t := sinPi(x) + if t == 0 { + lgamma = Inf(1) // -integer + return + } + nadj = Log(Pi / Abs(t*x)) + if t < 0 { + sign = -1 + } + } + + switch { + case x == 1 || x == 2: // purge off 1 and 2 + lgamma = 0 + return + case x < 2: // use lgamma(x) = lgamma(x+1) - log(x) + var y float64 + var i int + if x <= 0.9 { + lgamma = -Log(x) + switch { + case x >= (Ymin - 1 + 0.27): // 0.7316 <= x <= 0.9 + y = 1 - x + i = 0 + case x >= (Ymin - 1 - 0.27): // 0.2316 <= x < 0.7316 + y = x - (Tc - 1) + i = 1 + default: // 0 < x < 0.2316 + y = x + i = 2 + } + } else { + lgamma = 0 + switch { + case x >= (Ymin + 0.27): // 1.7316 <= x < 2 + y = 2 - x + i = 0 + case x >= (Ymin - 0.27): // 1.2316 <= x < 1.7316 + y = x - Tc + i = 1 + default: // 0.9 < x < 1.2316 + y = x - 1 + i = 2 + } + } + switch i { + case 0: + z := y * y + p1 := _lgamA[0] + z*(_lgamA[2]+z*(_lgamA[4]+z*(_lgamA[6]+z*(_lgamA[8]+z*_lgamA[10])))) + p2 := z * (_lgamA[1] + z*(+_lgamA[3]+z*(_lgamA[5]+z*(_lgamA[7]+z*(_lgamA[9]+z*_lgamA[11]))))) + p := y*p1 + p2 + lgamma += (p - 0.5*y) + case 1: + z := y * y + w := z * y + p1 := _lgamT[0] + w*(_lgamT[3]+w*(_lgamT[6]+w*(_lgamT[9]+w*_lgamT[12]))) // parallel comp + p2 := _lgamT[1] + w*(_lgamT[4]+w*(_lgamT[7]+w*(_lgamT[10]+w*_lgamT[13]))) + p3 := _lgamT[2] + w*(_lgamT[5]+w*(_lgamT[8]+w*(_lgamT[11]+w*_lgamT[14]))) + p := z*p1 - (Tt - w*(p2+y*p3)) + lgamma += (Tf + p) + case 2: + p1 := y * (_lgamU[0] + y*(_lgamU[1]+y*(_lgamU[2]+y*(_lgamU[3]+y*(_lgamU[4]+y*_lgamU[5]))))) + p2 := 1 + y*(_lgamV[1]+y*(_lgamV[2]+y*(_lgamV[3]+y*(_lgamV[4]+y*_lgamV[5])))) + lgamma += (-0.5*y + p1/p2) + } + case x < 8: // 2 <= x < 8 + i := int(x) + y := x - float64(i) + p := y * (_lgamS[0] + y*(_lgamS[1]+y*(_lgamS[2]+y*(_lgamS[3]+y*(_lgamS[4]+y*(_lgamS[5]+y*_lgamS[6])))))) + q := 1 + y*(_lgamR[1]+y*(_lgamR[2]+y*(_lgamR[3]+y*(_lgamR[4]+y*(_lgamR[5]+y*_lgamR[6]))))) + lgamma = 0.5*y + p/q + z := 1.0 // Lgamma(1+s) = Log(s) + Lgamma(s) + switch i { + case 7: + z *= (y + 6) + fallthrough + case 6: + z *= (y + 5) + fallthrough + case 5: + z *= (y + 4) + fallthrough + case 4: + z *= (y + 3) + fallthrough + case 3: + z *= (y + 2) + lgamma += Log(z) + } + case x < Two58: // 8 <= x < 2**58 + t := Log(x) + z := 1 / x + y := z * z + w := _lgamW[0] + z*(_lgamW[1]+y*(_lgamW[2]+y*(_lgamW[3]+y*(_lgamW[4]+y*(_lgamW[5]+y*_lgamW[6]))))) + lgamma = (x-0.5)*(t-1) + w + default: // 2**58 <= x <= Inf + lgamma = x * (Log(x) - 1) + } + if neg { + lgamma = nadj - lgamma + } + return +} + +// sinPi(x) is a helper function for negative x +func sinPi(x float64) float64 { + const ( + Two52 = 1 << 52 // 0x4330000000000000 ~4.5036e+15 + Two53 = 1 << 53 // 0x4340000000000000 ~9.0072e+15 + ) + if x < 0.25 { + return -Sin(Pi * x) + } + + // argument reduction + z := Floor(x) + var n int + if z != x { // inexact + x = Mod(x, 2) + n = int(x * 4) + } else { + if x >= Two53 { // x must be even + x = 0 + n = 0 + } else { + if x < Two52 { + z = x + Two52 // exact + } + n = int(1 & Float64bits(z)) + x = float64(n) + n <<= 2 + } + } + switch n { + case 0: + x = Sin(Pi * x) + case 1, 2: + x = Cos(Pi * (0.5 - x)) + case 3, 4: + x = Sin(Pi * (1 - x)) + case 5, 6: + x = -Cos(Pi * (x - 1.5)) + default: + x = Sin(Pi * (x - 2)) + } + return -x +} diff --git a/go/src/math/log.go b/go/src/math/log.go new file mode 100644 index 0000000000000000000000000000000000000000..695a545e7f00ec23ccf024e91c6172a454613fe4 --- /dev/null +++ b/go/src/math/log.go @@ -0,0 +1,129 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point logarithm. +*/ + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/e_log.c +// and came with this notice. The go code is a simpler +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_log(x) +// Return the logarithm of x +// +// Method : +// 1. Argument Reduction: find k and f such that +// x = 2**k * (1+f), +// where sqrt(2)/2 < 1+f < sqrt(2) . +// +// 2. Approximation of log(1+f). +// Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) +// = 2s + 2/3 s**3 + 2/5 s**5 + ....., +// = 2s + s*R +// We use a special Reme algorithm on [0,0.1716] to generate +// a polynomial of degree 14 to approximate R. The maximum error +// of this polynomial approximation is bounded by 2**-58.45. In +// other words, +// 2 4 6 8 10 12 14 +// R(z) ~ L1*s +L2*s +L3*s +L4*s +L5*s +L6*s +L7*s +// (the values of L1 to L7 are listed in the program) and +// | 2 14 | -58.45 +// | L1*s +...+L7*s - R(z) | <= 2 +// | | +// Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. +// In order to guarantee error in log below 1ulp, we compute log by +// log(1+f) = f - s*(f - R) (if f is not too large) +// log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy) +// +// 3. Finally, log(x) = k*Ln2 + log(1+f). +// = k*Ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*Ln2_lo))) +// Here Ln2 is split into two floating point number: +// Ln2_hi + Ln2_lo, +// where n*Ln2_hi is always exact for |n| < 2000. +// +// Special cases: +// log(x) is NaN with signal if x < 0 (including -INF) ; +// log(+INF) is +INF; log(0) is -INF with signal; +// log(NaN) is that NaN with no signal. +// +// Accuracy: +// according to an error analysis, the error is always less than +// 1 ulp (unit in the last place). +// +// Constants: +// The hexadecimal values are the intended ones for the following +// constants. The decimal values may be used, provided that the +// compiler will convert from decimal to binary accurately enough +// to produce the hexadecimal values shown. + +// Log returns the natural logarithm of x. +// +// Special cases are: +// +// Log(+Inf) = +Inf +// Log(0) = -Inf +// Log(x < 0) = NaN +// Log(NaN) = NaN +func Log(x float64) float64 { + if haveArchLog { + return archLog(x) + } + return log(x) +} + +func log(x float64) float64 { + const ( + Ln2Hi = 6.93147180369123816490e-01 /* 3fe62e42 fee00000 */ + Ln2Lo = 1.90821492927058770002e-10 /* 3dea39ef 35793c76 */ + L1 = 6.666666666666735130e-01 /* 3FE55555 55555593 */ + L2 = 3.999999999940941908e-01 /* 3FD99999 9997FA04 */ + L3 = 2.857142874366239149e-01 /* 3FD24924 94229359 */ + L4 = 2.222219843214978396e-01 /* 3FCC71C5 1D8E78AF */ + L5 = 1.818357216161805012e-01 /* 3FC74664 96CB03DE */ + L6 = 1.531383769920937332e-01 /* 3FC39A09 D078C69F */ + L7 = 1.479819860511658591e-01 /* 3FC2F112 DF3E5244 */ + ) + + // special cases + switch { + case IsNaN(x) || IsInf(x, 1): + return x + case x < 0: + return NaN() + case x == 0: + return Inf(-1) + } + + // reduce + f1, ki := Frexp(x) + if f1 < Sqrt2/2 { + f1 *= 2 + ki-- + } + f := f1 - 1 + k := float64(ki) + + // compute + s := f / (2 + f) + s2 := s * s + s4 := s2 * s2 + t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7))) + t2 := s4 * (L2 + s4*(L4+s4*L6)) + R := t1 + t2 + hfsq := 0.5 * f * f + return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f) +} diff --git a/go/src/math/log10.go b/go/src/math/log10.go new file mode 100644 index 0000000000000000000000000000000000000000..02c3a757c012be60ff3654fe063364390b8b947a --- /dev/null +++ b/go/src/math/log10.go @@ -0,0 +1,37 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Log10 returns the decimal logarithm of x. +// The special cases are the same as for [Log]. +func Log10(x float64) float64 { + if haveArchLog10 { + return archLog10(x) + } + return log10(x) +} + +func log10(x float64) float64 { + return Log(x) * (1 / Ln10) +} + +// Log2 returns the binary logarithm of x. +// The special cases are the same as for [Log]. +func Log2(x float64) float64 { + if haveArchLog2 { + return archLog2(x) + } + return log2(x) +} + +func log2(x float64) float64 { + frac, exp := Frexp(x) + // Make sure exact powers of two give an exact answer. + // Don't depend on Log(0.5)*(1/Ln2)+exp being exactly exp-1. + if frac == 0.5 { + return float64(exp - 1) + } + return Log(frac)*(1/Ln2) + float64(exp) +} diff --git a/go/src/math/log10_s390x.s b/go/src/math/log10_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..3638afe700df47ad95aa2bc16c9e07ed5ee04b23 --- /dev/null +++ b/go/src/math/log10_s390x.s @@ -0,0 +1,156 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial coefficients and other constants +DATA log10rodataL19<>+0(SB)/8, $0.000000000000000000E+00 +DATA log10rodataL19<>+8(SB)/8, $-1.0 +DATA log10rodataL19<>+16(SB)/8, $0x7FF8000000000000 //+NanN +DATA log10rodataL19<>+24(SB)/8, $.15375570329280596749 +DATA log10rodataL19<>+32(SB)/8, $.60171950900703668594E+04 +DATA log10rodataL19<>+40(SB)/8, $-1.9578460454940795898 +DATA log10rodataL19<>+48(SB)/8, $0.78962633073318517310E-01 +DATA log10rodataL19<>+56(SB)/8, $-.71784211884836937993E-02 +DATA log10rodataL19<>+64(SB)/8, $0.87011165920689940661E-03 +DATA log10rodataL19<>+72(SB)/8, $-.11865158981621437541E-03 +DATA log10rodataL19<>+80(SB)/8, $0.17258413403018680410E-04 +DATA log10rodataL19<>+88(SB)/8, $0.40752932047883484315E-06 +DATA log10rodataL19<>+96(SB)/8, $-.26149194688832680410E-05 +DATA log10rodataL19<>+104(SB)/8, $0.92453396963875026759E-08 +DATA log10rodataL19<>+112(SB)/8, $-.64572084905921579630E-07 +DATA log10rodataL19<>+120(SB)/8, $-5.5 +DATA log10rodataL19<>+128(SB)/8, $18446744073709551616. +GLOBL log10rodataL19<>+0(SB), RODATA, $136 + +// Table of log10 correction terms +DATA log10tab2074<>+0(SB)/8, $0.254164497922885069E-01 +DATA log10tab2074<>+8(SB)/8, $0.179018857989381839E-01 +DATA log10tab2074<>+16(SB)/8, $0.118926768029048674E-01 +DATA log10tab2074<>+24(SB)/8, $0.722595568238080033E-02 +DATA log10tab2074<>+32(SB)/8, $0.376393570022739135E-02 +DATA log10tab2074<>+40(SB)/8, $0.138901135928814326E-02 +DATA log10tab2074<>+48(SB)/8, $0 +DATA log10tab2074<>+56(SB)/8, $-0.490780466387818203E-03 +DATA log10tab2074<>+64(SB)/8, $-0.159811431402137571E-03 +DATA log10tab2074<>+72(SB)/8, $0.925796337165100494E-03 +DATA log10tab2074<>+80(SB)/8, $0.270683176738357035E-02 +DATA log10tab2074<>+88(SB)/8, $0.513079030821304758E-02 +DATA log10tab2074<>+96(SB)/8, $0.815089785397996303E-02 +DATA log10tab2074<>+104(SB)/8, $0.117253060262419215E-01 +DATA log10tab2074<>+112(SB)/8, $0.158164239345343963E-01 +DATA log10tab2074<>+120(SB)/8, $0.203903595489229786E-01 +GLOBL log10tab2074<>+0(SB), RODATA, $128 + +// Log10 returns the decimal logarithm of the argument. +// +// Special cases are: +// Log(+Inf) = +Inf +// Log(0) = -Inf +// Log(x < 0) = NaN +// Log(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·log10Asm(SB),NOSPLIT,$8-16 + FMOVD x+0(FP), F0 + MOVD $log10rodataL19<>+0(SB), R9 + FMOVD F0, x-8(SP) + WORD $0xC0298006 //iilf %r2,2147909631 + BYTE $0x7F + BYTE $0xFF + WORD $0x5840F008 //l %r4, 8(%r15) + SUBW R4, R2, R3 + RISBGZ $32, $47, $0, R3, R5 + MOVH $0x0, R1 + RISBGN $0, $31, $32, R5, R1 + WORD $0xC0590016 //iilf %r5,1507327 + BYTE $0xFF + BYTE $0xFF + MOVW R4, R10 + MOVW R5, R11 + CMPBLE R10, R11, L2 + WORD $0xC0297FEF //iilf %r2,2146435071 + BYTE $0xFF + BYTE $0xFF + MOVW R4, R10 + MOVW R2, R11 + CMPBLE R10, R11, L16 +L3: +L1: + FMOVD F0, ret+8(FP) + RET + +L2: + LTDBR F0, F0 + BLEU L13 + WORD $0xED009080 //mdb %f0,.L20-.L19(%r9) + BYTE $0x00 + BYTE $0x1C + FMOVD F0, x-8(SP) + WORD $0x5B20F008 //s %r2, 8(%r15) + RISBGZ $57, $60, $51, R2, R3 + ANDW $0xFFFF0000, R2 + RISBGN $0, $31, $32, R2, R1 + ADDW $0x4000000, R2 + BLEU L17 +L8: + SRW $8, R2, R2 + ORW $0x45000000, R2 +L4: + FMOVD log10rodataL19<>+120(SB), F2 + LDGR R1, F4 + WFMADB V4, V0, V2, V0 + FMOVD log10rodataL19<>+112(SB), F4 + FMOVD log10rodataL19<>+104(SB), F6 + WFMADB V0, V6, V4, V6 + FMOVD log10rodataL19<>+96(SB), F4 + FMOVD log10rodataL19<>+88(SB), F1 + WFMADB V0, V1, V4, V1 + WFMDB V0, V0, V4 + FMOVD log10rodataL19<>+80(SB), F2 + WFMADB V6, V4, V1, V6 + FMOVD log10rodataL19<>+72(SB), F1 + WFMADB V0, V2, V1, V2 + FMOVD log10rodataL19<>+64(SB), F1 + RISBGZ $57, $60, $0, R3, R3 + WFMADB V4, V6, V2, V6 + FMOVD log10rodataL19<>+56(SB), F2 + WFMADB V0, V1, V2, V1 + VLVGF $0, R2, V2 + WFMADB V4, V6, V1, V4 + LDEBR F2, F2 + FMOVD log10rodataL19<>+48(SB), F6 + WFMADB V0, V4, V6, V4 + FMOVD log10rodataL19<>+40(SB), F1 + FMOVD log10rodataL19<>+32(SB), F6 + MOVD $log10tab2074<>+0(SB), R1 + WFMADB V2, V1, V6, V2 + WORD $0x68331000 //ld %f3,0(%r3,%r1) + WFMADB V0, V4, V3, V0 + FMOVD log10rodataL19<>+24(SB), F4 + FMADD F4, F2, F0 + FMOVD F0, ret+8(FP) + RET + +L16: + RISBGZ $40, $55, $56, R3, R2 + RISBGZ $57, $60, $51, R3, R3 + ORW $0x45000000, R2 + BR L4 +L13: + BGE L18 //jnl .L18 + BVS L18 + FMOVD log10rodataL19<>+16(SB), F0 + BR L1 +L17: + SRAW $1, R2, R2 + SUBW $0x40000000, R2 + BR L8 +L18: + FMOVD log10rodataL19<>+8(SB), F0 + WORD $0xED009000 //ddb %f0,.L36-.L19(%r9) + BYTE $0x00 + BYTE $0x1D + BR L1 diff --git a/go/src/math/log1p.go b/go/src/math/log1p.go new file mode 100644 index 0000000000000000000000000000000000000000..bfcb813be8ceeccd197e374fdfb2595cc41346fe --- /dev/null +++ b/go/src/math/log1p.go @@ -0,0 +1,203 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/s_log1p.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// double log1p(double x) +// +// Method : +// 1. Argument Reduction: find k and f such that +// 1+x = 2**k * (1+f), +// where sqrt(2)/2 < 1+f < sqrt(2) . +// +// Note. If k=0, then f=x is exact. However, if k!=0, then f +// may not be representable exactly. In that case, a correction +// term is need. Let u=1+x rounded. Let c = (1+x)-u, then +// log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u), +// and add back the correction term c/u. +// (Note: when x > 2**53, one can simply return log(x)) +// +// 2. Approximation of log1p(f). +// Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) +// = 2s + 2/3 s**3 + 2/5 s**5 + ....., +// = 2s + s*R +// We use a special Reme algorithm on [0,0.1716] to generate +// a polynomial of degree 14 to approximate R The maximum error +// of this polynomial approximation is bounded by 2**-58.45. In +// other words, +// 2 4 6 8 10 12 14 +// R(z) ~ Lp1*s +Lp2*s +Lp3*s +Lp4*s +Lp5*s +Lp6*s +Lp7*s +// (the values of Lp1 to Lp7 are listed in the program) +// and +// | 2 14 | -58.45 +// | Lp1*s +...+Lp7*s - R(z) | <= 2 +// | | +// Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. +// In order to guarantee error in log below 1ulp, we compute log +// by +// log1p(f) = f - (hfsq - s*(hfsq+R)). +// +// 3. Finally, log1p(x) = k*ln2 + log1p(f). +// = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo))) +// Here ln2 is split into two floating point number: +// ln2_hi + ln2_lo, +// where n*ln2_hi is always exact for |n| < 2000. +// +// Special cases: +// log1p(x) is NaN with signal if x < -1 (including -INF) ; +// log1p(+INF) is +INF; log1p(-1) is -INF with signal; +// log1p(NaN) is that NaN with no signal. +// +// Accuracy: +// according to an error analysis, the error is always less than +// 1 ulp (unit in the last place). +// +// Constants: +// The hexadecimal values are the intended ones for the following +// constants. The decimal values may be used, provided that the +// compiler will convert from decimal to binary accurately enough +// to produce the hexadecimal values shown. +// +// Note: Assuming log() return accurate answer, the following +// algorithm can be used to compute log1p(x) to within a few ULP: +// +// u = 1+x; +// if(u==1.0) return x ; else +// return log(u)*(x/(u-1.0)); +// +// See HP-15C Advanced Functions Handbook, p.193. + +// Log1p returns the natural logarithm of 1 plus its argument x. +// It is more accurate than [Log](1 + x) when x is near zero. +// +// Special cases are: +// +// Log1p(+Inf) = +Inf +// Log1p(±0) = ±0 +// Log1p(-1) = -Inf +// Log1p(x < -1) = NaN +// Log1p(NaN) = NaN +func Log1p(x float64) float64 { + if haveArchLog1p { + return archLog1p(x) + } + return log1p(x) +} + +func log1p(x float64) float64 { + const ( + Sqrt2M1 = 4.142135623730950488017e-01 // Sqrt(2)-1 = 0x3fda827999fcef34 + Sqrt2HalfM1 = -2.928932188134524755992e-01 // Sqrt(2)/2-1 = 0xbfd2bec333018866 + Small = 1.0 / (1 << 29) // 2**-29 = 0x3e20000000000000 + Tiny = 1.0 / (1 << 54) // 2**-54 + Two53 = 1 << 53 // 2**53 + Ln2Hi = 6.93147180369123816490e-01 // 3fe62e42fee00000 + Ln2Lo = 1.90821492927058770002e-10 // 3dea39ef35793c76 + Lp1 = 6.666666666666735130e-01 // 3FE5555555555593 + Lp2 = 3.999999999940941908e-01 // 3FD999999997FA04 + Lp3 = 2.857142874366239149e-01 // 3FD2492494229359 + Lp4 = 2.222219843214978396e-01 // 3FCC71C51D8E78AF + Lp5 = 1.818357216161805012e-01 // 3FC7466496CB03DE + Lp6 = 1.531383769920937332e-01 // 3FC39A09D078C69F + Lp7 = 1.479819860511658591e-01 // 3FC2F112DF3E5244 + ) + + // special cases + switch { + case x < -1 || IsNaN(x): // includes -Inf + return NaN() + case x == -1: + return Inf(-1) + case IsInf(x, 1): + return Inf(1) + } + + absx := Abs(x) + + var f float64 + var iu uint64 + k := 1 + if absx < Sqrt2M1 { // |x| < Sqrt(2)-1 + if absx < Small { // |x| < 2**-29 + if absx < Tiny { // |x| < 2**-54 + return x + } + return x - x*x*0.5 + } + if x > Sqrt2HalfM1 { // Sqrt(2)/2-1 < x + // (Sqrt(2)/2-1) < x < (Sqrt(2)-1) + k = 0 + f = x + iu = 1 + } + } + var c float64 + if k != 0 { + var u float64 + if absx < Two53 { // 1<<53 + u = 1.0 + x + iu = Float64bits(u) + k = int((iu >> 52) - 1023) + // correction term + if k > 0 { + c = 1.0 - (u - x) + } else { + c = x - (u - 1.0) + } + c /= u + } else { + u = x + iu = Float64bits(u) + k = int((iu >> 52) - 1023) + c = 0 + } + iu &= 0x000fffffffffffff + if iu < 0x0006a09e667f3bcd { // mantissa of Sqrt(2) + u = Float64frombits(iu | 0x3ff0000000000000) // normalize u + } else { + k++ + u = Float64frombits(iu | 0x3fe0000000000000) // normalize u/2 + iu = (0x0010000000000000 - iu) >> 2 + } + f = u - 1.0 // Sqrt(2)/2 < u < Sqrt(2) + } + hfsq := 0.5 * f * f + var s, R, z float64 + if iu == 0 { // |f| < 2**-20 + if f == 0 { + if k == 0 { + return 0 + } + c += float64(k) * Ln2Lo + return float64(k)*Ln2Hi + c + } + R = hfsq * (1.0 - 0.66666666666666666*f) // avoid division + if k == 0 { + return f - R + } + return float64(k)*Ln2Hi - ((R - (float64(k)*Ln2Lo + c)) - f) + } + s = f / (2.0 + f) + z = s * s + R = z * (Lp1 + z*(Lp2+z*(Lp3+z*(Lp4+z*(Lp5+z*(Lp6+z*Lp7)))))) + if k == 0 { + return f - (hfsq - s*(hfsq+R)) + } + return float64(k)*Ln2Hi - ((hfsq - (s*(hfsq+R) + (float64(k)*Ln2Lo + c))) - f) +} diff --git a/go/src/math/log1p_s390x.s b/go/src/math/log1p_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..98fe82c9c390029aebab7474bdcb536c1a414c2c --- /dev/null +++ b/go/src/math/log1p_s390x.s @@ -0,0 +1,180 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Constants +DATA ·log1pxlim<> + 0(SB)/4, $0xfff00000 +GLOBL ·log1pxlim<> + 0(SB), RODATA, $4 +DATA ·log1pxzero<> + 0(SB)/8, $0.0 +GLOBL ·log1pxzero<> + 0(SB), RODATA, $8 +DATA ·log1pxminf<> + 0(SB)/8, $0xfff0000000000000 +GLOBL ·log1pxminf<> + 0(SB), RODATA, $8 +DATA ·log1pxnan<> + 0(SB)/8, $0x7ff8000000000000 +GLOBL ·log1pxnan<> + 0(SB), RODATA, $8 +DATA ·log1pyout<> + 0(SB)/8, $0x40fce621e71da000 +GLOBL ·log1pyout<> + 0(SB), RODATA, $8 +DATA ·log1pxout<> + 0(SB)/8, $0x40f1000000000000 +GLOBL ·log1pxout<> + 0(SB), RODATA, $8 +DATA ·log1pxl2<> + 0(SB)/8, $0xbfda7aecbeba4e46 +GLOBL ·log1pxl2<> + 0(SB), RODATA, $8 +DATA ·log1pxl1<> + 0(SB)/8, $0x3ffacde700000000 +GLOBL ·log1pxl1<> + 0(SB), RODATA, $8 +DATA ·log1pxa<> + 0(SB)/8, $5.5 +GLOBL ·log1pxa<> + 0(SB), RODATA, $8 +DATA ·log1pxmone<> + 0(SB)/8, $-1.0 +GLOBL ·log1pxmone<> + 0(SB), RODATA, $8 + +// Minimax polynomial approximations +DATA ·log1pc8<> + 0(SB)/8, $0.212881813645679599E-07 +GLOBL ·log1pc8<> + 0(SB), RODATA, $8 +DATA ·log1pc7<> + 0(SB)/8, $-.148682720127920854E-06 +GLOBL ·log1pc7<> + 0(SB), RODATA, $8 +DATA ·log1pc6<> + 0(SB)/8, $0.938370938292558173E-06 +GLOBL ·log1pc6<> + 0(SB), RODATA, $8 +DATA ·log1pc5<> + 0(SB)/8, $-.602107458843052029E-05 +GLOBL ·log1pc5<> + 0(SB), RODATA, $8 +DATA ·log1pc4<> + 0(SB)/8, $0.397389654305194527E-04 +GLOBL ·log1pc4<> + 0(SB), RODATA, $8 +DATA ·log1pc3<> + 0(SB)/8, $-.273205381970859341E-03 +GLOBL ·log1pc3<> + 0(SB), RODATA, $8 +DATA ·log1pc2<> + 0(SB)/8, $0.200350613573012186E-02 +GLOBL ·log1pc2<> + 0(SB), RODATA, $8 +DATA ·log1pc1<> + 0(SB)/8, $-.165289256198351540E-01 +GLOBL ·log1pc1<> + 0(SB), RODATA, $8 +DATA ·log1pc0<> + 0(SB)/8, $0.181818181818181826E+00 +GLOBL ·log1pc0<> + 0(SB), RODATA, $8 + + +// Table of log10 correction terms +DATA ·log1ptab<> + 0(SB)/8, $0.585235384085551248E-01 +DATA ·log1ptab<> + 8(SB)/8, $0.412206153771168640E-01 +DATA ·log1ptab<> + 16(SB)/8, $0.273839003221648339E-01 +DATA ·log1ptab<> + 24(SB)/8, $0.166383778368856480E-01 +DATA ·log1ptab<> + 32(SB)/8, $0.866678223433169637E-02 +DATA ·log1ptab<> + 40(SB)/8, $0.319831684989627514E-02 +DATA ·log1ptab<> + 48(SB)/8, $-.000000000000000000E+00 +DATA ·log1ptab<> + 56(SB)/8, $-.113006378583725549E-02 +DATA ·log1ptab<> + 64(SB)/8, $-.367979419636602491E-03 +DATA ·log1ptab<> + 72(SB)/8, $0.213172484510484979E-02 +DATA ·log1ptab<> + 80(SB)/8, $0.623271047682013536E-02 +DATA ·log1ptab<> + 88(SB)/8, $0.118140812789696885E-01 +DATA ·log1ptab<> + 96(SB)/8, $0.187681358930914206E-01 +DATA ·log1ptab<> + 104(SB)/8, $0.269985148668178992E-01 +DATA ·log1ptab<> + 112(SB)/8, $0.364186619761331328E-01 +DATA ·log1ptab<> + 120(SB)/8, $0.469505379381388441E-01 +GLOBL ·log1ptab<> + 0(SB), RODATA, $128 + +// Log1p returns the natural logarithm of 1 plus its argument x. +// It is more accurate than Log(1 + x) when x is near zero. +// +// Special cases are: +// Log1p(+Inf) = +Inf +// Log1p(±0) = ±0 +// Log1p(-1) = -Inf +// Log1p(x < -1) = NaN +// Log1p(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·log1pAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·log1pxmone<>+0(SB), R1 + MOVD ·log1pxout<>+0(SB), R2 + FMOVD 0(R1), F3 + MOVD $·log1pxa<>+0(SB), R1 + MOVWZ ·log1pxlim<>+0(SB), R0 + FMOVD 0(R1), F1 + MOVD $·log1pc8<>+0(SB), R1 + FMOVD 0(R1), F5 + MOVD $·log1pc7<>+0(SB), R1 + VLEG $0, 0(R1), V20 + MOVD $·log1pc6<>+0(SB), R1 + WFSDB V0, V3, V4 + VLEG $0, 0(R1), V18 + MOVD $·log1pc5<>+0(SB), R1 + VLEG $0, 0(R1), V16 + MOVD R2, R5 + LGDR F4, R3 + WORD $0xC0190006 //iilf %r1,425983 + BYTE $0x7F + BYTE $0xFF + SRAD $32, R3, R3 + SUBW R3, R1 + SRW $16, R1, R1 + BYTE $0x18 //lr %r4,%r1 + BYTE $0x41 + RISBGN $0, $15, $48, R4, R2 + RISBGN $16, $31, $32, R4, R5 + MOVW R0, R6 + MOVW R3, R7 + CMPBGT R6, R7, L8 + WFCEDBS V4, V4, V6 + MOVD $·log1pxzero<>+0(SB), R1 + FMOVD 0(R1), F2 + BVS LEXITTAGlog1p + LCDBR F4, F4 + WFCEDBS V2, V4, V6 + BEQ L9 + WFCHDBS V4, V2, V2 + BEQ LEXITTAGlog1p + MOVD $·log1pxnan<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET + +L8: + LDGR R2, F2 + FSUB F4, F3 + FMADD F2, F4, F1 + MOVD $·log1pc4<>+0(SB), R2 + LCDBR F1, F4 + FMOVD 0(R2), F7 + FSUB F3, F0 + MOVD $·log1pc3<>+0(SB), R2 + FMOVD 0(R2), F3 + MOVD $·log1pc2<>+0(SB), R2 + WFMDB V1, V1, V6 + FMADD F7, F4, F3 + WFMSDB V0, V2, V1, V0 + FMOVD 0(R2), F7 + WFMADB V4, V5, V20, V5 + MOVD $·log1pc1<>+0(SB), R2 + FMOVD 0(R2), F2 + FMADD F7, F4, F2 + WFMADB V4, V18, V16, V4 + FMADD F3, F6, F2 + WFMADB V5, V6, V4, V5 + FMUL F6, F6 + MOVD $·log1pc0<>+0(SB), R2 + WFMADB V6, V5, V2, V6 + FMOVD 0(R2), F4 + WFMADB V0, V6, V4, V6 + RISBGZ $57, $60, $3, R1, R1 + MOVD $·log1ptab<>+0(SB), R2 + MOVD $·log1pxl1<>+0(SB), R3 + WORD $0x68112000 //ld %f1,0(%r1,%r2) + FMOVD 0(R3), F2 + WFMADB V0, V6, V1, V0 + MOVD $·log1pyout<>+0(SB), R1 + LDGR R5, F6 + FMOVD 0(R1), F4 + WFMSDB V2, V6, V4, V2 + MOVD $·log1pxl2<>+0(SB), R1 + FMOVD 0(R1), F4 + FMADD F4, F2, F0 + FMOVD F0, ret+8(FP) + RET + +L9: + MOVD $·log1pxminf<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET + + +LEXITTAGlog1p: + FMOVD F0, ret+8(FP) + RET + diff --git a/go/src/math/log_amd64.s b/go/src/math/log_amd64.s new file mode 100644 index 0000000000000000000000000000000000000000..508df68a9bddce0ced5e6017934679b581704620 --- /dev/null +++ b/go/src/math/log_amd64.s @@ -0,0 +1,112 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define HSqrt2 7.07106781186547524401e-01 // sqrt(2)/2 +#define Ln2Hi 6.93147180369123816490e-01 // 0x3fe62e42fee00000 +#define Ln2Lo 1.90821492927058770002e-10 // 0x3dea39ef35793c76 +#define L1 6.666666666666735130e-01 // 0x3FE5555555555593 +#define L2 3.999999999940941908e-01 // 0x3FD999999997FA04 +#define L3 2.857142874366239149e-01 // 0x3FD2492494229359 +#define L4 2.222219843214978396e-01 // 0x3FCC71C51D8E78AF +#define L5 1.818357216161805012e-01 // 0x3FC7466496CB03DE +#define L6 1.531383769920937332e-01 // 0x3FC39A09D078C69F +#define L7 1.479819860511658591e-01 // 0x3FC2F112DF3E5244 +#define NaN 0x7FF8000000000001 +#define NegInf 0xFFF0000000000000 +#define PosInf 0x7FF0000000000000 + +// func Log(x float64) float64 +TEXT ·archLog(SB),NOSPLIT,$0 + // test bits for special cases + MOVQ x+0(FP), BX + MOVQ $~(1<<63), AX // sign bit mask + ANDQ BX, AX + JEQ isZero + MOVQ $0, AX + CMPQ AX, BX + JGT isNegative + MOVQ $PosInf, AX + CMPQ AX, BX + JLE isInfOrNaN + // f1, ki := math.Frexp(x); k := float64(ki) + MOVQ BX, X0 + MOVQ $0x000FFFFFFFFFFFFF, AX + MOVQ AX, X2 + ANDPD X0, X2 + MOVSD $0.5, X0 // 0x3FE0000000000000 + ORPD X0, X2 // X2= f1 + SHRQ $52, BX + ANDL $0x7FF, BX + SUBL $0x3FE, BX + XORPS X1, X1 // break dependency for CVTSL2SD + CVTSL2SD BX, X1 // x1= k, x2= f1 + // if f1 < math.Sqrt2/2 { k -= 1; f1 *= 2 } + MOVSD $HSqrt2, X0 // x0= 0.7071, x1= k, x2= f1 + CMPSD X2, X0, 5 // cmpnlt; x0= 0 or ^0, x1= k, x2 = f1 + MOVSD $1.0, X3 // x0= 0 or ^0, x1= k, x2 = f1, x3= 1 + ANDPD X0, X3 // x0= 0 or ^0, x1= k, x2 = f1, x3= 0 or 1 + SUBSD X3, X1 // x0= 0 or ^0, x1= k, x2 = f1, x3= 0 or 1 + MOVSD $1.0, X0 // x0= 1, x1= k, x2= f1, x3= 0 or 1 + ADDSD X0, X3 // x0= 1, x1= k, x2= f1, x3= 1 or 2 + MULSD X3, X2 // x0= 1, x1= k, x2= f1 + // f := f1 - 1 + SUBSD X0, X2 // x1= k, x2= f + // s := f / (2 + f) + MOVSD $2.0, X0 + ADDSD X2, X0 + MOVAPD X2, X3 + DIVSD X0, X3 // x1=k, x2= f, x3= s + // s2 := s * s + MOVAPD X3, X4 // x1= k, x2= f, x3= s + MULSD X4, X4 // x1= k, x2= f, x3= s, x4= s2 + // s4 := s2 * s2 + MOVAPD X4, X5 // x1= k, x2= f, x3= s, x4= s2 + MULSD X5, X5 // x1= k, x2= f, x3= s, x4= s2, x5= s4 + // t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7))) + MOVSD $L7, X6 + MULSD X5, X6 + ADDSD $L5, X6 + MULSD X5, X6 + ADDSD $L3, X6 + MULSD X5, X6 + ADDSD $L1, X6 + MULSD X6, X4 // x1= k, x2= f, x3= s, x4= t1, x5= s4 + // t2 := s4 * (L2 + s4*(L4+s4*L6)) + MOVSD $L6, X6 + MULSD X5, X6 + ADDSD $L4, X6 + MULSD X5, X6 + ADDSD $L2, X6 + MULSD X6, X5 // x1= k, x2= f, x3= s, x4= t1, x5= t2 + // R := t1 + t2 + ADDSD X5, X4 // x1= k, x2= f, x3= s, x4= R + // hfsq := 0.5 * f * f + MOVSD $0.5, X0 + MULSD X2, X0 + MULSD X2, X0 // x0= hfsq, x1= k, x2= f, x3= s, x4= R + // return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f) + ADDSD X0, X4 // x0= hfsq, x1= k, x2= f, x3= s, x4= hfsq+R + MULSD X4, X3 // x0= hfsq, x1= k, x2= f, x3= s*(hfsq+R) + MOVSD $Ln2Lo, X4 + MULSD X1, X4 // x4= k*Ln2Lo + ADDSD X4, X3 // x0= hfsq, x1= k, x2= f, x3= s*(hfsq+R)+k*Ln2Lo + SUBSD X3, X0 // x0= hfsq-(s*(hfsq+R)+k*Ln2Lo), x1= k, x2= f + SUBSD X2, X0 // x0= (hfsq-(s*(hfsq+R)+k*Ln2Lo))-f, x1= k + MULSD $Ln2Hi, X1 // x0= (hfsq-(s*(hfsq+R)+k*Ln2Lo))-f, x1= k*Ln2Hi + SUBSD X0, X1 // x1= k*Ln2Hi-((hfsq-(s*(hfsq+R)+k*Ln2Lo))-f) + MOVSD X1, ret+8(FP) + RET +isInfOrNaN: + MOVQ BX, ret+8(FP) // +Inf or NaN, return x + RET +isNegative: + MOVQ $NaN, AX + MOVQ AX, ret+8(FP) // return NaN + RET +isZero: + MOVQ $NegInf, AX + MOVQ AX, ret+8(FP) // return -Inf + RET diff --git a/go/src/math/log_asm.go b/go/src/math/log_asm.go new file mode 100644 index 0000000000000000000000000000000000000000..848cce13b289b52e37c8f08e9c3d6d0c149831d7 --- /dev/null +++ b/go/src/math/log_asm.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build amd64 || s390x + +package math + +const haveArchLog = true + +func archLog(x float64) float64 diff --git a/go/src/math/log_s390x.s b/go/src/math/log_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..215d7a03a7509f8a2739431f2d6fb1e0832fe428 --- /dev/null +++ b/go/src/math/log_s390x.s @@ -0,0 +1,168 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial approximations +DATA ·logrodataL21<> + 0(SB)/8, $-.499999999999999778E+00 +DATA ·logrodataL21<> + 8(SB)/8, $0.333333333333343751E+00 +DATA ·logrodataL21<> + 16(SB)/8, $-.250000000001606881E+00 +DATA ·logrodataL21<> + 24(SB)/8, $0.199999999971603032E+00 +DATA ·logrodataL21<> + 32(SB)/8, $-.166666663114122038E+00 +DATA ·logrodataL21<> + 40(SB)/8, $-.125002923782692399E+00 +DATA ·logrodataL21<> + 48(SB)/8, $0.111142014580396256E+00 +DATA ·logrodataL21<> + 56(SB)/8, $0.759438932618934220E-01 +DATA ·logrodataL21<> + 64(SB)/8, $0.142857144267212549E+00 +DATA ·logrodataL21<> + 72(SB)/8, $-.993038938793590759E-01 +DATA ·logrodataL21<> + 80(SB)/8, $-1.0 +GLOBL ·logrodataL21<> + 0(SB), RODATA, $88 + +// Constants +DATA ·logxminf<> + 0(SB)/8, $0xfff0000000000000 +GLOBL ·logxminf<> + 0(SB), RODATA, $8 +DATA ·logxnan<> + 0(SB)/8, $0x7ff8000000000000 +GLOBL ·logxnan<> + 0(SB), RODATA, $8 +DATA ·logx43f<> + 0(SB)/8, $0x43f0000000000000 +GLOBL ·logx43f<> + 0(SB), RODATA, $8 +DATA ·logxl2<> + 0(SB)/8, $0x3fda7aecbeba4e46 +GLOBL ·logxl2<> + 0(SB), RODATA, $8 +DATA ·logxl1<> + 0(SB)/8, $0x3ffacde700000000 +GLOBL ·logxl1<> + 0(SB), RODATA, $8 + +/* Input transform scale and add constants */ +DATA ·logxm<> + 0(SB)/8, $0x3fc77604e63c84b1 +DATA ·logxm<> + 8(SB)/8, $0x40fb39456ab53250 +DATA ·logxm<> + 16(SB)/8, $0x3fc9ee358b945f3f +DATA ·logxm<> + 24(SB)/8, $0x40fb39418bf3b137 +DATA ·logxm<> + 32(SB)/8, $0x3fccfb2e1304f4b6 +DATA ·logxm<> + 40(SB)/8, $0x40fb393d3eda3022 +DATA ·logxm<> + 48(SB)/8, $0x3fd0000000000000 +DATA ·logxm<> + 56(SB)/8, $0x40fb393969e70000 +DATA ·logxm<> + 64(SB)/8, $0x3fd11117aafbfe04 +DATA ·logxm<> + 72(SB)/8, $0x40fb3936eaefafcf +DATA ·logxm<> + 80(SB)/8, $0x3fd2492af5e658b2 +DATA ·logxm<> + 88(SB)/8, $0x40fb39343ff01715 +DATA ·logxm<> + 96(SB)/8, $0x3fd3b50c622a43dd +DATA ·logxm<> + 104(SB)/8, $0x40fb39315adae2f3 +DATA ·logxm<> + 112(SB)/8, $0x3fd56bbeea918777 +DATA ·logxm<> + 120(SB)/8, $0x40fb392e21698552 +GLOBL ·logxm<> + 0(SB), RODATA, $128 + +// Log returns the natural logarithm of the argument. +// +// Special cases are: +// Log(+Inf) = +Inf +// Log(0) = -Inf +// Log(x < 0) = NaN +// Log(NaN) = NaN +// The algorithm used is minimax polynomial approximation using a table of +// polynomial coefficients determined with a Remez exchange algorithm. + +TEXT ·logAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + MOVD $·logrodataL21<>+0(SB), R9 + MOVH $0x8006, R4 + LGDR F0, R1 + MOVD $0x3FF0000000000000, R6 + SRAD $48, R1, R1 + MOVD $0x40F03E8000000000, R8 + SUBW R1, R4 + RISBGZ $32, $59, $0, R4, R2 + RISBGN $0, $15, $48, R2, R6 + RISBGN $16, $31, $32, R2, R8 + MOVW R1, R7 + CMPBGT R7, $22, L17 + LTDBR F0, F0 + MOVD $·logx43f<>+0(SB), R1 + FMOVD 0(R1), F2 + BLEU L3 + MOVH $0x8005, R12 + MOVH $0x8405, R0 + BR L15 +L7: + LTDBR F0, F0 + BLEU L3 +L15: + FMUL F2, F0 + LGDR F0, R1 + SRAD $48, R1, R1 + SUBW R1, R0, R2 + SUBW R1, R12, R3 + BYTE $0x18 //lr %r4,%r2 + BYTE $0x42 + ANDW $0xFFFFFFF0, R3 + ANDW $0xFFFFFFF0, R2 + BYTE $0x18 //lr %r5,%r1 + BYTE $0x51 + MOVW R1, R7 + CMPBLE R7, $22, L7 + RISBGN $0, $15, $48, R3, R6 + RISBGN $16, $31, $32, R2, R8 +L2: + MOVH R5, R5 + MOVH $0x7FEF, R1 + CMPW R5, R1 + BGT L1 + LDGR R6, F2 + FMUL F2, F0 + RISBGZ $57, $59, $3, R4, R4 + FMOVD 80(R9), F2 + MOVD $·logxm<>+0(SB), R7 + ADD R7, R4 + FMOVD 72(R9), F4 + WORD $0xED004000 //madb %f2,%f0,0(%r4) + BYTE $0x20 + BYTE $0x1E + FMOVD 64(R9), F1 + FMOVD F2, F0 + FMOVD 56(R9), F2 + WFMADB V0, V2, V4, V2 + WFMDB V0, V0, V6 + FMOVD 48(R9), F4 + WFMADB V0, V2, V4, V2 + FMOVD 40(R9), F4 + WFMADB V2, V6, V1, V2 + FMOVD 32(R9), F1 + WFMADB V6, V4, V1, V4 + FMOVD 24(R9), F1 + WFMADB V6, V2, V1, V2 + FMOVD 16(R9), F1 + WFMADB V6, V4, V1, V4 + MOVD $·logxl1<>+0(SB), R1 + FMOVD 8(R9), F1 + WFMADB V6, V2, V1, V2 + FMOVD 0(R9), F1 + WFMADB V6, V4, V1, V4 + FMOVD 8(R4), F1 + WFMADB V0, V2, V4, V2 + LDGR R8, F4 + WFMADB V6, V2, V0, V2 + WORD $0xED401000 //msdb %f1,%f4,0(%r1) + BYTE $0x10 + BYTE $0x1F + MOVD ·logxl2<>+0(SB), R1 + LCDBR F1, F0 + LDGR R1, F4 + WFMADB V0, V4, V2, V0 +L1: + FMOVD F0, ret+8(FP) + RET +L3: + LTDBR F0, F0 + BEQ L20 + BGE L1 + BVS L1 + + MOVD $·logxnan<>+0(SB), R1 + FMOVD 0(R1), F0 + BR L1 +L20: + MOVD $·logxminf<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET +L17: + BYTE $0x18 //lr %r5,%r1 + BYTE $0x51 + BR L2 diff --git a/go/src/math/log_stub.go b/go/src/math/log_stub.go new file mode 100644 index 0000000000000000000000000000000000000000..d35992bf37ab69227a4afe49a21cef7e37d0fc30 --- /dev/null +++ b/go/src/math/log_stub.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !amd64 && !s390x + +package math + +const haveArchLog = false + +func archLog(x float64) float64 { + panic("not implemented") +} diff --git a/go/src/math/logb.go b/go/src/math/logb.go new file mode 100644 index 0000000000000000000000000000000000000000..1a46464127cc886aa78ad825c075fda4eab05614 --- /dev/null +++ b/go/src/math/logb.go @@ -0,0 +1,52 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Logb returns the binary exponent of x. +// +// Special cases are: +// +// Logb(±Inf) = +Inf +// Logb(0) = -Inf +// Logb(NaN) = NaN +func Logb(x float64) float64 { + // special cases + switch { + case x == 0: + return Inf(-1) + case IsInf(x, 0): + return Inf(1) + case IsNaN(x): + return x + } + return float64(ilogb(x)) +} + +// Ilogb returns the binary exponent of x as an integer. +// +// Special cases are: +// +// Ilogb(±Inf) = MaxInt32 +// Ilogb(0) = MinInt32 +// Ilogb(NaN) = MaxInt32 +func Ilogb(x float64) int { + // special cases + switch { + case x == 0: + return MinInt32 + case IsNaN(x): + return MaxInt32 + case IsInf(x, 0): + return MaxInt32 + } + return ilogb(x) +} + +// ilogb returns the binary exponent of x. It assumes x is finite and +// non-zero. +func ilogb(x float64) int { + x, exp := normalize(x) + return int((Float64bits(x)>>shift)&mask) - bias + exp +} diff --git a/go/src/math/mod.go b/go/src/math/mod.go new file mode 100644 index 0000000000000000000000000000000000000000..6f24250cfb461265fa51362c7ccc140c559abfc7 --- /dev/null +++ b/go/src/math/mod.go @@ -0,0 +1,52 @@ +// Copyright 2009-2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point mod function. +*/ + +// Mod returns the floating-point remainder of x/y. +// The magnitude of the result is less than y and its +// sign agrees with that of x. +// +// Special cases are: +// +// Mod(±Inf, y) = NaN +// Mod(NaN, y) = NaN +// Mod(x, 0) = NaN +// Mod(x, ±Inf) = x +// Mod(x, NaN) = NaN +func Mod(x, y float64) float64 { + if haveArchMod { + return archMod(x, y) + } + return mod(x, y) +} + +func mod(x, y float64) float64 { + if y == 0 || IsInf(x, 0) || IsNaN(x) || IsNaN(y) { + return NaN() + } + y = Abs(y) + + yfr, yexp := Frexp(y) + r := x + if x < 0 { + r = -x + } + + for r >= y { + rfr, rexp := Frexp(r) + if rfr < yfr { + rexp = rexp - 1 + } + r = r - Ldexp(y, rexp-yexp) + } + if x < 0 { + r = -r + } + return r +} diff --git a/go/src/math/modf.go b/go/src/math/modf.go new file mode 100644 index 0000000000000000000000000000000000000000..12630958e969b7a820016d4b005216ebcb515486 --- /dev/null +++ b/go/src/math/modf.go @@ -0,0 +1,18 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Modf returns integer and fractional floating-point numbers +// that sum to f. Both values have the same sign as f. +// +// Special cases are: +// +// Modf(±Inf) = ±Inf, NaN +// Modf(NaN) = NaN, NaN +func Modf(f float64) (integer float64, fractional float64) { + integer = Trunc(f) + fractional = Copysign(f-integer, f) + return +} diff --git a/go/src/math/nextafter.go b/go/src/math/nextafter.go new file mode 100644 index 0000000000000000000000000000000000000000..ec18d542d9c0371d0b69831971faa415ab0f216c --- /dev/null +++ b/go/src/math/nextafter.go @@ -0,0 +1,51 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Nextafter32 returns the next representable float32 value after x towards y. +// +// Special cases are: +// +// Nextafter32(x, x) = x +// Nextafter32(NaN, y) = NaN +// Nextafter32(x, NaN) = NaN +func Nextafter32(x, y float32) (r float32) { + switch { + case IsNaN(float64(x)) || IsNaN(float64(y)): // special case + r = float32(NaN()) + case x == y: + r = x + case x == 0: + r = float32(Copysign(float64(Float32frombits(1)), float64(y))) + case (y > x) == (x > 0): + r = Float32frombits(Float32bits(x) + 1) + default: + r = Float32frombits(Float32bits(x) - 1) + } + return +} + +// Nextafter returns the next representable float64 value after x towards y. +// +// Special cases are: +// +// Nextafter(x, x) = x +// Nextafter(NaN, y) = NaN +// Nextafter(x, NaN) = NaN +func Nextafter(x, y float64) (r float64) { + switch { + case IsNaN(x) || IsNaN(y): // special case + r = NaN() + case x == y: + r = x + case x == 0: + r = Copysign(Float64frombits(1), y) + case (y > x) == (x > 0): + r = Float64frombits(Float64bits(x) + 1) + default: + r = Float64frombits(Float64bits(x) - 1) + } + return +} diff --git a/go/src/math/pow.go b/go/src/math/pow.go new file mode 100644 index 0000000000000000000000000000000000000000..3f42945376d3fac2888d27cfe848ffecdf3abfdc --- /dev/null +++ b/go/src/math/pow.go @@ -0,0 +1,166 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +func isOddInt(x float64) bool { + if Abs(x) >= (1 << 53) { + // 1 << 53 is the largest exact integer in the float64 format. + // Any number outside this range will be truncated before the decimal point and therefore will always be + // an even integer. + // Without this check and if x overflows int64 the int64(xi) conversion below may produce incorrect results + // on some architectures (and does so on arm64). See issue #57465. + return false + } + + xi, xf := Modf(x) + return xf == 0 && int64(xi)&1 == 1 +} + +// Special cases taken from FreeBSD's /usr/src/lib/msun/src/e_pow.c +// updated by IEEE Std. 754-2008 "Section 9.2.1 Special values". + +// Pow returns x**y, the base-x exponential of y. +// +// Special cases are (in order): +// +// Pow(x, ±0) = 1 for any x +// Pow(1, y) = 1 for any y +// Pow(x, 1) = x for any x +// Pow(NaN, y) = NaN +// Pow(x, NaN) = NaN +// Pow(±0, y) = ±Inf for y an odd integer < 0 +// Pow(±0, -Inf) = +Inf +// Pow(±0, +Inf) = +0 +// Pow(±0, y) = +Inf for finite y < 0 and not an odd integer +// Pow(±0, y) = ±0 for y an odd integer > 0 +// Pow(±0, y) = +0 for finite y > 0 and not an odd integer +// Pow(-1, ±Inf) = 1 +// Pow(x, +Inf) = +Inf for |x| > 1 +// Pow(x, -Inf) = +0 for |x| > 1 +// Pow(x, +Inf) = +0 for |x| < 1 +// Pow(x, -Inf) = +Inf for |x| < 1 +// Pow(+Inf, y) = +Inf for y > 0 +// Pow(+Inf, y) = +0 for y < 0 +// Pow(-Inf, y) = Pow(-0, -y) +// Pow(x, y) = NaN for finite x < 0 and finite non-integer y +func Pow(x, y float64) float64 { + if haveArchPow { + return archPow(x, y) + } + return pow(x, y) +} + +func pow(x, y float64) float64 { + switch { + case y == 0 || x == 1: + return 1 + case y == 1: + return x + case IsNaN(x) || IsNaN(y): + return NaN() + case x == 0: + switch { + case y < 0: + if Signbit(x) && isOddInt(y) { + return Inf(-1) + } + return Inf(1) + case y > 0: + if Signbit(x) && isOddInt(y) { + return x + } + return 0 + } + case IsInf(y, 0): + switch { + case x == -1: + return 1 + case (Abs(x) < 1) == IsInf(y, 1): + return 0 + default: + return Inf(1) + } + case IsInf(x, 0): + if IsInf(x, -1) { + return Pow(1/x, -y) // Pow(-0, -y) + } + switch { + case y < 0: + return 0 + case y > 0: + return Inf(1) + } + case y == 0.5: + return Sqrt(x) + case y == -0.5: + return 1 / Sqrt(x) + } + + yi, yf := Modf(Abs(y)) + if yf != 0 && x < 0 { + return NaN() + } + if yi >= 1<<63 { + // yi is a large even int that will lead to overflow (or underflow to 0) + // for all x except -1 (x == 1 was handled earlier) + switch { + case x == -1: + return 1 + case (Abs(x) < 1) == (y > 0): + return 0 + default: + return Inf(1) + } + } + + // ans = a1 * 2**ae (= 1 for now). + a1 := 1.0 + ae := 0 + + // ans *= x**yf + if yf != 0 { + if yf > 0.5 { + yf-- + yi++ + } + a1 = Exp(yf * Log(x)) + } + + // ans *= x**yi + // by multiplying in successive squarings + // of x according to bits of yi. + // accumulate powers of two into exp. + x1, xe := Frexp(x) + for i := int64(yi); i != 0; i >>= 1 { + if xe < -1<<12 || 1<<12 < xe { + // catch xe before it overflows the left shift below + // Since i !=0 it has at least one bit still set, so ae will accumulate xe + // on at least one more iteration, ae += xe is a lower bound on ae + // the lower bound on ae exceeds the size of a float64 exp + // so the final call to Ldexp will produce under/overflow (0/Inf) + ae += xe + break + } + if i&1 == 1 { + a1 *= x1 + ae += xe + } + x1 *= x1 + xe <<= 1 + if x1 < .5 { + x1 += x1 + xe-- + } + } + + // ans = a1*2**ae + // if y < 0 { ans = 1 / ans } + // but in the opposite order + if y < 0 { + a1 = 1 / a1 + ae = -ae + } + return Ldexp(a1, ae) +} diff --git a/go/src/math/pow10.go b/go/src/math/pow10.go new file mode 100644 index 0000000000000000000000000000000000000000..c31ad8dbc778fe5dbd2a676645019b7ac0e91974 --- /dev/null +++ b/go/src/math/pow10.go @@ -0,0 +1,47 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// pow10tab stores the pre-computed values 10**i for i < 32. +var pow10tab = [...]float64{ + 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + 1e20, 1e21, 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28, 1e29, + 1e30, 1e31, +} + +// pow10postab32 stores the pre-computed value for 10**(i*32) at index i. +var pow10postab32 = [...]float64{ + 1e00, 1e32, 1e64, 1e96, 1e128, 1e160, 1e192, 1e224, 1e256, 1e288, +} + +// pow10negtab32 stores the pre-computed value for 10**(-i*32) at index i. +var pow10negtab32 = [...]float64{ + 1e-00, 1e-32, 1e-64, 1e-96, 1e-128, 1e-160, 1e-192, 1e-224, 1e-256, 1e-288, 1e-320, +} + +// Pow10 returns 10**n, the base-10 exponential of n. +// +// Special cases are: +// +// Pow10(n) = 0 for n < -323 +// Pow10(n) = +Inf for n > 308 +func Pow10(n int) float64 { + if 0 <= n && n <= 308 { + return pow10postab32[uint(n)/32] * pow10tab[uint(n)%32] + } + + if -323 <= n && n <= 0 { + return pow10negtab32[uint(-n)/32] / pow10tab[uint(-n)%32] + } + + // n < -323 || 308 < n + if n > 0 { + return Inf(1) + } + + // n < -323 + return 0 +} diff --git a/go/src/math/pow_s390x.s b/go/src/math/pow_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..97cd48d96ec85008138c877c0ebadc0172690f53 --- /dev/null +++ b/go/src/math/pow_s390x.s @@ -0,0 +1,634 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define PosInf 0x7FF0000000000000 +#define NaN 0x7FF8000000000001 +#define NegInf 0xFFF0000000000000 +#define PosOne 0x3FF0000000000000 +#define NegOne 0xBFF0000000000000 +#define NegZero 0x8000000000000000 + +// Minimax polynomial approximation +DATA ·powrodataL51<> + 0(SB)/8, $-1.0 +DATA ·powrodataL51<> + 8(SB)/8, $1.0 +DATA ·powrodataL51<> + 16(SB)/8, $0.24022650695910110361E+00 +DATA ·powrodataL51<> + 24(SB)/8, $0.69314718055994686185E+00 +DATA ·powrodataL51<> + 32(SB)/8, $0.96181291057109484809E-02 +DATA ·powrodataL51<> + 40(SB)/8, $0.15403814778342868389E-03 +DATA ·powrodataL51<> + 48(SB)/8, $0.55504108652095235601E-01 +DATA ·powrodataL51<> + 56(SB)/8, $0.13333818813168698658E-02 +DATA ·powrodataL51<> + 64(SB)/8, $0.68205322933914439200E-12 +DATA ·powrodataL51<> + 72(SB)/8, $-.18466496523378731640E-01 +DATA ·powrodataL51<> + 80(SB)/8, $0.19697596291603973706E-02 +DATA ·powrodataL51<> + 88(SB)/8, $0.23083120654155209200E+00 +DATA ·powrodataL51<> + 96(SB)/8, $0.55324356012093416771E-06 +DATA ·powrodataL51<> + 104(SB)/8, $-.40340677224649339048E-05 +DATA ·powrodataL51<> + 112(SB)/8, $0.30255507904062541562E-04 +DATA ·powrodataL51<> + 120(SB)/8, $-.77453979912413008787E-07 +DATA ·powrodataL51<> + 128(SB)/8, $-.23637115549923464737E-03 +DATA ·powrodataL51<> + 136(SB)/8, $0.11016119077267717198E-07 +DATA ·powrodataL51<> + 144(SB)/8, $0.22608272174486123035E-09 +DATA ·powrodataL51<> + 152(SB)/8, $-.15895808101370190382E-08 +DATA ·powrodataL51<> + 160(SB)/8, $0x4540190000000000 +GLOBL ·powrodataL51<> + 0(SB), RODATA, $168 + +// Constants +DATA ·pow_x001a<> + 0(SB)/8, $0x1a000000000000 +GLOBL ·pow_x001a<> + 0(SB), RODATA, $8 +DATA ·pow_xinf<> + 0(SB)/8, $0x7ff0000000000000 //+Inf +GLOBL ·pow_xinf<> + 0(SB), RODATA, $8 +DATA ·pow_xnan<> + 0(SB)/8, $0x7ff8000000000000 //NaN +GLOBL ·pow_xnan<> + 0(SB), RODATA, $8 +DATA ·pow_x434<> + 0(SB)/8, $0x4340000000000000 +GLOBL ·pow_x434<> + 0(SB), RODATA, $8 +DATA ·pow_x433<> + 0(SB)/8, $0x4330000000000000 +GLOBL ·pow_x433<> + 0(SB), RODATA, $8 +DATA ·pow_x43f<> + 0(SB)/8, $0x43f0000000000000 +GLOBL ·pow_x43f<> + 0(SB), RODATA, $8 +DATA ·pow_xadd<> + 0(SB)/8, $0xc2f0000100003fef +GLOBL ·pow_xadd<> + 0(SB), RODATA, $8 +DATA ·pow_xa<> + 0(SB)/8, $0x4019000000000000 +GLOBL ·pow_xa<> + 0(SB), RODATA, $8 + +// Scale correction tables +DATA powiadd<> + 0(SB)/8, $0xf000000000000000 +DATA powiadd<> + 8(SB)/8, $0x1000000000000000 +GLOBL powiadd<> + 0(SB), RODATA, $16 +DATA powxscale<> + 0(SB)/8, $0x4ff0000000000000 +DATA powxscale<> + 8(SB)/8, $0x2ff0000000000000 +GLOBL powxscale<> + 0(SB), RODATA, $16 + +// Fractional powers of 2 table +DATA ·powtexp<> + 0(SB)/8, $0.442737824274138381E-01 +DATA ·powtexp<> + 8(SB)/8, $0.263602189790660309E-01 +DATA ·powtexp<> + 16(SB)/8, $0.122565642281703586E-01 +DATA ·powtexp<> + 24(SB)/8, $0.143757052860721398E-02 +DATA ·powtexp<> + 32(SB)/8, $-.651375034121276075E-02 +DATA ·powtexp<> + 40(SB)/8, $-.119317678849450159E-01 +DATA ·powtexp<> + 48(SB)/8, $-.150868749549871069E-01 +DATA ·powtexp<> + 56(SB)/8, $-.161992609578469234E-01 +DATA ·powtexp<> + 64(SB)/8, $-.154492360403337917E-01 +DATA ·powtexp<> + 72(SB)/8, $-.129850717389178721E-01 +DATA ·powtexp<> + 80(SB)/8, $-.892902649276657891E-02 +DATA ·powtexp<> + 88(SB)/8, $-.338202636596794887E-02 +DATA ·powtexp<> + 96(SB)/8, $0.357266307045684762E-02 +DATA ·powtexp<> + 104(SB)/8, $0.118665304327406698E-01 +DATA ·powtexp<> + 112(SB)/8, $0.214434994118118914E-01 +DATA ·powtexp<> + 120(SB)/8, $0.322580645161290314E-01 +GLOBL ·powtexp<> + 0(SB), RODATA, $128 + +// Log multiplier tables +DATA ·powtl<> + 0(SB)/8, $0xbdf9723a80db6a05 +DATA ·powtl<> + 8(SB)/8, $0x3e0cfe4a0babe862 +DATA ·powtl<> + 16(SB)/8, $0xbe163b42dd33dada +DATA ·powtl<> + 24(SB)/8, $0xbe0cdf9de2a8429c +DATA ·powtl<> + 32(SB)/8, $0xbde9723a80db6a05 +DATA ·powtl<> + 40(SB)/8, $0xbdb37fcae081745e +DATA ·powtl<> + 48(SB)/8, $0xbdd8b2f901ac662c +DATA ·powtl<> + 56(SB)/8, $0xbde867dc68c36cc9 +DATA ·powtl<> + 64(SB)/8, $0xbdd23e36b47256b7 +DATA ·powtl<> + 72(SB)/8, $0xbde4c9b89fcc7933 +DATA ·powtl<> + 80(SB)/8, $0xbdd16905cad7cf66 +DATA ·powtl<> + 88(SB)/8, $0x3ddb417414aa5529 +DATA ·powtl<> + 96(SB)/8, $0xbdce046f2889983c +DATA ·powtl<> + 104(SB)/8, $0x3dc2c3865d072897 +DATA ·powtl<> + 112(SB)/8, $0x8000000000000000 +DATA ·powtl<> + 120(SB)/8, $0x3dc1ca48817f8afe +DATA ·powtl<> + 128(SB)/8, $0xbdd703518a88bfb7 +DATA ·powtl<> + 136(SB)/8, $0x3dc64afcc46942ce +DATA ·powtl<> + 144(SB)/8, $0xbd9d79191389891a +DATA ·powtl<> + 152(SB)/8, $0x3ddd563044da4fa0 +DATA ·powtl<> + 160(SB)/8, $0x3e0f42b5e5f8f4b6 +DATA ·powtl<> + 168(SB)/8, $0x3e0dfa2c2cbf6ead +DATA ·powtl<> + 176(SB)/8, $0x3e14e25e91661293 +DATA ·powtl<> + 184(SB)/8, $0x3e0aac461509e20c +GLOBL ·powtl<> + 0(SB), RODATA, $192 + +DATA ·powtm<> + 0(SB)/8, $0x3da69e13 +DATA ·powtm<> + 8(SB)/8, $0x100003d66fcb6 +DATA ·powtm<> + 16(SB)/8, $0x200003d1538df +DATA ·powtm<> + 24(SB)/8, $0x300003cab729e +DATA ·powtm<> + 32(SB)/8, $0x400003c1a784c +DATA ·powtm<> + 40(SB)/8, $0x500003ac9b074 +DATA ·powtm<> + 48(SB)/8, $0x60000bb498d22 +DATA ·powtm<> + 56(SB)/8, $0x68000bb8b29a2 +DATA ·powtm<> + 64(SB)/8, $0x70000bb9a32d4 +DATA ·powtm<> + 72(SB)/8, $0x74000bb9946bb +DATA ·powtm<> + 80(SB)/8, $0x78000bb92e34b +DATA ·powtm<> + 88(SB)/8, $0x80000bb6c57dc +DATA ·powtm<> + 96(SB)/8, $0x84000bb4020f7 +DATA ·powtm<> + 104(SB)/8, $0x8c000ba93832d +DATA ·powtm<> + 112(SB)/8, $0x9000080000000 +DATA ·powtm<> + 120(SB)/8, $0x940003aa66c4c +DATA ·powtm<> + 128(SB)/8, $0x980003b2fb12a +DATA ·powtm<> + 136(SB)/8, $0xa00003bc1def6 +DATA ·powtm<> + 144(SB)/8, $0xa80003c1eb0eb +DATA ·powtm<> + 152(SB)/8, $0xb00003c64dcec +DATA ·powtm<> + 160(SB)/8, $0xc00003cc49e4e +DATA ·powtm<> + 168(SB)/8, $0xd00003d12f1de +DATA ·powtm<> + 176(SB)/8, $0xe00003d4a9c6f +DATA ·powtm<> + 184(SB)/8, $0xf00003d846c66 +GLOBL ·powtm<> + 0(SB), RODATA, $192 + +// Table of indices into multiplier tables +// Adjusted from asm to remove offset and convert +DATA ·powtabi<> + 0(SB)/8, $0x1010101 +DATA ·powtabi<> + 8(SB)/8, $0x101020202020203 +DATA ·powtabi<> + 16(SB)/8, $0x303030404040405 +DATA ·powtabi<> + 24(SB)/8, $0x505050606060708 +DATA ·powtabi<> + 32(SB)/8, $0x90a0b0c0d0e0f10 +DATA ·powtabi<> + 40(SB)/8, $0x1011111212121313 +DATA ·powtabi<> + 48(SB)/8, $0x1314141414151515 +DATA ·powtabi<> + 56(SB)/8, $0x1516161617171717 +GLOBL ·powtabi<> + 0(SB), RODATA, $64 + +// Pow returns x**y, the base-x exponential of y. +// +// Special cases are (in order): +// Pow(x, ±0) = 1 for any x +// Pow(1, y) = 1 for any y +// Pow(x, 1) = x for any x +// Pow(NaN, y) = NaN +// Pow(x, NaN) = NaN +// Pow(±0, y) = ±Inf for y an odd integer < 0 +// Pow(±0, -Inf) = +Inf +// Pow(±0, +Inf) = +0 +// Pow(±0, y) = +Inf for finite y < 0 and not an odd integer +// Pow(±0, y) = ±0 for y an odd integer > 0 +// Pow(±0, y) = +0 for finite y > 0 and not an odd integer +// Pow(-1, ±Inf) = 1 +// Pow(x, +Inf) = +Inf for |x| > 1 +// Pow(x, -Inf) = +0 for |x| > 1 +// Pow(x, +Inf) = +0 for |x| < 1 +// Pow(x, -Inf) = +Inf for |x| < 1 +// Pow(+Inf, y) = +Inf for y > 0 +// Pow(+Inf, y) = +0 for y < 0 +// Pow(-Inf, y) = Pow(-0, -y) +// Pow(x, y) = NaN for finite x < 0 and finite non-integer y + +TEXT ·powAsm(SB), NOSPLIT, $0-24 + // special case + MOVD x+0(FP), R1 + MOVD y+8(FP), R2 + + // special case Pow(1, y) = 1 for any y + MOVD $PosOne, R3 + CMPUBEQ R1, R3, xIsOne + + // special case Pow(x, 1) = x for any x + MOVD $PosOne, R4 + CMPUBEQ R2, R4, yIsOne + + // special case Pow(x, NaN) = NaN for any x + MOVD $~(1<<63), R5 + AND R2, R5 // y = |y| + MOVD $PosInf, R4 + CMPUBLT R4, R5, yIsNan + + MOVD $NegInf, R3 + CMPUBEQ R1, R3, xIsNegInf + + MOVD $NegOne, R3 + CMPUBEQ R1, R3, xIsNegOne + + MOVD $PosInf, R3 + CMPUBEQ R1, R3, xIsPosInf + + MOVD $NegZero, R3 + CMPUBEQ R1, R3, xIsNegZero + + MOVD $PosInf, R4 + CMPUBEQ R2, R4, yIsPosInf + + MOVD $0x0, R3 + CMPUBEQ R1, R3, xIsPosZero + CMPBLT R1, R3, xLtZero + BR Normal +xIsPosInf: + // special case Pow(+Inf, y) = +Inf for y > 0 + MOVD $0x0, R4 + CMPBGT R2, R4, posInfGeZero + BR Normal +xIsNegInf: + //Pow(-Inf, y) = Pow(-0, -y) + FMOVD y+8(FP), F2 + FNEG F2, F2 // y = -y + BR negZeroNegY // call Pow(-0, -y) +xIsNegOne: + // special case Pow(-1, ±Inf) = 1 + MOVD $PosInf, R4 + CMPUBEQ R2, R4, negOnePosInf + MOVD $NegInf, R4 + CMPUBEQ R2, R4, negOneNegInf + BR Normal +xIsPosZero: + // special case Pow(+0, -Inf) = +Inf + MOVD $NegInf, R4 + CMPUBEQ R2, R4, zeroNegInf + + // special case Pow(+0, y < 0) = +Inf + FMOVD y+8(FP), F2 + FMOVD $(0.0), F4 + FCMPU F2, F4 + BLT posZeroLtZero //y < 0.0 + BR Normal +xIsNegZero: + // special case Pow(-0, -Inf) = +Inf + MOVD $NegInf, R4 + CMPUBEQ R2, R4, zeroNegInf + FMOVD y+8(FP), F2 +negZeroNegY: + // special case Pow(x, ±0) = 1 for any x + FMOVD $(0.0), F4 + FCMPU F4, F2 + BLT negZeroGtZero // y > 0.0 + BEQ yIsZero // y = 0.0 + + FMOVD $(-0.0), F4 + FCMPU F4, F2 + BLT negZeroGtZero // y > -0.0 + BEQ yIsZero // y = -0.0 + + // special case Pow(-0, y) = -Inf for y an odd integer < 0 + // special case Pow(-0, y) = +Inf for finite y < 0 and not an odd integer + FIDBR $5, F2, F4 //F2 translate to integer F4 + FCMPU F2, F4 + BNE zeroNotOdd // y is not an (odd) integer and y < 0 + FMOVD $(2.0), F4 + FDIV F4, F2 // F2 = F2 / 2.0 + FIDBR $5, F2, F4 //F2 translate to integer F4 + FCMPU F2, F4 + BNE negZeroOddInt // y is an odd integer and y < 0 + BR zeroNotOdd // y is not an (odd) integer and y < 0 + +negZeroGtZero: + // special case Pow(-0, y) = -0 for y an odd integer > 0 + // special case Pow(±0, y) = +0 for finite y > 0 and not an odd integer + FIDBR $5, F2, F4 //F2 translate to integer F4 + FCMPU F2, F4 + BNE zeroNotOddGtZero // y is not an (odd) integer and y > 0 + FMOVD $(2.0), F4 + FDIV F4, F2 // F2 = F2 / 2.0 + FIDBR $5, F2, F4 //F2 translate to integer F4 + FCMPU F2, F4 + BNE negZeroOddIntGtZero // y is an odd integer and y > 0 + BR zeroNotOddGtZero // y is not an (odd) integer + +xLtZero: + // special case Pow(x, y) = NaN for finite x < 0 and finite non-integer y + FMOVD y+8(FP), F2 + FIDBR $5, F2, F4 + FCMPU F2, F4 + BNE ltZeroInt + BR Normal +yIsPosInf: + // special case Pow(x, +Inf) = +Inf for |x| > 1 + FMOVD x+0(FP), F1 + FMOVD $(1.0), F3 + FCMPU F1, F3 + BGT gtOnePosInf + FMOVD $(-1.0), F3 + FCMPU F1, F3 + BLT ltNegOnePosInf +Normal: + FMOVD x+0(FP), F0 + FMOVD y+8(FP), F2 + MOVD $·powrodataL51<>+0(SB), R9 + LGDR F0, R3 + WORD $0xC0298009 //iilf %r2,2148095317 + BYTE $0x55 + BYTE $0x55 + RISBGNZ $32, $63, $32, R3, R1 + SUBW R1, R2 + RISBGNZ $58, $63, $50, R2, R3 + BYTE $0x18 //lr %r5,%r1 + BYTE $0x51 + MOVD $·powtabi<>+0(SB), R12 + WORD $0xE303C000 //llgc %r0,0(%r3,%r12) + BYTE $0x00 + BYTE $0x90 + SUBW $0x1A0000, R5 + SLD $3, R0, R3 + MOVD $·powtm<>+0(SB), R4 + MOVH $0x0, R8 + ANDW $0x7FF00000, R2 + ORW R5, R1 + WORD $0x5A234000 //a %r2,0(%r3,%r4) + MOVD $0x3FF0000000000000, R5 + RISBGZ $40, $63, $56, R2, R3 + RISBGN $0, $31, $32, R2, R8 + ORW $0x45000000, R3 + MOVW R1, R6 + CMPBLT R6, $0, L42 + FMOVD F0, F4 +L2: + VLVGF $0, R3, V1 + MOVD $·pow_xa<>+0(SB), R2 + WORD $0xED3090A0 //lde %f3,.L52-.L51(%r9) + BYTE $0x00 + BYTE $0x24 + FMOVD 0(R2), F6 + FSUBS F1, F3 + LDGR R8, F1 + WFMSDB V4, V1, V6, V4 + FMOVD 152(R9), F6 + WFMDB V4, V4, V7 + FMOVD 144(R9), F1 + FMOVD 136(R9), F5 + WFMADB V4, V1, V6, V1 + VLEG $0, 128(R9), V16 + FMOVD 120(R9), F6 + WFMADB V4, V5, V6, V5 + FMOVD 112(R9), F6 + WFMADB V1, V7, V5, V1 + WFMADB V4, V6, V16, V16 + SLD $3, R0, R2 + FMOVD 104(R9), F5 + WORD $0xED824004 //ldeb %f8,4(%r2,%r4) + BYTE $0x00 + BYTE $0x04 + LDEBR F3, F3 + FMOVD 96(R9), F6 + WFMADB V4, V6, V5, V6 + FADD F8, F3 + WFMADB V7, V6, V16, V6 + FMUL F7, F7 + FMOVD 88(R9), F5 + FMADD F7, F1, F6 + WFMADB V4, V5, V3, V16 + FMOVD 80(R9), F1 + WFSDB V16, V3, V3 + MOVD $·powtl<>+0(SB), R3 + WFMADB V4, V6, V1, V6 + FMADD F5, F4, F3 + FMOVD 72(R9), F1 + WFMADB V4, V6, V1, V6 + WORD $0xED323000 //adb %f3,0(%r2,%r3) + BYTE $0x00 + BYTE $0x1A + FMOVD 64(R9), F1 + WFMADB V4, V6, V1, V6 + MOVD $·pow_xadd<>+0(SB), R2 + WFMADB V4, V6, V3, V4 + FMOVD 0(R2), F5 + WFADB V4, V16, V3 + VLEG $0, 56(R9), V20 + WFMSDB V2, V3, V5, V3 + VLEG $0, 48(R9), V18 + WFADB V3, V5, V6 + LGDR F3, R2 + WFMSDB V2, V16, V6, V16 + FMOVD 40(R9), F1 + WFMADB V2, V4, V16, V4 + FMOVD 32(R9), F7 + WFMDB V4, V4, V3 + WFMADB V4, V1, V20, V1 + WFMADB V4, V7, V18, V7 + VLEG $0, 24(R9), V16 + WFMADB V1, V3, V7, V1 + FMOVD 16(R9), F5 + WFMADB V4, V5, V16, V5 + RISBGZ $57, $60, $3, R2, R4 + WFMADB V3, V1, V5, V1 + MOVD $·powtexp<>+0(SB), R3 + WORD $0x68343000 //ld %f3,0(%r4,%r3) + FMADD F3, F4, F4 + RISBGN $0, $15, $48, R2, R5 + WFMADB V4, V1, V3, V4 + LGDR F6, R2 + LDGR R5, F1 + SRAD $48, R2, R2 + FMADD F1, F4, F1 + RLL $16, R2, R2 + ANDW $0x7FFF0000, R2 + WORD $0xC22B3F71 //alfi %r2,1064370176 + BYTE $0x00 + BYTE $0x00 + ORW R2, R1, R3 + MOVW R3, R6 + CMPBLT R6, $0, L43 +L1: + FMOVD F1, ret+16(FP) + RET +L43: + LTDBR F0, F0 + BLTU L44 + FMOVD F0, F3 +L7: + MOVD $·pow_xinf<>+0(SB), R3 + FMOVD 0(R3), F5 + WFCEDBS V3, V5, V7 + BVS L8 + WFMDB V3, V2, V6 +L8: + WFCEDBS V2, V2, V3 + BVS L9 + LTDBR F2, F2 + BEQ L26 + MOVW R1, R6 + CMPBLT R6, $0, L45 +L11: + WORD $0xC0190003 //iilf %r1,262143 + BYTE $0xFF + BYTE $0xFF + MOVW R2, R7 + MOVW R1, R6 + CMPBLE R7, R6, L34 + RISBGNZ $32, $63, $32, R5, R1 + LGDR F6, R2 + MOVD $powiadd<>+0(SB), R3 + RISBGZ $60, $60, $4, R2, R2 + WORD $0x5A123000 //a %r1,0(%r2,%r3) + RISBGN $0, $31, $32, R1, R5 + LDGR R5, F1 + FMADD F1, F4, F1 + MOVD $powxscale<>+0(SB), R1 + WORD $0xED121000 //mdb %f1,0(%r2,%r1) + BYTE $0x00 + BYTE $0x1C + BR L1 +L42: + LTDBR F0, F0 + BLTU L46 + FMOVD F0, F4 +L3: + MOVD $·pow_x001a<>+0(SB), R2 + WORD $0xED402000 //cdb %f4,0(%r2) + BYTE $0x00 + BYTE $0x19 + BGE L2 + BVS L2 + MOVD $·pow_x43f<>+0(SB), R2 + WORD $0xED402000 //mdb %f4,0(%r2) + BYTE $0x00 + BYTE $0x1C + WORD $0xC0298009 //iilf %r2,2148095317 + BYTE $0x55 + BYTE $0x55 + LGDR F4, R3 + RISBGNZ $32, $63, $32, R3, R3 + SUBW R3, R2, R3 + RISBGZ $33, $43, $0, R3, R2 + RISBGNZ $58, $63, $50, R3, R3 + WORD $0xE303C000 //llgc %r0,0(%r3,%r12) + BYTE $0x00 + BYTE $0x90 + SLD $3, R0, R3 + WORD $0x5A234000 //a %r2,0(%r3,%r4) + BYTE $0x18 //lr %r3,%r2 + BYTE $0x32 + RISBGN $0, $31, $32, R3, R8 + ADDW $0x4000000, R3 + BLEU L5 + RISBGZ $40, $63, $56, R3, R3 + ORW $0x45000000, R3 + BR L2 +L9: + WFCEDBS V0, V0, V4 + BVS L35 + FMOVD F2, F1 + BR L1 +L46: + LCDBR F0, F4 + BR L3 +L44: + LCDBR F0, F3 + BR L7 +L35: + FMOVD F0, F1 + BR L1 +L26: + FMOVD 8(R9), F1 + BR L1 +L34: + FMOVD 8(R9), F4 +L19: + LTDBR F6, F6 + BLEU L47 +L18: + WFMDB V4, V5, V1 + BR L1 +L5: + RISBGZ $33, $50, $63, R3, R3 + WORD $0xC23B4000 //alfi %r3,1073741824 + BYTE $0x00 + BYTE $0x00 + RLL $24, R3, R3 + ORW $0x45000000, R3 + BR L2 +L45: + WFCEDBS V0, V0, V4 + BVS L35 + LTDBR F0, F0 + BLEU L48 + FMOVD 8(R9), F4 +L12: + MOVW R2, R6 + CMPBLT R6, $0, L19 + FMUL F4, F1 + BR L1 +L47: + BLT L40 + WFCEDBS V0, V0, V2 + BVS L49 +L16: + MOVD ·pow_xnan<>+0(SB), R1 + LDGR R1, F0 + WFMDB V4, V0, V1 + BR L1 +L48: + LGDR F0, R3 + RISBGNZ $32, $63, $32, R3, R1 + MOVW R1, R6 + CMPBEQ R6, $0, L29 + LTDBR F2, F2 + BLTU L50 + FMOVD F2, F4 +L14: + MOVD $·pow_x433<>+0(SB), R1 + FMOVD 0(R1), F7 + WFCHDBS V4, V7, V3 + BEQ L15 + WFADB V7, V4, V3 + FSUB F7, F3 + WFCEDBS V4, V3, V3 + BEQ L15 + LTDBR F0, F0 + FMOVD 8(R9), F4 + BNE L16 +L13: + LTDBR F2, F2 + BLT L18 +L40: + FMOVD $0, F0 + WFMDB V4, V0, V1 + BR L1 +L49: + WFMDB V0, V4, V1 + BR L1 +L29: + FMOVD 8(R9), F4 + BR L13 +L15: + MOVD $·pow_x434<>+0(SB), R1 + FMOVD 0(R1), F7 + WFCHDBS V4, V7, V3 + BEQ L32 + WFADB V7, V4, V3 + FSUB F7, F3 + WFCEDBS V4, V3, V4 + BEQ L32 + FMOVD 0(R9), F4 +L17: + LTDBR F0, F0 + BNE L12 + BR L13 +L32: + FMOVD 8(R9), F4 + BR L17 +L50: + LCDBR F2, F4 + BR L14 +xIsOne: // Pow(1, y) = 1 for any y +yIsOne: // Pow(x, 1) = x for any x +posInfGeZero: // Pow(+Inf, y) = +Inf for y > 0 + MOVD R1, ret+16(FP) + RET +yIsNan: // Pow(NaN, y) = NaN +ltZeroInt: // Pow(x, y) = NaN for finite x < 0 and finite non-integer y + MOVD $NaN, R2 + MOVD R2, ret+16(FP) + RET +negOnePosInf: // Pow(-1, ±Inf) = 1 +negOneNegInf: + MOVD $PosOne, R3 + MOVD R3, ret+16(FP) + RET +negZeroOddInt: + MOVD $NegInf, R3 + MOVD R3, ret+16(FP) + RET +zeroNotOdd: // Pow(±0, y) = +Inf for finite y < 0 and not an odd integer +posZeroLtZero: // special case Pow(+0, y < 0) = +Inf +zeroNegInf: // Pow(±0, -Inf) = +Inf + MOVD $PosInf, R3 + MOVD R3, ret+16(FP) + RET +gtOnePosInf: //Pow(x, +Inf) = +Inf for |x| > 1 +ltNegOnePosInf: + MOVD R2, ret+16(FP) + RET +yIsZero: //Pow(x, ±0) = 1 for any x + MOVD $PosOne, R4 + MOVD R4, ret+16(FP) + RET +negZeroOddIntGtZero: // Pow(-0, y) = -0 for y an odd integer > 0 + MOVD $NegZero, R3 + MOVD R3, ret+16(FP) + RET +zeroNotOddGtZero: // Pow(±0, y) = +0 for finite y > 0 and not an odd integer + MOVD $0, ret+16(FP) + RET diff --git a/go/src/math/remainder.go b/go/src/math/remainder.go new file mode 100644 index 0000000000000000000000000000000000000000..8e99345c59b79733440ae789b1a3dc265fca6c25 --- /dev/null +++ b/go/src/math/remainder.go @@ -0,0 +1,95 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code and the comment below are from +// FreeBSD's /usr/src/lib/msun/src/e_remainder.c and came +// with this notice. The go code is a simplified version of +// the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_remainder(x,y) +// Return : +// returns x REM y = x - [x/y]*y as if in infinite +// precision arithmetic, where [x/y] is the (infinite bit) +// integer nearest x/y (in half way cases, choose the even one). +// Method : +// Based on Mod() returning x - [x/y]chopped * y exactly. + +// Remainder returns the IEEE 754 floating-point remainder of x/y. +// +// Special cases are: +// +// Remainder(±Inf, y) = NaN +// Remainder(NaN, y) = NaN +// Remainder(x, 0) = NaN +// Remainder(x, ±Inf) = x +// Remainder(x, NaN) = NaN +func Remainder(x, y float64) float64 { + if haveArchRemainder { + return archRemainder(x, y) + } + return remainder(x, y) +} + +func remainder(x, y float64) float64 { + const ( + Tiny = 4.45014771701440276618e-308 // 0x0020000000000000 + HalfMax = MaxFloat64 / 2 + ) + // special cases + switch { + case IsNaN(x) || IsNaN(y) || IsInf(x, 0) || y == 0: + return NaN() + case IsInf(y, 0): + return x + } + sign := false + if x < 0 { + x = -x + sign = true + } + if y < 0 { + y = -y + } + if x == y { + if sign { + zero := 0.0 + return -zero + } + return 0 + } + if y <= HalfMax { + x = Mod(x, y+y) // now x < 2y + } + if y < Tiny { + if x+x > y { + x -= y + if x+x >= y { + x -= y + } + } + } else { + yHalf := 0.5 * y + if x > yHalf { + x -= y + if x >= yHalf { + x -= y + } + } + } + if sign { + x = -x + } + return x +} diff --git a/go/src/math/signbit.go b/go/src/math/signbit.go new file mode 100644 index 0000000000000000000000000000000000000000..fe6b5a22af69ee026c96ef7ef9b2efba61d79572 --- /dev/null +++ b/go/src/math/signbit.go @@ -0,0 +1,10 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Signbit reports whether x is negative or negative zero. +func Signbit(x float64) bool { + return int64(Float64bits(x)) < 0 +} diff --git a/go/src/math/sin.go b/go/src/math/sin.go new file mode 100644 index 0000000000000000000000000000000000000000..4793d7e7cd63da1f7eb9634aa6c76ba3328bca1d --- /dev/null +++ b/go/src/math/sin.go @@ -0,0 +1,244 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point sine and cosine. +*/ + +// The original C code, the long comment, and the constants +// below were from http://netlib.sandia.gov/cephes/cmath/sin.c, +// available from http://www.netlib.org/cephes/cmath.tgz. +// The go code is a simplified version of the original C. +// +// sin.c +// +// Circular sine +// +// SYNOPSIS: +// +// double x, y, sin(); +// y = sin( x ); +// +// DESCRIPTION: +// +// Range reduction is into intervals of pi/4. The reduction error is nearly +// eliminated by contriving an extended precision modular arithmetic. +// +// Two polynomial approximating functions are employed. +// Between 0 and pi/4 the sine is approximated by +// x + x**3 P(x**2). +// Between pi/4 and pi/2 the cosine is represented as +// 1 - x**2 Q(x**2). +// +// ACCURACY: +// +// Relative error: +// arithmetic domain # trials peak rms +// DEC 0, 10 150000 3.0e-17 7.8e-18 +// IEEE -1.07e9,+1.07e9 130000 2.1e-16 5.4e-17 +// +// Partial loss of accuracy begins to occur at x = 2**30 = 1.074e9. The loss +// is not gradual, but jumps suddenly to about 1 part in 10e7. Results may +// be meaningless for x > 2**49 = 5.6e14. +// +// cos.c +// +// Circular cosine +// +// SYNOPSIS: +// +// double x, y, cos(); +// y = cos( x ); +// +// DESCRIPTION: +// +// Range reduction is into intervals of pi/4. The reduction error is nearly +// eliminated by contriving an extended precision modular arithmetic. +// +// Two polynomial approximating functions are employed. +// Between 0 and pi/4 the cosine is approximated by +// 1 - x**2 Q(x**2). +// Between pi/4 and pi/2 the sine is represented as +// x + x**3 P(x**2). +// +// ACCURACY: +// +// Relative error: +// arithmetic domain # trials peak rms +// IEEE -1.07e9,+1.07e9 130000 2.1e-16 5.4e-17 +// DEC 0,+1.07e9 17000 3.0e-17 7.2e-18 +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov + +// sin coefficients +var _sin = [...]float64{ + 1.58962301576546568060e-10, // 0x3de5d8fd1fd19ccd + -2.50507477628578072866e-8, // 0xbe5ae5e5a9291f5d + 2.75573136213857245213e-6, // 0x3ec71de3567d48a1 + -1.98412698295895385996e-4, // 0xbf2a01a019bfdf03 + 8.33333333332211858878e-3, // 0x3f8111111110f7d0 + -1.66666666666666307295e-1, // 0xbfc5555555555548 +} + +// cos coefficients +var _cos = [...]float64{ + -1.13585365213876817300e-11, // 0xbda8fa49a0861a9b + 2.08757008419747316778e-9, // 0x3e21ee9d7b4e3f05 + -2.75573141792967388112e-7, // 0xbe927e4f7eac4bc6 + 2.48015872888517045348e-5, // 0x3efa01a019c844f5 + -1.38888888888730564116e-3, // 0xbf56c16c16c14f91 + 4.16666666666665929218e-2, // 0x3fa555555555554b +} + +// Cos returns the cosine of the radian argument x. +// +// Special cases are: +// +// Cos(±Inf) = NaN +// Cos(NaN) = NaN +func Cos(x float64) float64 { + if haveArchCos { + return archCos(x) + } + return cos(x) +} + +func cos(x float64) float64 { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case IsNaN(x) || IsInf(x, 0): + return NaN() + } + + // make argument positive + sign := false + x = Abs(x) + + var j uint64 + var y, z float64 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float64(j) // integer part of x/(Pi/4), as float + + // map zeros to origin + if j&1 == 1 { + j++ + y++ + } + j &= 7 // octant modulo 2Pi radians (360 degrees) + z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic + } + + if j > 3 { + j -= 4 + sign = !sign + } + if j > 1 { + sign = !sign + } + + zz := z * z + if j == 1 || j == 2 { + y = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5]) + } else { + y = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5]) + } + if sign { + y = -y + } + return y +} + +// Sin returns the sine of the radian argument x. +// +// Special cases are: +// +// Sin(±0) = ±0 +// Sin(±Inf) = NaN +// Sin(NaN) = NaN +func Sin(x float64) float64 { + if haveArchSin { + return archSin(x) + } + return sin(x) +} + +func sin(x float64) float64 { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case x == 0 || IsNaN(x): + return x // return ±0 || NaN() + case IsInf(x, 0): + return NaN() + } + + // make argument positive but save the sign + sign := false + if x < 0 { + x = -x + sign = true + } + + var j uint64 + var y, z float64 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float64(j) // integer part of x/(Pi/4), as float + + // map zeros to origin + if j&1 == 1 { + j++ + y++ + } + j &= 7 // octant modulo 2Pi radians (360 degrees) + z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic + } + // reflect in x axis + if j > 3 { + sign = !sign + j -= 4 + } + zz := z * z + if j == 1 || j == 2 { + y = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5]) + } else { + y = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5]) + } + if sign { + y = -y + } + return y +} diff --git a/go/src/math/sin_s390x.s b/go/src/math/sin_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..79d564b938ec2881296957e159c823f187a12f7b --- /dev/null +++ b/go/src/math/sin_s390x.s @@ -0,0 +1,369 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Various constants +DATA sincosxnan<>+0(SB)/8, $0x7ff8000000000000 +GLOBL sincosxnan<>+0(SB), RODATA, $8 +DATA sincosxlim<>+0(SB)/8, $0x432921fb54442d19 +GLOBL sincosxlim<>+0(SB), RODATA, $8 +DATA sincosxadd<>+0(SB)/8, $0xc338000000000000 +GLOBL sincosxadd<>+0(SB), RODATA, $8 +DATA sincosxpi2l<>+0(SB)/8, $0.108285667392191389e-31 +GLOBL sincosxpi2l<>+0(SB), RODATA, $8 +DATA sincosxpi2m<>+0(SB)/8, $0.612323399573676480e-16 +GLOBL sincosxpi2m<>+0(SB), RODATA, $8 +DATA sincosxpi2h<>+0(SB)/8, $0.157079632679489656e+01 +GLOBL sincosxpi2h<>+0(SB), RODATA, $8 +DATA sincosrpi2<>+0(SB)/8, $0.636619772367581341e+00 +GLOBL sincosrpi2<>+0(SB), RODATA, $8 + +// Minimax polynomial approximations +DATA sincosc0<>+0(SB)/8, $0.100000000000000000E+01 +GLOBL sincosc0<>+0(SB), RODATA, $8 +DATA sincosc1<>+0(SB)/8, $-.499999999999999833E+00 +GLOBL sincosc1<>+0(SB), RODATA, $8 +DATA sincosc2<>+0(SB)/8, $0.416666666666625843E-01 +GLOBL sincosc2<>+0(SB), RODATA, $8 +DATA sincosc3<>+0(SB)/8, $-.138888888885498984E-02 +GLOBL sincosc3<>+0(SB), RODATA, $8 +DATA sincosc4<>+0(SB)/8, $0.248015871681607202E-04 +GLOBL sincosc4<>+0(SB), RODATA, $8 +DATA sincosc5<>+0(SB)/8, $-.275572911309937875E-06 +GLOBL sincosc5<>+0(SB), RODATA, $8 +DATA sincosc6<>+0(SB)/8, $0.208735047247632818E-08 +GLOBL sincosc6<>+0(SB), RODATA, $8 +DATA sincosc7<>+0(SB)/8, $-.112753632738365317E-10 +GLOBL sincosc7<>+0(SB), RODATA, $8 +DATA sincoss0<>+0(SB)/8, $0.100000000000000000E+01 +GLOBL sincoss0<>+0(SB), RODATA, $8 +DATA sincoss1<>+0(SB)/8, $-.166666666666666657E+00 +GLOBL sincoss1<>+0(SB), RODATA, $8 +DATA sincoss2<>+0(SB)/8, $0.833333333333309209E-02 +GLOBL sincoss2<>+0(SB), RODATA, $8 +DATA sincoss3<>+0(SB)/8, $-.198412698410701448E-03 +GLOBL sincoss3<>+0(SB), RODATA, $8 +DATA sincoss4<>+0(SB)/8, $0.275573191453906794E-05 +GLOBL sincoss4<>+0(SB), RODATA, $8 +DATA sincoss5<>+0(SB)/8, $-.250520918387633290E-07 +GLOBL sincoss5<>+0(SB), RODATA, $8 +DATA sincoss6<>+0(SB)/8, $0.160571285514715856E-09 +GLOBL sincoss6<>+0(SB), RODATA, $8 +DATA sincoss7<>+0(SB)/8, $-.753213484933210972E-12 +GLOBL sincoss7<>+0(SB), RODATA, $8 + +// Sin returns the sine of the radian argument x. +// +// Special cases are: +// Sin(±0) = ±0 +// Sin(±Inf) = NaN +// Sin(NaN) = NaN +// The algorithm used is minimax polynomial approximation. +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·sinAsm(SB),NOSPLIT,$0-16 + FMOVD x+0(FP), F0 + //special case Sin(±0) = ±0 + FMOVD $(0.0), F1 + FCMPU F0, F1 + BEQ sinIsZero + LTDBR F0, F0 + BLTU L17 + FMOVD F0, F5 +L2: + MOVD $sincosxlim<>+0(SB), R1 + FMOVD 0(R1), F1 + FCMPU F5, F1 + BGT L16 + MOVD $sincoss7<>+0(SB), R1 + FMOVD 0(R1), F4 + MOVD $sincoss6<>+0(SB), R1 + FMOVD 0(R1), F1 + MOVD $sincoss5<>+0(SB), R1 + VLEG $0, 0(R1), V18 + MOVD $sincoss4<>+0(SB), R1 + FMOVD 0(R1), F6 + MOVD $sincoss2<>+0(SB), R1 + VLEG $0, 0(R1), V16 + MOVD $sincoss3<>+0(SB), R1 + FMOVD 0(R1), F7 + MOVD $sincoss1<>+0(SB), R1 + FMOVD 0(R1), F3 + MOVD $sincoss0<>+0(SB), R1 + FMOVD 0(R1), F2 + WFCHDBS V2, V5, V2 + BEQ L18 + MOVD $sincosrpi2<>+0(SB), R1 + FMOVD 0(R1), F3 + MOVD $sincosxadd<>+0(SB), R1 + FMOVD 0(R1), F2 + WFMSDB V0, V3, V2, V3 + FMOVD 0(R1), F6 + FADD F3, F6 + MOVD $sincosxpi2h<>+0(SB), R1 + FMOVD 0(R1), F2 + FMSUB F2, F6, F0 + MOVD $sincosxpi2m<>+0(SB), R1 + FMOVD 0(R1), F4 + FMADD F4, F6, F0 + MOVD $sincosxpi2l<>+0(SB), R1 + WFMDB V0, V0, V1 + FMOVD 0(R1), F7 + WFMDB V1, V1, V2 + LGDR F3, R1 + MOVD $sincosxlim<>+0(SB), R2 + TMLL R1, $1 + BEQ L6 + FMOVD 0(R2), F0 + WFCHDBS V0, V5, V0 + BNE L14 + MOVD $sincosc7<>+0(SB), R2 + FMOVD 0(R2), F0 + MOVD $sincosc6<>+0(SB), R2 + FMOVD 0(R2), F4 + MOVD $sincosc5<>+0(SB), R2 + WFMADB V1, V0, V4, V0 + FMOVD 0(R2), F6 + MOVD $sincosc4<>+0(SB), R2 + WFMADB V1, V0, V6, V0 + FMOVD 0(R2), F4 + MOVD $sincosc2<>+0(SB), R2 + FMOVD 0(R2), F6 + WFMADB V2, V4, V6, V4 + MOVD $sincosc3<>+0(SB), R2 + FMOVD 0(R2), F3 + MOVD $sincosc1<>+0(SB), R2 + WFMADB V2, V0, V3, V0 + FMOVD 0(R2), F6 + WFMADB V1, V4, V6, V4 + TMLL R1, $2 + WFMADB V2, V0, V4, V0 + MOVD $sincosc0<>+0(SB), R1 + FMOVD 0(R1), F2 + WFMADB V1, V0, V2, V0 + BNE L15 + FMOVD F0, ret+8(FP) + RET + +L6: + FMOVD 0(R2), F4 + WFCHDBS V4, V5, V4 + BNE L14 + MOVD $sincoss7<>+0(SB), R2 + FMOVD 0(R2), F4 + MOVD $sincoss6<>+0(SB), R2 + FMOVD 0(R2), F3 + MOVD $sincoss5<>+0(SB), R2 + WFMADB V1, V4, V3, V4 + WFMADB V6, V7, V0, V6 + FMOVD 0(R2), F0 + MOVD $sincoss4<>+0(SB), R2 + FMADD F4, F1, F0 + FMOVD 0(R2), F3 + MOVD $sincoss2<>+0(SB), R2 + FMOVD 0(R2), F4 + MOVD $sincoss3<>+0(SB), R2 + WFMADB V2, V3, V4, V3 + FMOVD 0(R2), F4 + MOVD $sincoss1<>+0(SB), R2 + WFMADB V2, V0, V4, V0 + FMOVD 0(R2), F4 + WFMADB V1, V3, V4, V3 + FNEG F6, F4 + WFMADB V2, V0, V3, V2 + WFMDB V4, V1, V0 + TMLL R1, $2 + WFMSDB V0, V2, V6, V0 + BNE L15 + FMOVD F0, ret+8(FP) + RET + +L14: + MOVD $sincosxnan<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET + +L18: + WFMDB V0, V0, V2 + WFMADB V2, V4, V1, V4 + WFMDB V2, V2, V1 + WFMADB V2, V4, V18, V4 + WFMADB V1, V6, V16, V6 + WFMADB V1, V4, V7, V4 + WFMADB V2, V6, V3, V6 + FMUL F0, F2 + WFMADB V1, V4, V6, V4 + FMADD F4, F2, F0 + FMOVD F0, ret+8(FP) + RET + +L17: + FNEG F0, F5 + BR L2 +L15: + FNEG F0, F0 + FMOVD F0, ret+8(FP) + RET + + +L16: + BR ·sin(SB) //tail call +sinIsZero: + FMOVD F0, ret+8(FP) + RET + +// Cos returns the cosine of the radian argument. +// +// Special cases are: +// Cos(±Inf) = NaN +// Cos(NaN) = NaN +// The algorithm used is minimax polynomial approximation. +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·cosAsm(SB),NOSPLIT,$0-16 + FMOVD x+0(FP), F0 + LTDBR F0, F0 + BLTU L35 + FMOVD F0, F1 +L21: + MOVD $sincosxlim<>+0(SB), R1 + FMOVD 0(R1), F2 + FCMPU F1, F2 + BGT L30 + MOVD $sincosc7<>+0(SB), R1 + FMOVD 0(R1), F4 + MOVD $sincosc6<>+0(SB), R1 + VLEG $0, 0(R1), V20 + MOVD $sincosc5<>+0(SB), R1 + VLEG $0, 0(R1), V18 + MOVD $sincosc4<>+0(SB), R1 + FMOVD 0(R1), F6 + MOVD $sincosc2<>+0(SB), R1 + VLEG $0, 0(R1), V16 + MOVD $sincosc3<>+0(SB), R1 + FMOVD 0(R1), F7 + MOVD $sincosc1<>+0(SB), R1 + FMOVD 0(R1), F5 + MOVD $sincosrpi2<>+0(SB), R1 + FMOVD 0(R1), F2 + MOVD $sincosxadd<>+0(SB), R1 + FMOVD 0(R1), F3 + MOVD $sincoss0<>+0(SB), R1 + WFMSDB V0, V2, V3, V2 + FMOVD 0(R1), F3 + WFCHDBS V3, V1, V3 + LGDR F2, R1 + BEQ L36 + MOVD $sincosxadd<>+0(SB), R2 + FMOVD 0(R2), F4 + FADD F2, F4 + MOVD $sincosxpi2h<>+0(SB), R2 + FMOVD 0(R2), F2 + WFMSDB V4, V2, V0, V2 + MOVD $sincosxpi2m<>+0(SB), R2 + FMOVD 0(R2), F0 + WFMADB V4, V0, V2, V0 + MOVD $sincosxpi2l<>+0(SB), R2 + WFMDB V0, V0, V2 + FMOVD 0(R2), F5 + WFMDB V2, V2, V6 + MOVD $sincosxlim<>+0(SB), R2 + TMLL R1, $1 + BNE L25 + FMOVD 0(R2), F0 + WFCHDBS V0, V1, V0 + BNE L33 + MOVD $sincosc7<>+0(SB), R2 + FMOVD 0(R2), F0 + MOVD $sincosc6<>+0(SB), R2 + FMOVD 0(R2), F4 + MOVD $sincosc5<>+0(SB), R2 + WFMADB V2, V0, V4, V0 + FMOVD 0(R2), F1 + MOVD $sincosc4<>+0(SB), R2 + WFMADB V2, V0, V1, V0 + FMOVD 0(R2), F4 + MOVD $sincosc2<>+0(SB), R2 + FMOVD 0(R2), F1 + WFMADB V6, V4, V1, V4 + MOVD $sincosc3<>+0(SB), R2 + FMOVD 0(R2), F3 + MOVD $sincosc1<>+0(SB), R2 + WFMADB V6, V0, V3, V0 + FMOVD 0(R2), F1 + WFMADB V2, V4, V1, V4 + TMLL R1, $2 + WFMADB V6, V0, V4, V0 + MOVD $sincosc0<>+0(SB), R1 + FMOVD 0(R1), F4 + WFMADB V2, V0, V4, V0 + BNE L34 + FMOVD F0, ret+8(FP) + RET + +L25: + FMOVD 0(R2), F3 + WFCHDBS V3, V1, V1 + BNE L33 + MOVD $sincoss7<>+0(SB), R2 + FMOVD 0(R2), F1 + MOVD $sincoss6<>+0(SB), R2 + FMOVD 0(R2), F3 + MOVD $sincoss5<>+0(SB), R2 + WFMADB V2, V1, V3, V1 + FMOVD 0(R2), F3 + MOVD $sincoss4<>+0(SB), R2 + WFMADB V2, V1, V3, V1 + FMOVD 0(R2), F3 + MOVD $sincoss2<>+0(SB), R2 + FMOVD 0(R2), F7 + WFMADB V6, V3, V7, V3 + MOVD $sincoss3<>+0(SB), R2 + FMADD F5, F4, F0 + FMOVD 0(R2), F4 + MOVD $sincoss1<>+0(SB), R2 + FMADD F1, F6, F4 + FMOVD 0(R2), F1 + FMADD F3, F2, F1 + FMUL F0, F2 + WFMADB V6, V4, V1, V6 + TMLL R1, $2 + FMADD F6, F2, F0 + BNE L34 + FMOVD F0, ret+8(FP) + RET + +L33: + MOVD $sincosxnan<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET + +L36: + FMUL F0, F0 + MOVD $sincosc0<>+0(SB), R1 + WFMDB V0, V0, V1 + WFMADB V0, V4, V20, V4 + WFMADB V1, V6, V16, V6 + WFMADB V0, V4, V18, V4 + WFMADB V0, V6, V5, V6 + WFMADB V1, V4, V7, V4 + FMOVD 0(R1), F2 + WFMADB V1, V4, V6, V4 + WFMADB V0, V4, V2, V0 + FMOVD F0, ret+8(FP) + RET + +L35: + FNEG F0, F1 + BR L21 +L34: + FNEG F0, F0 + FMOVD F0, ret+8(FP) + RET + +L30: + BR ·cos(SB) //tail call diff --git a/go/src/math/sincos.go b/go/src/math/sincos.go new file mode 100644 index 0000000000000000000000000000000000000000..e3fb96094fa75f33727cd676bb937b17233707d9 --- /dev/null +++ b/go/src/math/sincos.go @@ -0,0 +1,73 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// Coefficients _sin[] and _cos[] are found in pkg/math/sin.go. + +// Sincos returns Sin(x), Cos(x). +// +// Special cases are: +// +// Sincos(±0) = ±0, 1 +// Sincos(±Inf) = NaN, NaN +// Sincos(NaN) = NaN, NaN +func Sincos(x float64) (sin, cos float64) { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case x == 0: + return x, 1 // return ±0.0, 1.0 + case IsNaN(x) || IsInf(x, 0): + return NaN(), NaN() + } + + // make argument positive + sinSign, cosSign := false, false + if x < 0 { + x = -x + sinSign = true + } + + var j uint64 + var y, z float64 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float64(j) // integer part of x/(Pi/4), as float + + if j&1 == 1 { // map zeros to origin + j++ + y++ + } + j &= 7 // octant modulo 2Pi radians (360 degrees) + z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic + } + if j > 3 { // reflect in x axis + j -= 4 + sinSign, cosSign = !sinSign, !cosSign + } + if j > 1 { + cosSign = !cosSign + } + + zz := z * z + cos = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5]) + sin = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5]) + if j == 1 || j == 2 { + sin, cos = cos, sin + } + if cosSign { + cos = -cos + } + if sinSign { + sin = -sin + } + return +} diff --git a/go/src/math/sinh.go b/go/src/math/sinh.go new file mode 100644 index 0000000000000000000000000000000000000000..78b3c299d668931fb0289328a99b0ab5ce29f723 --- /dev/null +++ b/go/src/math/sinh.go @@ -0,0 +1,93 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +/* + Floating-point hyperbolic sine and cosine. + + The exponential func is called for arguments + greater in magnitude than 0.5. + + A series is used for arguments smaller in magnitude than 0.5. + + Cosh(x) is computed from the exponential func for + all arguments. +*/ + +// Sinh returns the hyperbolic sine of x. +// +// Special cases are: +// +// Sinh(±0) = ±0 +// Sinh(±Inf) = ±Inf +// Sinh(NaN) = NaN +func Sinh(x float64) float64 { + if haveArchSinh { + return archSinh(x) + } + return sinh(x) +} + +func sinh(x float64) float64 { + // The coefficients are #2029 from Hart & Cheney. (20.36D) + const ( + P0 = -0.6307673640497716991184787251e+6 + P1 = -0.8991272022039509355398013511e+5 + P2 = -0.2894211355989563807284660366e+4 + P3 = -0.2630563213397497062819489e+2 + Q0 = -0.6307673640497716991212077277e+6 + Q1 = 0.1521517378790019070696485176e+5 + Q2 = -0.173678953558233699533450911e+3 + ) + + sign := false + if x < 0 { + x = -x + sign = true + } + + var temp float64 + switch { + case x > 21: + temp = Exp(x) * 0.5 + + case x > 0.5: + ex := Exp(x) + temp = (ex - 1/ex) * 0.5 + + default: + sq := x * x + temp = (((P3*sq+P2)*sq+P1)*sq + P0) * x + temp = temp / (((sq+Q2)*sq+Q1)*sq + Q0) + } + + if sign { + temp = -temp + } + return temp +} + +// Cosh returns the hyperbolic cosine of x. +// +// Special cases are: +// +// Cosh(±0) = 1 +// Cosh(±Inf) = +Inf +// Cosh(NaN) = NaN +func Cosh(x float64) float64 { + if haveArchCosh { + return archCosh(x) + } + return cosh(x) +} + +func cosh(x float64) float64 { + x = Abs(x) + if x > 21 { + return Exp(x) * 0.5 + } + ex := Exp(x) + return (ex + 1/ex) * 0.5 +} diff --git a/go/src/math/sinh_s390x.s b/go/src/math/sinh_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..d684968a3a87e684c80d166369fc3dc229a1186c --- /dev/null +++ b/go/src/math/sinh_s390x.s @@ -0,0 +1,251 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + + +#include "textflag.h" + +// Constants +DATA sinhrodataL21<>+0(SB)/8, $0.231904681384629956E-16 +DATA sinhrodataL21<>+8(SB)/8, $0.693147180559945286E+00 +DATA sinhrodataL21<>+16(SB)/8, $704.E0 +GLOBL sinhrodataL21<>+0(SB), RODATA, $24 +DATA sinhrlog2<>+0(SB)/8, $0x3ff7154760000000 +GLOBL sinhrlog2<>+0(SB), RODATA, $8 +DATA sinhxinf<>+0(SB)/8, $0x7ff0000000000000 +GLOBL sinhxinf<>+0(SB), RODATA, $8 +DATA sinhxinit<>+0(SB)/8, $0x3ffb504f333f9de6 +GLOBL sinhxinit<>+0(SB), RODATA, $8 +DATA sinhxlim1<>+0(SB)/8, $800.E0 +GLOBL sinhxlim1<>+0(SB), RODATA, $8 +DATA sinhxadd<>+0(SB)/8, $0xc3200001610007fb +GLOBL sinhxadd<>+0(SB), RODATA, $8 +DATA sinhx4ff<>+0(SB)/8, $0x4ff0000000000000 +GLOBL sinhx4ff<>+0(SB), RODATA, $8 + +// Minimax polynomial approximations +DATA sinhe0<>+0(SB)/8, $0.11715728752538099300E+01 +GLOBL sinhe0<>+0(SB), RODATA, $8 +DATA sinhe1<>+0(SB)/8, $0.11715728752538099300E+01 +GLOBL sinhe1<>+0(SB), RODATA, $8 +DATA sinhe2<>+0(SB)/8, $0.58578643762688526692E+00 +GLOBL sinhe2<>+0(SB), RODATA, $8 +DATA sinhe3<>+0(SB)/8, $0.19526214587563004497E+00 +GLOBL sinhe3<>+0(SB), RODATA, $8 +DATA sinhe4<>+0(SB)/8, $0.48815536475176217404E-01 +GLOBL sinhe4<>+0(SB), RODATA, $8 +DATA sinhe5<>+0(SB)/8, $0.97631072948627397816E-02 +GLOBL sinhe5<>+0(SB), RODATA, $8 +DATA sinhe6<>+0(SB)/8, $0.16271839297756073153E-02 +GLOBL sinhe6<>+0(SB), RODATA, $8 +DATA sinhe7<>+0(SB)/8, $0.23245485387271142509E-03 +GLOBL sinhe7<>+0(SB), RODATA, $8 +DATA sinhe8<>+0(SB)/8, $0.29080955860869629131E-04 +GLOBL sinhe8<>+0(SB), RODATA, $8 +DATA sinhe9<>+0(SB)/8, $0.32311267157667725278E-05 +GLOBL sinhe9<>+0(SB), RODATA, $8 + +// Sinh returns the hyperbolic sine of the argument. +// +// Special cases are: +// Sinh(±0) = ±0 +// Sinh(±Inf) = ±Inf +// Sinh(NaN) = NaN +// The algorithm used is minimax polynomial approximation +// with coefficients determined with a Remez exchange algorithm. + +TEXT ·sinhAsm(SB),NOSPLIT,$0-16 + FMOVD x+0(FP), F0 + //special case Sinh(±0) = ±0 + FMOVD $(0.0), F1 + FCMPU F0, F1 + BEQ sinhIsZero + //special case Sinh(±Inf) = ±Inf + FMOVD $1.797693134862315708145274237317043567981e+308, F1 + FCMPU F1, F0 + BLEU sinhIsInf + FMOVD $-1.797693134862315708145274237317043567981e+308, F1 + FCMPU F1, F0 + BGT sinhIsInf + + MOVD $sinhrodataL21<>+0(SB), R5 + LTDBR F0, F0 + MOVD sinhxinit<>+0(SB), R1 + FMOVD F0, F4 + MOVD R1, R3 + BLTU L19 + FMOVD F0, F2 +L2: + WORD $0xED205010 //cdb %f2,.L22-.L21(%r5) + BYTE $0x00 + BYTE $0x19 + BGE L15 //jnl .L15 + BVS L15 + WFCEDBS V2, V2, V0 + BEQ L20 +L12: + FMOVD F4, F0 + FMOVD F0, ret+8(FP) + RET + +L15: + WFCEDBS V2, V2, V0 + BVS L12 + MOVD $sinhxlim1<>+0(SB), R2 + FMOVD 0(R2), F0 + WFCHDBS V0, V2, V0 + BEQ L6 + WFCHEDBS V4, V2, V6 + MOVD $sinhxinf<>+0(SB), R1 + FMOVD 0(R1), F0 + BNE LEXITTAGsinh + WFCHDBS V2, V4, V2 + BNE L16 + FNEG F0, F0 + FMOVD F0, ret+8(FP) + RET + +L19: + FNEG F0, F2 + BR L2 +L6: + MOVD $sinhxadd<>+0(SB), R2 + FMOVD 0(R2), F0 + MOVD sinhrlog2<>+0(SB), R2 + LDGR R2, F6 + WFMSDB V4, V6, V0, V16 + FMOVD sinhrodataL21<>+8(SB), F6 + WFADB V0, V16, V0 + FMOVD sinhrodataL21<>+0(SB), F3 + WFMSDB V0, V6, V4, V6 + MOVD $sinhe9<>+0(SB), R2 + WFMADB V0, V3, V6, V0 + FMOVD 0(R2), F1 + MOVD $sinhe7<>+0(SB), R2 + WFMDB V0, V0, V6 + FMOVD 0(R2), F5 + MOVD $sinhe8<>+0(SB), R2 + FMOVD 0(R2), F3 + MOVD $sinhe6<>+0(SB), R2 + WFMADB V6, V1, V5, V1 + FMOVD 0(R2), F5 + MOVD $sinhe5<>+0(SB), R2 + FMOVD 0(R2), F7 + MOVD $sinhe3<>+0(SB), R2 + WFMADB V6, V3, V5, V3 + FMOVD 0(R2), F5 + MOVD $sinhe4<>+0(SB), R2 + WFMADB V6, V7, V5, V7 + FMOVD 0(R2), F5 + MOVD $sinhe2<>+0(SB), R2 + VLEG $0, 0(R2), V20 + WFMDB V6, V6, V18 + WFMADB V6, V5, V20, V5 + WFMADB V1, V18, V7, V1 + FNEG F0, F0 + WFMADB V3, V18, V5, V3 + MOVD $sinhe1<>+0(SB), R3 + WFCEDBS V2, V4, V2 + FMOVD 0(R3), F5 + MOVD $sinhe0<>+0(SB), R3 + WFMADB V6, V1, V5, V1 + FMOVD 0(R3), F5 + VLGVG $0, V16, R2 + WFMADB V6, V3, V5, V6 + RLL $3, R2, R2 + RISBGN $0, $15, $48, R2, R1 + BEQ L9 + WFMSDB V0, V1, V6, V0 + MOVD $sinhx4ff<>+0(SB), R3 + FNEG F0, F0 + FMOVD 0(R3), F2 + FMUL F2, F0 + ANDW $0xFFFF, R2 + WORD $0xA53FEFB6 //llill %r3,61366 + SUBW R2, R3, R2 + RISBGN $0, $15, $48, R2, R1 + LDGR R1, F2 + FMUL F2, F0 + FMOVD F0, ret+8(FP) + RET + +L20: + MOVD $sinhxadd<>+0(SB), R2 + FMOVD 0(R2), F2 + MOVD sinhrlog2<>+0(SB), R2 + LDGR R2, F0 + WFMSDB V4, V0, V2, V6 + FMOVD sinhrodataL21<>+8(SB), F0 + FADD F6, F2 + MOVD $sinhe9<>+0(SB), R2 + FMSUB F0, F2, F4 + FMOVD 0(R2), F1 + FMOVD sinhrodataL21<>+0(SB), F3 + MOVD $sinhe7<>+0(SB), R2 + FMADD F3, F2, F4 + FMOVD 0(R2), F0 + MOVD $sinhe8<>+0(SB), R2 + WFMDB V4, V4, V2 + FMOVD 0(R2), F3 + MOVD $sinhe6<>+0(SB), R2 + FMOVD 0(R2), F5 + LGDR F6, R2 + RLL $3, R2, R2 + RISBGN $0, $15, $48, R2, R1 + WFMADB V2, V1, V0, V1 + LDGR R1, F0 + MOVD $sinhe5<>+0(SB), R1 + WFMADB V2, V3, V5, V3 + FMOVD 0(R1), F5 + MOVD $sinhe3<>+0(SB), R1 + FMOVD 0(R1), F6 + WFMDB V2, V2, V7 + WFMADB V2, V5, V6, V5 + WORD $0xA7487FB6 //lhi %r4,32694 + FNEG F4, F4 + ANDW $0xFFFF, R2 + SUBW R2, R4, R2 + RISBGN $0, $15, $48, R2, R3 + LDGR R3, F6 + WFADB V0, V6, V16 + MOVD $sinhe4<>+0(SB), R1 + WFMADB V1, V7, V5, V1 + WFMDB V4, V16, V4 + FMOVD 0(R1), F5 + MOVD $sinhe2<>+0(SB), R1 + VLEG $0, 0(R1), V16 + MOVD $sinhe1<>+0(SB), R1 + WFMADB V2, V5, V16, V5 + VLEG $0, 0(R1), V16 + WFMADB V3, V7, V5, V3 + WFMADB V2, V1, V16, V1 + FSUB F6, F0 + FMUL F1, F4 + MOVD $sinhe0<>+0(SB), R1 + FMOVD 0(R1), F6 + WFMADB V2, V3, V6, V2 + WFMADB V0, V2, V4, V0 + FMOVD F0, ret+8(FP) + RET + +L9: + WFMADB V0, V1, V6, V0 + MOVD $sinhx4ff<>+0(SB), R3 + FMOVD 0(R3), F2 + FMUL F2, F0 + WORD $0xA72AF000 //ahi %r2,-4096 + RISBGN $0, $15, $48, R2, R1 + LDGR R1, F2 + FMUL F2, F0 + FMOVD F0, ret+8(FP) + RET + +L16: + FMOVD F0, ret+8(FP) + RET + +LEXITTAGsinh: +sinhIsInf: +sinhIsZero: + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/sqrt.go b/go/src/math/sqrt.go new file mode 100644 index 0000000000000000000000000000000000000000..54929ebcaf74c30fdf6462d521e5aab5fc28942e --- /dev/null +++ b/go/src/math/sqrt.go @@ -0,0 +1,145 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code and the long comment below are +// from FreeBSD's /usr/src/lib/msun/src/e_sqrt.c and +// came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_sqrt(x) +// Return correctly rounded sqrt. +// ----------------------------------------- +// | Use the hardware sqrt if you have one | +// ----------------------------------------- +// Method: +// Bit by bit method using integer arithmetic. (Slow, but portable) +// 1. Normalization +// Scale x to y in [1,4) with even powers of 2: +// find an integer k such that 1 <= (y=x*2**(2k)) < 4, then +// sqrt(x) = 2**k * sqrt(y) +// 2. Bit by bit computation +// Let q = sqrt(y) truncated to i bit after binary point (q = 1), +// i 0 +// i+1 2 +// s = 2*q , and y = 2 * ( y - q ). (1) +// i i i i +// +// To compute q from q , one checks whether +// i+1 i +// +// -(i+1) 2 +// (q + 2 ) <= y. (2) +// i +// -(i+1) +// If (2) is false, then q = q ; otherwise q = q + 2 . +// i+1 i i+1 i +// +// With some algebraic manipulation, it is not difficult to see +// that (2) is equivalent to +// -(i+1) +// s + 2 <= y (3) +// i i +// +// The advantage of (3) is that s and y can be computed by +// i i +// the following recurrence formula: +// if (3) is false +// +// s = s , y = y ; (4) +// i+1 i i+1 i +// +// otherwise, +// -i -(i+1) +// s = s + 2 , y = y - s - 2 (5) +// i+1 i i+1 i i +// +// One may easily use induction to prove (4) and (5). +// Note. Since the left hand side of (3) contain only i+2 bits, +// it is not necessary to do a full (53-bit) comparison +// in (3). +// 3. Final rounding +// After generating the 53 bits result, we compute one more bit. +// Together with the remainder, we can decide whether the +// result is exact, bigger than 1/2ulp, or less than 1/2ulp +// (it will never equal to 1/2ulp). +// The rounding mode can be detected by checking whether +// huge + tiny is equal to huge, and whether huge - tiny is +// equal to huge for some floating point number "huge" and "tiny". +// +// +// Notes: Rounding mode detection omitted. The constants "mask", "shift", +// and "bias" are found in src/math/bits.go + +// Sqrt returns the square root of x. +// +// Special cases are: +// +// Sqrt(+Inf) = +Inf +// Sqrt(±0) = ±0 +// Sqrt(x < 0) = NaN +// Sqrt(NaN) = NaN +func Sqrt(x float64) float64 { + return sqrt(x) +} + +// Note: On systems where Sqrt is a single instruction, the compiler +// may turn a direct call into a direct use of that instruction instead. + +func sqrt(x float64) float64 { + // special cases + switch { + case x == 0 || IsNaN(x) || IsInf(x, 1): + return x + case x < 0: + return NaN() + } + ix := Float64bits(x) + // normalize x + exp := int((ix >> shift) & mask) + if exp == 0 { // subnormal x + for ix&(1<>= 1 // exp = exp/2, exponent of square root + // generate sqrt(x) bit by bit + ix <<= 1 + var q, s uint64 // q = sqrt(x) + r := uint64(1 << (shift + 1)) // r = moving bit from MSB to LSB + for r != 0 { + t := s + r + if t <= ix { + s = t + r + ix -= t + q += r + } + ix <<= 1 + r >>= 1 + } + // final rounding + if ix != 0 { // remainder, result not exact + q += q & 1 // round according to extra bit + } + ix = q>>1 + uint64(exp-1+bias)< 2**49 = 5.6e14. +// [Accuracy loss statement from sin.go comments.] +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov + +// tan coefficients +var _tanP = [...]float64{ + -1.30936939181383777646e4, // 0xc0c992d8d24f3f38 + 1.15351664838587416140e6, // 0x413199eca5fc9ddd + -1.79565251976484877988e7, // 0xc1711fead3299176 +} +var _tanQ = [...]float64{ + 1.00000000000000000000e0, + 1.36812963470692954678e4, // 0x40cab8a5eeb36572 + -1.32089234440210967447e6, // 0xc13427bc582abc96 + 2.50083801823357915839e7, // 0x4177d98fc2ead8ef + -5.38695755929454629881e7, // 0xc189afe03cbe5a31 +} + +// Tan returns the tangent of the radian argument x. +// +// Special cases are: +// +// Tan(±0) = ±0 +// Tan(±Inf) = NaN +// Tan(NaN) = NaN +func Tan(x float64) float64 { + if haveArchTan { + return archTan(x) + } + return tan(x) +} + +func tan(x float64) float64 { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case x == 0 || IsNaN(x): + return x // return ±0 || NaN() + case IsInf(x, 0): + return NaN() + } + + // make argument positive but save the sign + sign := false + if x < 0 { + x = -x + sign = true + } + var j uint64 + var y, z float64 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float64(j) // integer part of x/(Pi/4), as float + + /* map zeros and singularities to origin */ + if j&1 == 1 { + j++ + y++ + } + + z = ((x - y*PI4A) - y*PI4B) - y*PI4C + } + zz := z * z + + if zz > 1e-14 { + y = z + z*(zz*(((_tanP[0]*zz)+_tanP[1])*zz+_tanP[2])/((((zz+_tanQ[1])*zz+_tanQ[2])*zz+_tanQ[3])*zz+_tanQ[4])) + } else { + y = z + } + if j&2 == 2 { + y = -1 / y + } + if sign { + y = -y + } + return y +} diff --git a/go/src/math/tan_s390x.s b/go/src/math/tan_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..48cd2841e881e00c272640d792bcc25ffa91a574 --- /dev/null +++ b/go/src/math/tan_s390x.s @@ -0,0 +1,111 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial approximations +DATA ·tanrodataL13<> + 0(SB)/8, $0.181017336383229927e-07 +DATA ·tanrodataL13<> + 8(SB)/8, $-.256590857271311164e-03 +DATA ·tanrodataL13<> + 16(SB)/8, $-.464359274328689195e+00 +DATA ·tanrodataL13<> + 24(SB)/8, $1.0 +DATA ·tanrodataL13<> + 32(SB)/8, $-.333333333333333464e+00 +DATA ·tanrodataL13<> + 40(SB)/8, $0.245751217306830032e-01 +DATA ·tanrodataL13<> + 48(SB)/8, $-.245391301343844510e-03 +DATA ·tanrodataL13<> + 56(SB)/8, $0.214530914428992319e-01 +DATA ·tanrodataL13<> + 64(SB)/8, $0.108285667160535624e-31 +DATA ·tanrodataL13<> + 72(SB)/8, $0.612323399573676480e-16 +DATA ·tanrodataL13<> + 80(SB)/8, $0.157079632679489656e+01 +DATA ·tanrodataL13<> + 88(SB)/8, $0.636619772367581341e+00 +GLOBL ·tanrodataL13<> + 0(SB), RODATA, $96 + +// Constants +DATA ·tanxnan<> + 0(SB)/8, $0x7ff8000000000000 +GLOBL ·tanxnan<> + 0(SB), RODATA, $8 +DATA ·tanxlim<> + 0(SB)/8, $0x432921fb54442d19 +GLOBL ·tanxlim<> + 0(SB), RODATA, $8 +DATA ·tanxadd<> + 0(SB)/8, $0xc338000000000000 +GLOBL ·tanxadd<> + 0(SB), RODATA, $8 + +// Tan returns the tangent of the radian argument. +// +// Special cases are: +// Tan(±0) = ±0 +// Tan(±Inf) = NaN +// Tan(NaN) = NaN +// The algorithm used is minimax polynomial approximation using a table of +// polynomial coefficients determined with a Remez exchange algorithm. + +TEXT ·tanAsm(SB), NOSPLIT, $0-16 + FMOVD x+0(FP), F0 + //special case Tan(±0) = ±0 + FMOVD $(0.0), F1 + FCMPU F0, F1 + BEQ atanIsZero + + MOVD $·tanrodataL13<>+0(SB), R5 + LTDBR F0, F0 + BLTU L10 + FMOVD F0, F2 +L2: + MOVD $·tanxlim<>+0(SB), R1 + FMOVD 0(R1), F1 + FCMPU F2, F1 + BGT L9 + BVS L11 + MOVD $·tanxadd<>+0(SB), R1 + FMOVD 88(R5), F6 + FMOVD 0(R1), F4 + WFMSDB V0, V6, V4, V6 + FMOVD 80(R5), F1 + FADD F6, F4 + FMOVD 72(R5), F2 + FMSUB F1, F4, F0 + FMOVD 64(R5), F3 + WFMADB V4, V2, V0, V2 + FMOVD 56(R5), F1 + WFMADB V4, V3, V2, V4 + FMUL F2, F2 + VLEG $0, 48(R5), V18 + LGDR F6, R1 + FMOVD 40(R5), F5 + FMOVD 32(R5), F3 + FMADD F1, F2, F3 + FMOVD 24(R5), F1 + FMOVD 16(R5), F7 + FMOVD 8(R5), F0 + WFMADB V2, V7, V1, V7 + WFMADB V2, V0, V5, V0 + WFMDB V2, V2, V1 + FMOVD 0(R5), F5 + WFLCDB V4, V16 + WFMADB V2, V5, V18, V5 + WFMADB V1, V0, V7, V0 + TMLL R1, $1 + WFMADB V1, V5, V3, V1 + BNE L12 + WFDDB V0, V1, V0 + WFMDB V2, V16, V2 + WFMADB V2, V0, V4, V0 + LCDBR F0, F0 + FMOVD F0, ret+8(FP) + RET +L12: + WFMSDB V2, V1, V0, V2 + WFMDB V16, V2, V2 + FDIV F2, F0 + FMOVD F0, ret+8(FP) + RET +L11: + MOVD $·tanxnan<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET +L10: + LCDBR F0, F2 + BR L2 +L9: + BR ·tan(SB) +atanIsZero: + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/tanh.go b/go/src/math/tanh.go new file mode 100644 index 0000000000000000000000000000000000000000..94ebc3b6515d52cb8eccdc62f341518913c2ec7a --- /dev/null +++ b/go/src/math/tanh.go @@ -0,0 +1,105 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +// The original C code, the long comment, and the constants +// below were from http://netlib.sandia.gov/cephes/cmath/sin.c, +// available from http://www.netlib.org/cephes/cmath.tgz. +// The go code is a simplified version of the original C. +// tanh.c +// +// Hyperbolic tangent +// +// SYNOPSIS: +// +// double x, y, tanh(); +// +// y = tanh( x ); +// +// DESCRIPTION: +// +// Returns hyperbolic tangent of argument in the range MINLOG to MAXLOG. +// MAXLOG = 8.8029691931113054295988e+01 = log(2**127) +// MINLOG = -8.872283911167299960540e+01 = log(2**-128) +// +// A rational function is used for |x| < 0.625. The form +// x + x**3 P(x)/Q(x) of Cody & Waite is employed. +// Otherwise, +// tanh(x) = sinh(x)/cosh(x) = 1 - 2/(exp(2x) + 1). +// +// ACCURACY: +// +// Relative error: +// arithmetic domain # trials peak rms +// IEEE -2,2 30000 2.5e-16 5.8e-17 +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov +// + +var tanhP = [...]float64{ + -9.64399179425052238628e-1, + -9.92877231001918586564e1, + -1.61468768441708447952e3, +} +var tanhQ = [...]float64{ + 1.12811678491632931402e2, + 2.23548839060100448583e3, + 4.84406305325125486048e3, +} + +// Tanh returns the hyperbolic tangent of x. +// +// Special cases are: +// +// Tanh(±0) = ±0 +// Tanh(±Inf) = ±1 +// Tanh(NaN) = NaN +func Tanh(x float64) float64 { + if haveArchTanh { + return archTanh(x) + } + return tanh(x) +} + +func tanh(x float64) float64 { + const MAXLOG = 8.8029691931113054295988e+01 // log(2**127) + z := Abs(x) + switch { + case z > 0.5*MAXLOG: + if x < 0 { + return -1 + } + return 1 + case z >= 0.625: + s := Exp(2 * z) + z = 1 - 2/(s+1) + if x < 0 { + z = -z + } + default: + if x == 0 { + return x + } + s := x * x + z = x + x*s*((tanhP[0]*s+tanhP[1])*s+tanhP[2])/(((s+tanhQ[0])*s+tanhQ[1])*s+tanhQ[2]) + } + return z +} diff --git a/go/src/math/tanh_s390x.s b/go/src/math/tanh_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..7e2d4dd7972935c305848a407ee6f6c91bdd1b4c --- /dev/null +++ b/go/src/math/tanh_s390x.s @@ -0,0 +1,169 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// Minimax polynomial approximations +DATA tanhrodataL18<>+0(SB)/8, $-1.0 +DATA tanhrodataL18<>+8(SB)/8, $-2.0 +DATA tanhrodataL18<>+16(SB)/8, $1.0 +DATA tanhrodataL18<>+24(SB)/8, $2.0 +DATA tanhrodataL18<>+32(SB)/8, $0.20000000000000011868E+01 +DATA tanhrodataL18<>+40(SB)/8, $0.13333333333333341256E+01 +DATA tanhrodataL18<>+48(SB)/8, $0.26666666663549111502E+00 +DATA tanhrodataL18<>+56(SB)/8, $0.66666666658721844678E+00 +DATA tanhrodataL18<>+64(SB)/8, $0.88890217768964374821E-01 +DATA tanhrodataL18<>+72(SB)/8, $0.25397199429103821138E-01 +DATA tanhrodataL18<>+80(SB)/8, $-.346573590279972643E+00 +DATA tanhrodataL18<>+88(SB)/8, $20.E0 +GLOBL tanhrodataL18<>+0(SB), RODATA, $96 + +// Constants +DATA tanhrlog2<>+0(SB)/8, $0x4007154760000000 +GLOBL tanhrlog2<>+0(SB), RODATA, $8 +DATA tanhxadd<>+0(SB)/8, $0xc2f0000100003ff0 +GLOBL tanhxadd<>+0(SB), RODATA, $8 +DATA tanhxmone<>+0(SB)/8, $-1.0 +GLOBL tanhxmone<>+0(SB), RODATA, $8 +DATA tanhxzero<>+0(SB)/8, $0 +GLOBL tanhxzero<>+0(SB), RODATA, $8 + +// Polynomial coefficients +DATA tanhtab<>+0(SB)/8, $0.000000000000000000E+00 +DATA tanhtab<>+8(SB)/8, $-.171540871271399150E-01 +DATA tanhtab<>+16(SB)/8, $-.306597931864376363E-01 +DATA tanhtab<>+24(SB)/8, $-.410200970469965021E-01 +DATA tanhtab<>+32(SB)/8, $-.486343079978231466E-01 +DATA tanhtab<>+40(SB)/8, $-.538226193725835820E-01 +DATA tanhtab<>+48(SB)/8, $-.568439602538111520E-01 +DATA tanhtab<>+56(SB)/8, $-.579091847395528847E-01 +DATA tanhtab<>+64(SB)/8, $-.571909584179366341E-01 +DATA tanhtab<>+72(SB)/8, $-.548312665987204407E-01 +DATA tanhtab<>+80(SB)/8, $-.509471843643441085E-01 +DATA tanhtab<>+88(SB)/8, $-.456353588448863359E-01 +DATA tanhtab<>+96(SB)/8, $-.389755254243262365E-01 +DATA tanhtab<>+104(SB)/8, $-.310332908285244231E-01 +DATA tanhtab<>+112(SB)/8, $-.218623539150173528E-01 +DATA tanhtab<>+120(SB)/8, $-.115062908917949451E-01 +GLOBL tanhtab<>+0(SB), RODATA, $128 + +// Tanh returns the hyperbolic tangent of the argument. +// +// Special cases are: +// Tanh(±0) = ±0 +// Tanh(±Inf) = ±1 +// Tanh(NaN) = NaN +// The algorithm used is minimax polynomial approximation using a table of +// polynomial coefficients determined with a Remez exchange algorithm. + +TEXT ·tanhAsm(SB),NOSPLIT,$0-16 + FMOVD x+0(FP), F0 + // special case Tanh(±0) = ±0 + FMOVD $(0.0), F1 + FCMPU F0, F1 + BEQ tanhIsZero + MOVD $tanhrodataL18<>+0(SB), R5 + LTDBR F0, F0 + MOVD $0x4034000000000000, R1 + BLTU L15 + FMOVD F0, F1 +L2: + MOVD $tanhxadd<>+0(SB), R2 + FMOVD 0(R2), F2 + MOVD tanhrlog2<>+0(SB), R2 + LDGR R2, F4 + WFMSDB V0, V4, V2, V4 + MOVD $tanhtab<>+0(SB), R3 + LGDR F4, R2 + RISBGZ $57, $60, $3, R2, R4 + WORD $0xED105058 //cdb %f1,.L19-.L18(%r5) + BYTE $0x00 + BYTE $0x19 + RISBGN $0, $15, $48, R2, R1 + WORD $0x68543000 //ld %f5,0(%r4,%r3) + LDGR R1, F6 + BLT L3 + MOVD $tanhxzero<>+0(SB), R1 + FMOVD 0(R1), F2 + WFCHDBS V0, V2, V4 + BEQ L9 + WFCHDBS V2, V0, V2 + BNE L1 + MOVD $tanhxmone<>+0(SB), R1 + FMOVD 0(R1), F0 + FMOVD F0, ret+8(FP) + RET + +L3: + FADD F4, F2 + FMOVD tanhrodataL18<>+80(SB), F4 + FMADD F4, F2, F0 + FMOVD tanhrodataL18<>+72(SB), F1 + WFMDB V0, V0, V3 + FMOVD tanhrodataL18<>+64(SB), F2 + WFMADB V0, V1, V2, V1 + FMOVD tanhrodataL18<>+56(SB), F4 + FMOVD tanhrodataL18<>+48(SB), F2 + WFMADB V1, V3, V4, V1 + FMOVD tanhrodataL18<>+40(SB), F4 + WFMADB V3, V2, V4, V2 + FMOVD tanhrodataL18<>+32(SB), F4 + WORD $0xB9270022 //lhr %r2,%r2 + WFMADB V3, V1, V4, V1 + FMOVD tanhrodataL18<>+24(SB), F4 + WFMADB V3, V2, V4, V3 + WFMADB V0, V5, V0, V2 + WFMADB V0, V1, V3, V0 + WORD $0xA7183ECF //lhi %r1,16079 + WFMADB V0, V2, V5, V2 + FMUL F6, F2 + MOVW R2, R10 + MOVW R1, R11 + CMPBLE R10, R11, L16 + FMOVD F6, F0 + WORD $0xED005010 //adb %f0,.L28-.L18(%r5) + BYTE $0x00 + BYTE $0x1A + WORD $0xA7184330 //lhi %r1,17200 + FADD F2, F0 + MOVW R2, R10 + MOVW R1, R11 + CMPBGT R10, R11, L17 + WORD $0xED605010 //sdb %f6,.L28-.L18(%r5) + BYTE $0x00 + BYTE $0x1B + FADD F6, F2 + WFDDB V0, V2, V0 + FMOVD F0, ret+8(FP) + RET + +L9: + FMOVD tanhrodataL18<>+16(SB), F0 +L1: + FMOVD F0, ret+8(FP) + RET + +L15: + FNEG F0, F1 + BR L2 +L16: + FADD F6, F2 + FMOVD tanhrodataL18<>+8(SB), F0 + FMADD F4, F2, F0 + FMOVD tanhrodataL18<>+0(SB), F4 + FNEG F0, F0 + WFMADB V0, V2, V4, V0 + FMOVD F0, ret+8(FP) + RET + +L17: + WFDDB V0, V4, V0 + FMOVD tanhrodataL18<>+16(SB), F2 + WFSDB V0, V2, V0 + FMOVD F0, ret+8(FP) + RET + +tanhIsZero: //return ±0 + FMOVD F0, ret+8(FP) + RET diff --git a/go/src/math/trig_reduce.go b/go/src/math/trig_reduce.go new file mode 100644 index 0000000000000000000000000000000000000000..5ecdd8375e3295b5aa3f9bc60f0ab40b06db9f54 --- /dev/null +++ b/go/src/math/trig_reduce.go @@ -0,0 +1,102 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +import ( + "math/bits" +) + +// reduceThreshold is the maximum value of x where the reduction using Pi/4 +// in 3 float64 parts still gives accurate results. This threshold +// is set by y*C being representable as a float64 without error +// where y is given by y = floor(x * (4 / Pi)) and C is the leading partial +// terms of 4/Pi. Since the leading terms (PI4A and PI4B in sin.go) have 30 +// and 32 trailing zero bits, y should have less than 30 significant bits. +// +// y < 1<<30 -> floor(x*4/Pi) < 1<<30 -> x < (1<<30 - 1) * Pi/4 +// +// So, conservatively we can take x < 1<<29. +// Above this threshold Payne-Hanek range reduction must be used. +const reduceThreshold = 1 << 29 + +// trigReduce implements Payne-Hanek range reduction by Pi/4 +// for x > 0. It returns the integer part mod 8 (j) and +// the fractional part (z) of x / (Pi/4). +// The implementation is based on: +// "ARGUMENT REDUCTION FOR HUGE ARGUMENTS: Good to the Last Bit" +// K. C. Ng et al, March 24, 1992 +// The simulated multi-precision calculation of x*B uses 64-bit integer arithmetic. +func trigReduce(x float64) (j uint64, z float64) { + const PI4 = Pi / 4 + if x < PI4 { + return 0, x + } + // Extract out the integer and exponent such that, + // x = ix * 2 ** exp. + ix := Float64bits(x) + exp := int(ix>>shift&mask) - bias - shift + ix &^= mask << shift + ix |= 1 << shift + // Use the exponent to extract the 3 appropriate uint64 digits from mPi4, + // B ~ (z0, z1, z2), such that the product leading digit has the exponent -61. + // Note, exp >= -53 since x >= PI4 and exp < 971 for maximum float64. + digit, bitshift := uint(exp+61)/64, uint(exp+61)%64 + z0 := (mPi4[digit] << bitshift) | (mPi4[digit+1] >> (64 - bitshift)) + z1 := (mPi4[digit+1] << bitshift) | (mPi4[digit+2] >> (64 - bitshift)) + z2 := (mPi4[digit+2] << bitshift) | (mPi4[digit+3] >> (64 - bitshift)) + // Multiply mantissa by the digits and extract the upper two digits (hi, lo). + z2hi, _ := bits.Mul64(z2, ix) + z1hi, z1lo := bits.Mul64(z1, ix) + z0lo := z0 * ix + lo, c := bits.Add64(z1lo, z2hi, 0) + hi, _ := bits.Add64(z0lo, z1hi, c) + // The top 3 bits are j. + j = hi >> 61 + // Extract the fraction and find its magnitude. + hi = hi<<3 | lo>>61 + lz := uint(bits.LeadingZeros64(hi)) + e := uint64(bias - (lz + 1)) + // Clear implicit mantissa bit and shift into place. + hi = (hi << (lz + 1)) | (lo >> (64 - (lz + 1))) + hi >>= 64 - shift + // Include the exponent and convert to a float. + hi |= e << shift + z = Float64frombits(hi) + // Map zeros to origin. + if j&1 == 1 { + j++ + j &= 7 + z-- + } + // Multiply the fractional part by pi/4. + return j, z * PI4 +} + +// mPi4 is the binary digits of 4/pi as a uint64 array, +// that is, 4/pi = Sum mPi4[i]*2^(-64*i) +// 19 64-bit digits and the leading one bit give 1217 bits +// of precision to handle the largest possible float64 exponent. +var mPi4 = [...]uint64{ + 0x0000000000000001, + 0x45f306dc9c882a53, + 0xf84eafa3ea69bb81, + 0xb6c52b3278872083, + 0xfca2c757bd778ac3, + 0x6e48dc74849ba5c0, + 0x0c925dd413a32439, + 0xfc3bd63962534e7d, + 0xd1046bea5d768909, + 0xd338e04d68befc82, + 0x7323ac7306a673e9, + 0x3908bf177bf25076, + 0x3ff12fffbc0b301f, + 0xde5e2316b414da3e, + 0xda6cfd9e4f96136e, + 0x9e8c7ecd3cbfd45a, + 0xea4f758fd7cbe2f6, + 0x7a0e73ef14a525d4, + 0xd7f6bf623f1aba10, + 0xac06608df8f6d757, +} diff --git a/go/src/math/unsafe.go b/go/src/math/unsafe.go new file mode 100644 index 0000000000000000000000000000000000000000..e251f62a2a138508484a76e6dd66f3d8675efe3f --- /dev/null +++ b/go/src/math/unsafe.go @@ -0,0 +1,41 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +import "unsafe" + +// Despite being an exported symbol, +// Float32bits is linknamed by widely used packages. +// Notable members of the hall of shame include: +// - gitee.com/quant1x/num +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +// Note that this comment is not part of the doc comment. +// +//go:linkname Float32bits + +// Float32bits returns the IEEE 754 binary representation of f, +// with the sign bit of f and the result in the same bit position. +// Float32bits(Float32frombits(x)) == x. +func Float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) } + +// Float32frombits returns the floating-point number corresponding +// to the IEEE 754 binary representation b, with the sign bit of b +// and the result in the same bit position. +// Float32frombits(Float32bits(x)) == x. +func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) } + +// Float64bits returns the IEEE 754 binary representation of f, +// with the sign bit of f and the result in the same bit position, +// and Float64bits(Float64frombits(x)) == x. +func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) } + +// Float64frombits returns the floating-point number corresponding +// to the IEEE 754 binary representation b, with the sign bit of b +// and the result in the same bit position. +// Float64frombits(Float64bits(x)) == x. +func Float64frombits(b uint64) float64 { return *(*float64)(unsafe.Pointer(&b)) } diff --git a/go/src/mime/encodedword.go b/go/src/mime/encodedword.go new file mode 100644 index 0000000000000000000000000000000000000000..c4afad043a290837ef51e5d177e96e7b843e071a --- /dev/null +++ b/go/src/mime/encodedword.go @@ -0,0 +1,414 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import ( + "bytes" + "encoding/base64" + "errors" + "fmt" + "io" + "strings" + "unicode" + "unicode/utf8" +) + +// A WordEncoder is an RFC 2047 encoded-word encoder. +type WordEncoder byte + +const ( + // BEncoding represents Base64 encoding scheme as defined by RFC 2045. + BEncoding = WordEncoder('b') + // QEncoding represents the Q-encoding scheme as defined by RFC 2047. + QEncoding = WordEncoder('q') +) + +var ( + errInvalidWord = errors.New("mime: invalid RFC 2047 encoded-word") +) + +// Encode returns the encoded-word form of s. If s is ASCII without special +// characters, it is returned unchanged. The provided charset is the IANA +// charset name of s. It is case insensitive. +func (e WordEncoder) Encode(charset, s string) string { + if !needsEncoding(s) { + return s + } + return e.encodeWord(charset, s) +} + +func needsEncoding(s string) bool { + for _, b := range s { + if (b < ' ' || b > '~') && b != '\t' { + return true + } + } + return false +} + +// encodeWord encodes a string into an encoded-word. +func (e WordEncoder) encodeWord(charset, s string) string { + var buf strings.Builder + // Could use a hint like len(s)*3, but that's not enough for cases + // with word splits and too much for simpler inputs. + // 48 is close to maxEncodedWordLen/2, but adjusted to allocator size class. + buf.Grow(48) + + e.openWord(&buf, charset) + if e == BEncoding { + e.bEncode(&buf, charset, s) + } else { + e.qEncode(&buf, charset, s) + } + closeWord(&buf) + + return buf.String() +} + +const ( + // The maximum length of an encoded-word is 75 characters. + // See RFC 2047, section 2. + maxEncodedWordLen = 75 + // maxContentLen is how much content can be encoded, ignoring the header and + // 2-byte footer. + maxContentLen = maxEncodedWordLen - len("=?UTF-8?q?") - len("?=") +) + +var maxBase64Len = base64.StdEncoding.DecodedLen(maxContentLen) + +// bEncode encodes s using base64 encoding and writes it to buf. +func (e WordEncoder) bEncode(buf *strings.Builder, charset, s string) { + w := base64.NewEncoder(base64.StdEncoding, buf) + // If the charset is not UTF-8 or if the content is short, do not bother + // splitting the encoded-word. + if !isUTF8(charset) || base64.StdEncoding.EncodedLen(len(s)) <= maxContentLen { + io.WriteString(w, s) + w.Close() + return + } + + var currentLen, last, runeLen int + for i := 0; i < len(s); i += runeLen { + // Multi-byte characters must not be split across encoded-words. + // See RFC 2047, section 5.3. + _, runeLen = utf8.DecodeRuneInString(s[i:]) + + if currentLen+runeLen <= maxBase64Len { + currentLen += runeLen + } else { + io.WriteString(w, s[last:i]) + w.Close() + e.splitWord(buf, charset) + last = i + currentLen = runeLen + } + } + io.WriteString(w, s[last:]) + w.Close() +} + +// qEncode encodes s using Q encoding and writes it to buf. It splits the +// encoded-words when necessary. +func (e WordEncoder) qEncode(buf *strings.Builder, charset, s string) { + // We only split encoded-words when the charset is UTF-8. + if !isUTF8(charset) { + writeQString(buf, s) + return + } + + var currentLen, runeLen int + for i := 0; i < len(s); i += runeLen { + b := s[i] + // Multi-byte characters must not be split across encoded-words. + // See RFC 2047, section 5.3. + var encLen int + if b >= ' ' && b <= '~' && b != '=' && b != '?' && b != '_' { + runeLen, encLen = 1, 1 + } else { + _, runeLen = utf8.DecodeRuneInString(s[i:]) + encLen = 3 * runeLen + } + + if currentLen+encLen > maxContentLen { + e.splitWord(buf, charset) + currentLen = 0 + } + writeQString(buf, s[i:i+runeLen]) + currentLen += encLen + } +} + +// writeQString encodes s using Q encoding and writes it to buf. +func writeQString(buf *strings.Builder, s string) { + for i := 0; i < len(s); i++ { + switch b := s[i]; { + case b == ' ': + buf.WriteByte('_') + case b >= '!' && b <= '~' && b != '=' && b != '?' && b != '_': + buf.WriteByte(b) + default: + buf.WriteByte('=') + buf.WriteByte(upperhex[b>>4]) + buf.WriteByte(upperhex[b&0x0f]) + } + } +} + +// openWord writes the beginning of an encoded-word into buf. +func (e WordEncoder) openWord(buf *strings.Builder, charset string) { + buf.WriteString("=?") + buf.WriteString(charset) + buf.WriteByte('?') + buf.WriteByte(byte(e)) + buf.WriteByte('?') +} + +// closeWord writes the end of an encoded-word into buf. +func closeWord(buf *strings.Builder) { + buf.WriteString("?=") +} + +// splitWord closes the current encoded-word and opens a new one. +func (e WordEncoder) splitWord(buf *strings.Builder, charset string) { + closeWord(buf) + buf.WriteByte(' ') + e.openWord(buf, charset) +} + +func isUTF8(charset string) bool { + return strings.EqualFold(charset, "UTF-8") +} + +const upperhex = "0123456789ABCDEF" + +// A WordDecoder decodes MIME headers containing RFC 2047 encoded-words. +type WordDecoder struct { + // CharsetReader, if non-nil, defines a function to generate + // charset-conversion readers, converting from the provided + // charset into UTF-8. + // Charsets are always lower-case. utf-8, iso-8859-1 and us-ascii charsets + // are handled by default. + // One of the CharsetReader's result values must be non-nil. + CharsetReader func(charset string, input io.Reader) (io.Reader, error) +} + +// Decode decodes an RFC 2047 encoded-word. +func (d *WordDecoder) Decode(word string) (string, error) { + // See https://tools.ietf.org/html/rfc2047#section-2 for details. + // Our decoder is permissive, we accept empty encoded-text. + if len(word) < 8 || !strings.HasPrefix(word, "=?") || !strings.HasSuffix(word, "?=") || strings.Count(word, "?") != 4 { + return "", errInvalidWord + } + word = word[2 : len(word)-2] + + // split word "UTF-8?q?text" into "UTF-8", 'q', and "text" + charset, text, _ := strings.Cut(word, "?") + if charset == "" { + return "", errInvalidWord + } + encoding, text, _ := strings.Cut(text, "?") + if len(encoding) != 1 { + return "", errInvalidWord + } + + content, err := decode(encoding[0], text) + if err != nil { + return "", err + } + + var buf strings.Builder + if err := d.convert(&buf, charset, content); err != nil { + return "", err + } + return buf.String(), nil +} + +// DecodeHeader decodes all encoded-words of the given string. It returns an +// error if and only if [WordDecoder.CharsetReader] of d returns an error. +func (d *WordDecoder) DecodeHeader(header string) (string, error) { + // If there is no encoded-word, returns before creating a buffer. + i := strings.Index(header, "=?") + if i == -1 { + return header, nil + } + + var buf strings.Builder + + buf.WriteString(header[:i]) + header = header[i:] + + betweenWords := false + for { + start := strings.Index(header, "=?") + if start == -1 { + break + } + cur := start + len("=?") + + i := strings.Index(header[cur:], "?") + if i == -1 { + break + } + charset := header[cur : cur+i] + cur += i + len("?") + + if len(header) < cur+len("Q??=") { + break + } + encoding := header[cur] + cur++ + + if header[cur] != '?' { + break + } + cur++ + + j := strings.Index(header[cur:], "?=") + if j == -1 { + break + } + text := header[cur : cur+j] + end := cur + j + len("?=") + + content, err := decode(encoding, text) + if err != nil { + betweenWords = false + buf.WriteString(header[:start+2]) + header = header[start+2:] + continue + } + + // Write characters before the encoded-word. White-space and newline + // characters separating two encoded-words must be deleted. + if start > 0 && (!betweenWords || hasNonWhitespace(header[:start])) { + buf.WriteString(header[:start]) + } + + if err := d.convert(&buf, charset, content); err != nil { + return "", err + } + + header = header[end:] + betweenWords = true + } + + if len(header) > 0 { + buf.WriteString(header) + } + + return buf.String(), nil +} + +func decode(encoding byte, text string) ([]byte, error) { + switch encoding { + case 'B', 'b': + return base64.StdEncoding.DecodeString(text) + case 'Q', 'q': + return qDecode(text) + default: + return nil, errInvalidWord + } +} + +func (d *WordDecoder) convert(buf *strings.Builder, charset string, content []byte) error { + switch { + case strings.EqualFold("utf-8", charset): + buf.Write(content) + case strings.EqualFold("iso-8859-1", charset): + for _, c := range content { + buf.WriteRune(rune(c)) + } + case strings.EqualFold("us-ascii", charset): + for _, c := range content { + if c >= utf8.RuneSelf { + buf.WriteRune(unicode.ReplacementChar) + } else { + buf.WriteByte(c) + } + } + default: + if d.CharsetReader == nil { + return fmt.Errorf("mime: unhandled charset %q", charset) + } + r, err := d.CharsetReader(strings.ToLower(charset), bytes.NewReader(content)) + if err != nil { + return err + } + if _, err = io.Copy(buf, r); err != nil { + return err + } + } + return nil +} + +// hasNonWhitespace reports whether s (assumed to be ASCII) contains at least +// one byte of non-whitespace. +func hasNonWhitespace(s string) bool { + for _, b := range s { + switch b { + // Encoded-words can only be separated by linear white spaces which does + // not include vertical tabs (\v). + case ' ', '\t', '\n', '\r': + default: + return true + } + } + return false +} + +// qDecode decodes a Q encoded string. +func qDecode(s string) ([]byte, error) { + dec := make([]byte, len(s)) + n := 0 + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == '_': + dec[n] = ' ' + case c == '=': + if i+2 >= len(s) { + return nil, errInvalidWord + } + b, err := readHexByte(s[i+1], s[i+2]) + if err != nil { + return nil, err + } + dec[n] = b + i += 2 + case (c <= '~' && c >= ' ') || c == '\n' || c == '\r' || c == '\t': + dec[n] = c + default: + return nil, errInvalidWord + } + n++ + } + + return dec[:n], nil +} + +// readHexByte returns the byte from its quoted-printable representation. +func readHexByte(a, b byte) (byte, error) { + var hb, lb byte + var err error + if hb, err = fromHex(a); err != nil { + return 0, err + } + if lb, err = fromHex(b); err != nil { + return 0, err + } + return hb<<4 | lb, nil +} + +func fromHex(b byte) (byte, error) { + switch { + case b >= '0' && b <= '9': + return b - '0', nil + case b >= 'A' && b <= 'F': + return b - 'A' + 10, nil + // Accept badly encoded bytes. + case b >= 'a' && b <= 'f': + return b - 'a' + 10, nil + } + return 0, fmt.Errorf("mime: invalid hex byte %#02x", b) +} diff --git a/go/src/mime/encodedword_test.go b/go/src/mime/encodedword_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2a98794380fb029bb61b51d59a9de8eb67d81cf6 --- /dev/null +++ b/go/src/mime/encodedword_test.go @@ -0,0 +1,239 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import ( + "errors" + "io" + "strings" + "testing" +) + +func TestEncodeWord(t *testing.T) { + utf8, iso88591 := "utf-8", "iso-8859-1" + tests := []struct { + enc WordEncoder + charset string + src, exp string + }{ + {QEncoding, utf8, "François-Jérôme", "=?utf-8?q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?="}, + {BEncoding, utf8, "Café", "=?utf-8?b?Q2Fmw6k=?="}, + {QEncoding, iso88591, "La Seleção", "=?iso-8859-1?q?La_Sele=C3=A7=C3=A3o?="}, + {QEncoding, utf8, "", ""}, + {QEncoding, utf8, "A", "A"}, + {QEncoding, iso88591, "a", "a"}, + {QEncoding, utf8, "123 456", "123 456"}, + {QEncoding, utf8, "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~", "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~"}, + {QEncoding, utf8, strings.Repeat("é", 10), "=?utf-8?q?" + strings.Repeat("=C3=A9", 10) + "?="}, + {QEncoding, utf8, strings.Repeat("é", 11), "=?utf-8?q?" + strings.Repeat("=C3=A9", 10) + "?= =?utf-8?q?=C3=A9?="}, + {QEncoding, iso88591, strings.Repeat("\xe9", 22), "=?iso-8859-1?q?" + strings.Repeat("=E9", 22) + "?="}, + {QEncoding, utf8, strings.Repeat("\x80", 22), "=?utf-8?q?" + strings.Repeat("=80", 21) + "?= =?utf-8?q?=80?="}, + {BEncoding, iso88591, strings.Repeat("\xe9", 45), "=?iso-8859-1?b?" + strings.Repeat("6enp", 15) + "?="}, + {BEncoding, utf8, strings.Repeat("\x80", 48), "=?utf-8?b?" + strings.Repeat("gICA", 15) + "?= =?utf-8?b?gICA?="}, + } + + for _, test := range tests { + if s := test.enc.Encode(test.charset, test.src); s != test.exp { + t.Errorf("Encode(%q) = %q, want %q", test.src, s, test.exp) + } + } +} + +func TestEncodedWordLength(t *testing.T) { + tests := []struct { + enc WordEncoder + src string + }{ + {QEncoding, strings.Repeat("à", 30)}, + {QEncoding, strings.Repeat("é", 60)}, + {BEncoding, strings.Repeat("ï", 25)}, + {BEncoding, strings.Repeat("ô", 37)}, + {BEncoding, strings.Repeat("\x80", 50)}, + {QEncoding, "{$firstname} Bienvendio a Apostolica, aquà inicia el camino de tu"}, + } + + for _, test := range tests { + s := test.enc.Encode("utf-8", test.src) + wordLen := 0 + for i := 0; i < len(s); i++ { + if s[i] == ' ' { + wordLen = 0 + continue + } + + wordLen++ + if wordLen > maxEncodedWordLen { + t.Errorf("Encode(%q) has more than %d characters: %q", + test.src, maxEncodedWordLen, s) + } + } + } +} + +func TestDecodeWord(t *testing.T) { + tests := []struct { + src, exp string + hasErr bool + }{ + {"=?UTF-8?Q?=C2=A1Hola,_se=C3=B1or!?=", "¡Hola, señor!", false}, + {"=?UTF-8?Q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?=", "François-Jérôme", false}, + {"=?UTF-8?q?ascii?=", "ascii", false}, + {"=?utf-8?B?QW5kcsOp?=", "André", false}, + {"=?ISO-8859-1?Q?Rapha=EBl_Dupont?=", "Raphaël Dupont", false}, + {"=?utf-8?b?IkFudG9uaW8gSm9zw6kiIDxqb3NlQGV4YW1wbGUub3JnPg==?=", `"Antonio José" `, false}, + {"=?UTF-8?A?Test?=", "", true}, + {"=?UTF-8?Q?A=B?=", "", true}, + {"=?UTF-8?Q?=A?=", "", true}, + {"=?UTF-8?A?A?=", "", true}, + {"=????=", "", true}, + {"=?UTF-8???=", "", true}, + {"=?UTF-8?Q??=", "", false}, + } + + for _, test := range tests { + dec := new(WordDecoder) + s, err := dec.Decode(test.src) + if test.hasErr && err == nil { + t.Errorf("Decode(%q) should return an error", test.src) + continue + } + if !test.hasErr && err != nil { + t.Errorf("Decode(%q): %v", test.src, err) + continue + } + if s != test.exp { + t.Errorf("Decode(%q) = %q, want %q", test.src, s, test.exp) + } + } +} + +func TestDecodeHeader(t *testing.T) { + tests := []struct { + src, exp string + }{ + {"=?UTF-8?Q?=C2=A1Hola,_se=C3=B1or!?=", "¡Hola, señor!"}, + {"=?UTF-8?Q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?=", "François-Jérôme"}, + {"=?UTF-8?q?ascii?=", "ascii"}, + {"=?utf-8?B?QW5kcsOp?=", "André"}, + {"=?ISO-8859-1?Q?Rapha=EBl_Dupont?=", "Raphaël Dupont"}, + {"Jean", "Jean"}, + {"=?utf-8?b?IkFudG9uaW8gSm9zw6kiIDxqb3NlQGV4YW1wbGUub3JnPg==?=", `"Antonio José" `}, + {"=?UTF-8?A?Test?=", "=?UTF-8?A?Test?="}, + {"=?UTF-8?Q?A=B?=", "=?UTF-8?Q?A=B?="}, + {"=?UTF-8?Q?=A?=", "=?UTF-8?Q?=A?="}, + {"=?UTF-8?A?A?=", "=?UTF-8?A?A?="}, + // Incomplete words + {"=?", "=?"}, + {"=?UTF-8?", "=?UTF-8?"}, + {"=?UTF-8?=", "=?UTF-8?="}, + {"=?UTF-8?Q", "=?UTF-8?Q"}, + {"=?UTF-8?Q?", "=?UTF-8?Q?"}, + {"=?UTF-8?Q?=", "=?UTF-8?Q?="}, + {"=?UTF-8?Q?A", "=?UTF-8?Q?A"}, + {"=?UTF-8?Q?A?", "=?UTF-8?Q?A?"}, + // Tests from RFC 2047 + {"=?ISO-8859-1?Q?a?=", "a"}, + {"=?ISO-8859-1?Q?a?= b", "a b"}, + {"=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=", "ab"}, + {"=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=", "ab"}, + {"=?ISO-8859-1?Q?a?= \r\n\t =?ISO-8859-1?Q?b?=", "ab"}, + {"=?ISO-8859-1?Q?a_b?=", "a b"}, + } + + for _, test := range tests { + dec := new(WordDecoder) + s, err := dec.DecodeHeader(test.src) + if err != nil { + t.Errorf("DecodeHeader(%q): %v", test.src, err) + } + if s != test.exp { + t.Errorf("DecodeHeader(%q) = %q, want %q", test.src, s, test.exp) + } + } +} + +func TestCharsetDecoder(t *testing.T) { + tests := []struct { + src string + want string + charsets []string + content []string + }{ + {"=?utf-8?b?Q2Fmw6k=?=", "Café", nil, nil}, + {"=?ISO-8859-1?Q?caf=E9?=", "café", nil, nil}, + {"=?US-ASCII?Q?foo_bar?=", "foo bar", nil, nil}, + {"=?utf-8?Q?=?=", "=?utf-8?Q?=?=", nil, nil}, + {"=?utf-8?Q?=A?=", "=?utf-8?Q?=A?=", nil, nil}, + { + "=?ISO-8859-15?Q?f=F5=F6?= =?windows-1252?Q?b=E0r?=", + "f\xf5\xf6b\xe0r", + []string{"iso-8859-15", "windows-1252"}, + []string{"f\xf5\xf6", "b\xe0r"}, + }, + } + + for _, test := range tests { + i := 0 + dec := &WordDecoder{ + CharsetReader: func(charset string, input io.Reader) (io.Reader, error) { + if charset != test.charsets[i] { + t.Errorf("DecodeHeader(%q), got charset %q, want %q", test.src, charset, test.charsets[i]) + } + content, err := io.ReadAll(input) + if err != nil { + t.Errorf("DecodeHeader(%q), error in reader: %v", test.src, err) + } + got := string(content) + if got != test.content[i] { + t.Errorf("DecodeHeader(%q), got content %q, want %q", test.src, got, test.content[i]) + } + i++ + + return strings.NewReader(got), nil + }, + } + got, err := dec.DecodeHeader(test.src) + if err != nil { + t.Errorf("DecodeHeader(%q): %v", test.src, err) + } + if got != test.want { + t.Errorf("DecodeHeader(%q) = %q, want %q", test.src, got, test.want) + } + } +} + +func TestCharsetDecoderError(t *testing.T) { + dec := &WordDecoder{ + CharsetReader: func(charset string, input io.Reader) (io.Reader, error) { + return nil, errors.New("Test error") + }, + } + + if _, err := dec.DecodeHeader("=?charset?Q?foo?="); err == nil { + t.Error("DecodeHeader should return an error") + } +} + +func BenchmarkQEncodeWord(b *testing.B) { + for i := 0; i < b.N; i++ { + QEncoding.Encode("UTF-8", "¡Hola, señor!") + } +} + +func BenchmarkQDecodeWord(b *testing.B) { + dec := new(WordDecoder) + + for i := 0; i < b.N; i++ { + dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=") + } +} + +func BenchmarkQDecodeHeader(b *testing.B) { + dec := new(WordDecoder) + + for i := 0; i < b.N; i++ { + dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=") + } +} diff --git a/go/src/mime/example_test.go b/go/src/mime/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8a96873e5dc6b77d34f69563e8fea4f9e40b6743 --- /dev/null +++ b/go/src/mime/example_test.go @@ -0,0 +1,123 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime_test + +import ( + "bytes" + "fmt" + "io" + "mime" +) + +func ExampleWordEncoder_Encode() { + fmt.Println(mime.QEncoding.Encode("utf-8", "¡Hola, señor!")) + fmt.Println(mime.QEncoding.Encode("utf-8", "Hello!")) + fmt.Println(mime.BEncoding.Encode("UTF-8", "¡Hola, señor!")) + fmt.Println(mime.QEncoding.Encode("ISO-8859-1", "Caf\xE9")) + // Output: + // =?utf-8?q?=C2=A1Hola,_se=C3=B1or!?= + // Hello! + // =?UTF-8?b?wqFIb2xhLCBzZcOxb3Ih?= + // =?ISO-8859-1?q?Caf=E9?= +} + +func ExampleWordDecoder_Decode() { + dec := new(mime.WordDecoder) + header, err := dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=") + if err != nil { + panic(err) + } + fmt.Println(header) + + dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { + switch charset { + case "x-case": + // Fake character set for example. + // Real use would integrate with packages such + // as code.google.com/p/go-charset + content, err := io.ReadAll(input) + if err != nil { + return nil, err + } + return bytes.NewReader(bytes.ToUpper(content)), nil + default: + return nil, fmt.Errorf("unhandled charset %q", charset) + } + } + header, err = dec.Decode("=?x-case?q?hello!?=") + if err != nil { + panic(err) + } + fmt.Println(header) + // Output: + // ¡Hola, señor! + // HELLO! +} + +func ExampleWordDecoder_DecodeHeader() { + dec := new(mime.WordDecoder) + header, err := dec.DecodeHeader("=?utf-8?q?=C3=89ric?= , =?utf-8?q?Ana=C3=AFs?= ") + if err != nil { + panic(err) + } + fmt.Println(header) + + header, err = dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,?= =?utf-8?q?_se=C3=B1or!?=") + if err != nil { + panic(err) + } + fmt.Println(header) + + dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { + switch charset { + case "x-case": + // Fake character set for example. + // Real use would integrate with packages such + // as code.google.com/p/go-charset + content, err := io.ReadAll(input) + if err != nil { + return nil, err + } + return bytes.NewReader(bytes.ToUpper(content)), nil + default: + return nil, fmt.Errorf("unhandled charset %q", charset) + } + } + header, err = dec.DecodeHeader("=?x-case?q?hello_?= =?x-case?q?world!?=") + if err != nil { + panic(err) + } + fmt.Println(header) + // Output: + // Éric , Anaïs + // ¡Hola, señor! + // HELLO WORLD! +} + +func ExampleFormatMediaType() { + mediatype := "text/html" + params := map[string]string{ + "charset": "utf-8", + } + + result := mime.FormatMediaType(mediatype, params) + + fmt.Println("result:", result) + // Output: + // result: text/html; charset=utf-8 +} + +func ExampleParseMediaType() { + mediatype, params, err := mime.ParseMediaType("text/html; charset=utf-8") + if err != nil { + panic(err) + } + + fmt.Println("type:", mediatype) + fmt.Println("charset:", params["charset"]) + // Output: + // type: text/html + // charset: utf-8 +} diff --git a/go/src/mime/grammar.go b/go/src/mime/grammar.go new file mode 100644 index 0000000000000000000000000000000000000000..1efd8a16dec607de16233b9279e4b45ff2f1a964 --- /dev/null +++ b/go/src/mime/grammar.go @@ -0,0 +1,85 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +// isTSpecial reports whether c is in 'tspecials' as defined by RFC +// 1521 and RFC 2045. +func isTSpecial(c byte) bool { + // tspecials := "(" / ")" / "<" / ">" / "@" / + // "," / ";" / ":" / "\" / <"> + // "/" / "[" / "]" / "?" / "=" + // + // mask is a 128-bit bitmap with 1s for allowed bytes, + // so that the byte c can be tested with a shift and an and. + // If c >= 128, then 1<' | + 1<<'@' | + 1<<',' | + 1<<';' | + 1<<':' | + 1<<'\\' | + 1<<'"' | + 1<<'/' | + 1<<'[' | + 1<<']' | + 1<<'?' | + 1<<'=' + return ((uint64(1)<>64)) != 0 +} + +// isTokenChar reports whether c is in 'token' as defined by RFC +// 1521 and RFC 2045. +func isTokenChar(c byte) bool { + // token := 1* + // + // mask is a 128-bit bitmap with 1s for allowed bytes, + // so that the byte c can be tested with a shift and an and. + // If c >= 128, then 1<>64)) != 0 +} + +// isToken reports whether s is a 'token' as defined by RFC 1521 +// and RFC 2045. +func isToken(s string) bool { + if s == "" { + return false + } + for _, c := range []byte(s) { + if !isTokenChar(c) { + return false + } + } + return true +} diff --git a/go/src/mime/mediatype.go b/go/src/mime/mediatype.go new file mode 100644 index 0000000000000000000000000000000000000000..c6006b614f319e06126d0b21a42ea9cf9487b011 --- /dev/null +++ b/go/src/mime/mediatype.go @@ -0,0 +1,402 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import ( + "errors" + "fmt" + "maps" + "slices" + "strings" + "unicode" +) + +// FormatMediaType serializes mediatype t and the parameters +// param as a media type conforming to RFC 2045 and RFC 2616. +// The type and parameter names are written in lower-case. +// When any of the arguments result in a standard violation then +// FormatMediaType returns the empty string. +func FormatMediaType(t string, param map[string]string) string { + var b strings.Builder + if major, sub, ok := strings.Cut(t, "/"); !ok { + if !isToken(t) { + return "" + } + b.WriteString(strings.ToLower(t)) + } else { + if !isToken(major) || !isToken(sub) { + return "" + } + b.WriteString(strings.ToLower(major)) + b.WriteByte('/') + b.WriteString(strings.ToLower(sub)) + } + + for _, attribute := range slices.Sorted(maps.Keys(param)) { + value := param[attribute] + b.WriteByte(';') + b.WriteByte(' ') + if !isToken(attribute) { + return "" + } + b.WriteString(strings.ToLower(attribute)) + + needEnc := needsEncoding(value) + if needEnc { + // RFC 2231 section 4 + b.WriteByte('*') + } + b.WriteByte('=') + + if needEnc { + b.WriteString("utf-8''") + + offset := 0 + for index := 0; index < len(value); index++ { + ch := value[index] + // {RFC 2231 section 7} + // attribute-char := + if ch <= ' ' || ch >= 0x7F || + ch == '*' || ch == '\'' || ch == '%' || + isTSpecial(ch) { + + b.WriteString(value[offset:index]) + offset = index + 1 + + b.WriteByte('%') + b.WriteByte(upperhex[ch>>4]) + b.WriteByte(upperhex[ch&0x0F]) + } + } + b.WriteString(value[offset:]) + continue + } + + if isToken(value) { + b.WriteString(value) + continue + } + + b.WriteByte('"') + offset := 0 + for index := 0; index < len(value); index++ { + character := value[index] + if character == '"' || character == '\\' { + b.WriteString(value[offset:index]) + offset = index + b.WriteByte('\\') + } + } + b.WriteString(value[offset:]) + b.WriteByte('"') + } + return b.String() +} + +func checkMediaTypeDisposition(s string) error { + typ, rest := consumeToken(s) + if typ == "" { + return errNoMediaType + } + if rest == "" { + return nil + } + var ok bool + if rest, ok = strings.CutPrefix(rest, "/"); !ok { + return errNoSlashAfterFirstToken + } + subtype, rest := consumeToken(rest) + if subtype == "" { + return errNoTokenAfterSlash + } + if rest != "" { + return errUnexpectedContentAfterMediaSubtype + } + return nil +} + +var ( + errNoMediaType = errors.New("mime: no media type") + errNoSlashAfterFirstToken = errors.New("mime: expected slash after first token") + errNoTokenAfterSlash = errors.New("mime: expected token after slash") + errUnexpectedContentAfterMediaSubtype = errors.New("mime: unexpected content after media subtype") +) + +// ErrInvalidMediaParameter is returned by [ParseMediaType] if +// the media type value was found but there was an error parsing +// the optional parameters +var ErrInvalidMediaParameter = errors.New("mime: invalid media parameter") + +// ParseMediaType parses a media type value and any optional +// parameters, per RFC 1521. Media types are the values in +// Content-Type and Content-Disposition headers (RFC 2183). +// On success, ParseMediaType returns the media type converted +// to lowercase and trimmed of white space and a non-nil map. +// If there is an error parsing the optional parameter, +// the media type will be returned along with the error +// [ErrInvalidMediaParameter]. +// The returned map, params, maps from the lowercase +// attribute to the attribute value with its case preserved. +func ParseMediaType(v string) (mediatype string, params map[string]string, err error) { + base, _, _ := strings.Cut(v, ";") + mediatype = strings.TrimSpace(strings.ToLower(base)) + + err = checkMediaTypeDisposition(mediatype) + if err != nil { + return "", nil, err + } + + params = make(map[string]string) + + // Map of base parameter name -> parameter name -> value + // for parameters containing a '*' character. + // Lazily initialized. + var continuation map[string]map[string]string + + v = v[len(base):] + for len(v) > 0 { + v = strings.TrimLeftFunc(v, unicode.IsSpace) + if len(v) == 0 { + break + } + key, value, rest := consumeMediaParam(v) + if key == "" { + if strings.TrimSpace(rest) == ";" { + // Ignore trailing semicolons. + // Not an error. + break + } + // Parse error. + return mediatype, nil, ErrInvalidMediaParameter + } + + pmap := params + if baseName, _, ok := strings.Cut(key, "*"); ok { + if continuation == nil { + continuation = make(map[string]map[string]string) + } + if pmap, ok = continuation[baseName]; !ok { + continuation[baseName] = make(map[string]string) + pmap = continuation[baseName] + } + } + if v, exists := pmap[key]; exists && v != value { + // Duplicate parameter names are incorrect, but we allow them if they are equal. + return "", nil, errDuplicateParamName + } + pmap[key] = value + v = rest + } + + // Stitch together any continuations or things with stars + // (i.e. RFC 2231 things with stars: "foo*0" or "foo*") + var buf strings.Builder + for key, pieceMap := range continuation { + singlePartKey := key + "*" + if v, ok := pieceMap[singlePartKey]; ok { + if decv, ok := decode2231Enc(v); ok { + params[key] = decv + } + continue + } + + buf.Reset() + valid := false + for n := 0; ; n++ { + simplePart := fmt.Sprintf("%s*%d", key, n) + if v, ok := pieceMap[simplePart]; ok { + valid = true + buf.WriteString(v) + continue + } + encodedPart := simplePart + "*" + v, ok := pieceMap[encodedPart] + if !ok { + break + } + valid = true + if n == 0 { + if decv, ok := decode2231Enc(v); ok { + buf.WriteString(decv) + } + } else { + decv, _ := percentHexUnescape(v) + buf.WriteString(decv) + } + } + if valid { + params[key] = buf.String() + } + } + + return +} + +var errDuplicateParamName = errors.New("mime: duplicate parameter name") + +func decode2231Enc(v string) (string, bool) { + charset, v, ok := strings.Cut(v, "'") + if !ok { + return "", false + } + // TODO: ignoring the language part for now. If anybody needs it, we'll + // need to decide how to expose it in the API. But I'm not sure + // anybody uses it in practice. + _, extOtherVals, ok := strings.Cut(v, "'") + if !ok { + return "", false + } + charset = strings.ToLower(charset) + switch charset { + case "us-ascii", "utf-8": + default: + // Empty or unsupported encoding. + return "", false + } + return percentHexUnescape(extOtherVals) +} + +// consumeToken consumes a token from the beginning of provided +// string, per RFC 2045 section 5.1 (referenced from 2183), and return +// the token consumed and the rest of the string. Returns ("", v) on +// failure to consume at least one character. +func consumeToken(v string) (token, rest string) { + for i := range len(v) { + if !isTokenChar(v[i]) { + return v[:i], v[i:] + } + } + return v, "" +} + +// consumeValue consumes a "value" per RFC 2045, where a value is +// either a 'token' or a 'quoted-string'. On success, consumeValue +// returns the value consumed (and de-quoted/escaped, if a +// quoted-string) and the rest of the string. On failure, returns +// ("", v). +func consumeValue(v string) (value, rest string) { + if v == "" { + return + } + if v[0] != '"' { + return consumeToken(v) + } + + // parse a quoted-string + buffer := new(strings.Builder) + for i := 1; i < len(v); i++ { + r := v[i] + if r == '"' { + return buffer.String(), v[i+1:] + } + // When MSIE sends a full file path (in "intranet mode"), it does not + // escape backslashes: "C:\dev\go\foo.txt", not "C:\\dev\\go\\foo.txt". + // + // No known MIME generators emit unnecessary backslash escapes + // for simple token characters like numbers and letters. + // + // If we see an unnecessary backslash escape, assume it is from MSIE + // and intended as a literal backslash. This makes Go servers deal better + // with MSIE without affecting the way they handle conforming MIME + // generators. + if r == '\\' && i+1 < len(v) && isTSpecial(v[i+1]) { + buffer.WriteByte(v[i+1]) + i++ + continue + } + if r == '\r' || r == '\n' { + return "", v + } + buffer.WriteByte(v[i]) + } + // Did not find end quote. + return "", v +} + +func consumeMediaParam(v string) (param, value, rest string) { + rest = strings.TrimLeftFunc(v, unicode.IsSpace) + var ok bool + if rest, ok = strings.CutPrefix(rest, ";"); !ok { + return "", "", v + } + + rest = strings.TrimLeftFunc(rest, unicode.IsSpace) + param, rest = consumeToken(rest) + param = strings.ToLower(param) + if param == "" { + return "", "", v + } + + rest = strings.TrimLeftFunc(rest, unicode.IsSpace) + if rest, ok = strings.CutPrefix(rest, "="); !ok { + return "", "", v + } + rest = strings.TrimLeftFunc(rest, unicode.IsSpace) + value, rest2 := consumeValue(rest) + if value == "" && rest2 == rest { + return "", "", v + } + rest = rest2 + return param, value, rest +} + +func percentHexUnescape(s string) (string, bool) { + // Count %, check that they're well-formed. + percents := 0 + for i := 0; i < len(s); { + if s[i] != '%' { + i++ + continue + } + percents++ + if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { + return "", false + } + i += 3 + } + if percents == 0 { + return s, true + } + + t := make([]byte, len(s)-2*percents) + j := 0 + for i := 0; i < len(s); { + switch s[i] { + case '%': + t[j] = unhex(s[i+1])<<4 | unhex(s[i+2]) + j++ + i += 3 + default: + t[j] = s[i] + j++ + i++ + } + } + return string(t), true +} + +func ishex(c byte) bool { + switch { + case '0' <= c && c <= '9': + return true + case 'a' <= c && c <= 'f': + return true + case 'A' <= c && c <= 'F': + return true + } + return false +} + +func unhex(c byte) byte { + switch { + case '0' <= c && c <= '9': + return c - '0' + case 'a' <= c && c <= 'f': + return c - 'a' + 10 + case 'A' <= c && c <= 'F': + return c - 'A' + 10 + } + return 0 +} diff --git a/go/src/mime/mediatype_test.go b/go/src/mime/mediatype_test.go new file mode 100644 index 0000000000000000000000000000000000000000..da8d64de7a3f0cbc7c855fd002fbb65e8a5a9d15 --- /dev/null +++ b/go/src/mime/mediatype_test.go @@ -0,0 +1,564 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import ( + "maps" + "strings" + "testing" +) + +func TestConsumeToken(t *testing.T) { + tests := [...][3]string{ + {"foo bar", "foo", " bar"}, + {"bar", "bar", ""}, + {"", "", ""}, + {" foo", "", " foo"}, + } + for _, test := range tests { + token, rest := consumeToken(test[0]) + expectedToken := test[1] + expectedRest := test[2] + if token != expectedToken { + t.Errorf("expected to consume token '%s', not '%s' from '%s'", + expectedToken, token, test[0]) + } else if rest != expectedRest { + t.Errorf("expected to have left '%s', not '%s' after reading token '%s' from '%s'", + expectedRest, rest, token, test[0]) + } + } +} + +func TestConsumeValue(t *testing.T) { + tests := [...][3]string{ + {"foo bar", "foo", " bar"}, + {"bar", "bar", ""}, + {" bar ", "", " bar "}, + {`"My value"end`, "My value", "end"}, + {`"My value" end`, "My value", " end"}, + {`"\\" rest`, "\\", " rest"}, + {`"My \" value"end`, "My \" value", "end"}, + {`"\" rest`, "", `"\" rest`}, + {`"C:\dev\go\robots.txt"`, `C:\dev\go\robots.txt`, ""}, + {`"C:\新建文件夹\中文第二次测试.mp4"`, `C:\新建文件夹\中文第二次测试.mp4`, ""}, + } + for _, test := range tests { + value, rest := consumeValue(test[0]) + expectedValue := test[1] + expectedRest := test[2] + if value != expectedValue { + t.Errorf("expected to consume value [%s], not [%s] from [%s]", + expectedValue, value, test[0]) + } else if rest != expectedRest { + t.Errorf("expected to have left [%s], not [%s] after reading value [%s] from [%s]", + expectedRest, rest, value, test[0]) + } + } +} + +func TestConsumeMediaParam(t *testing.T) { + tests := [...][4]string{ + {" ; foo=bar", "foo", "bar", ""}, + {"; foo=bar", "foo", "bar", ""}, + {";foo=bar", "foo", "bar", ""}, + {";FOO=bar", "foo", "bar", ""}, + {`;foo="bar"`, "foo", "bar", ""}, + {`;foo="bar"; `, "foo", "bar", "; "}, + {`;foo="bar"; foo=baz`, "foo", "bar", "; foo=baz"}, + {` ; boundary=----CUT;`, "boundary", "----CUT", ";"}, + {` ; key=value; blah="value";name="foo" `, "key", "value", `; blah="value";name="foo" `}, + {`; blah="value";name="foo" `, "blah", "value", `;name="foo" `}, + {`;name="foo" `, "name", "foo", ` `}, + } + for _, test := range tests { + param, value, rest := consumeMediaParam(test[0]) + expectedParam := test[1] + expectedValue := test[2] + expectedRest := test[3] + if param != expectedParam { + t.Errorf("expected to consume param [%s], not [%s] from [%s]", + expectedParam, param, test[0]) + } else if value != expectedValue { + t.Errorf("expected to consume value [%s], not [%s] from [%s]", + expectedValue, value, test[0]) + } else if rest != expectedRest { + t.Errorf("expected to have left [%s], not [%s] after reading [%s/%s] from [%s]", + expectedRest, rest, param, value, test[0]) + } + } +} + +type mediaTypeTest struct { + in string + t string + p map[string]string +} + +var parseMediaTypeTests []mediaTypeTest + +func init() { + // Convenience map initializer + m := func(s ...string) map[string]string { + sm := make(map[string]string) + for i := 0; i < len(s); i += 2 { + sm[s[i]] = s[i+1] + } + return sm + } + + nameFoo := map[string]string{"name": "foo"} + parseMediaTypeTests = []mediaTypeTest{ + {`form-data; name="foo"`, "form-data", nameFoo}, + {` form-data ; name=foo`, "form-data", nameFoo}, + {`FORM-DATA;name="foo"`, "form-data", nameFoo}, + {` FORM-DATA ; name="foo"`, "form-data", nameFoo}, + {` FORM-DATA ; name="foo"`, "form-data", nameFoo}, + + {`form-data; key=value; blah="value";name="foo" `, + "form-data", + m("key", "value", "blah", "value", "name", "foo")}, + + {`foo; key=val1; key=the-key-appears-again-which-is-bogus`, + "", m()}, + + // From RFC 2231: + {`application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A`, + "application/x-stuff", + m("title", "This is ***fun***")}, + + {`message/external-body; access-type=URL; ` + + `URL*0="ftp://";` + + `URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"`, + "message/external-body", + m("access-type", "URL", + "url", "ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar")}, + + {`application/x-stuff; ` + + `title*0*=us-ascii'en'This%20is%20even%20more%20; ` + + `title*1*=%2A%2A%2Afun%2A%2A%2A%20; ` + + `title*2="isn't it!"`, + "application/x-stuff", + m("title", "This is even more ***fun*** isn't it!")}, + + // Tests from http://greenbytes.de/tech/tc2231/ + // Note: Backslash escape handling is a bit loose, like MSIE. + + // #attonly + {`attachment`, + "attachment", + m()}, + // #attonlyucase + {`ATTACHMENT`, + "attachment", + m()}, + // #attwithasciifilename + {`attachment; filename="foo.html"`, + "attachment", + m("filename", "foo.html")}, + // #attwithasciifilename25 + {`attachment; filename="0000000000111111111122222"`, + "attachment", + m("filename", "0000000000111111111122222")}, + // #attwithasciifilename35 + {`attachment; filename="00000000001111111111222222222233333"`, + "attachment", + m("filename", "00000000001111111111222222222233333")}, + // #attwithasciifnescapedchar + {`attachment; filename="f\oo.html"`, + "attachment", + m("filename", "f\\oo.html")}, + // #attwithasciifnescapedquote + {`attachment; filename="\"quoting\" tested.html"`, + "attachment", + m("filename", `"quoting" tested.html`)}, + // #attwithquotedsemicolon + {`attachment; filename="Here's a semicolon;.html"`, + "attachment", + m("filename", "Here's a semicolon;.html")}, + // #attwithfilenameandextparam + {`attachment; foo="bar"; filename="foo.html"`, + "attachment", + m("foo", "bar", "filename", "foo.html")}, + // #attwithfilenameandextparamescaped + {`attachment; foo="\"\\";filename="foo.html"`, + "attachment", + m("foo", "\"\\", "filename", "foo.html")}, + // #attwithasciifilenameucase + {`attachment; FILENAME="foo.html"`, + "attachment", + m("filename", "foo.html")}, + // #attwithasciifilenamenq + {`attachment; filename=foo.html`, + "attachment", + m("filename", "foo.html")}, + // #attwithasciifilenamenqs + {`attachment; filename=foo.html ;`, + "attachment", + m("filename", "foo.html")}, + // #attwithfntokensq + {`attachment; filename='foo.html'`, + "attachment", + m("filename", "'foo.html'")}, + // #attwithisofnplain + {`attachment; filename="foo-ä.html"`, + "attachment", + m("filename", "foo-ä.html")}, + // #attwithutf8fnplain + {`attachment; filename="foo-ä.html"`, + "attachment", + m("filename", "foo-ä.html")}, + // #attwithfnrawpctenca + {`attachment; filename="foo-%41.html"`, + "attachment", + m("filename", "foo-%41.html")}, + // #attwithfnusingpct + {`attachment; filename="50%.html"`, + "attachment", + m("filename", "50%.html")}, + // #attwithfnrawpctencaq + {`attachment; filename="foo-%\41.html"`, + "attachment", + m("filename", "foo-%\\41.html")}, + // #attwithnamepct + {`attachment; name="foo-%41.html"`, + "attachment", + m("name", "foo-%41.html")}, + // #attwithfilenamepctandiso + {`attachment; name="ä-%41.html"`, + "attachment", + m("name", "ä-%41.html")}, + // #attwithfnrawpctenclong + {`attachment; filename="foo-%c3%a4-%e2%82%ac.html"`, + "attachment", + m("filename", "foo-%c3%a4-%e2%82%ac.html")}, + // #attwithasciifilenamews1 + {`attachment; filename ="foo.html"`, + "attachment", + m("filename", "foo.html")}, + // #attmissingdisposition + {`filename=foo.html`, + "", m()}, + // #attmissingdisposition2 + {`x=y; filename=foo.html`, + "", m()}, + // #attmissingdisposition3 + {`"foo; filename=bar;baz"; filename=qux`, + "", m()}, + // #attmissingdisposition4 + {`filename=foo.html, filename=bar.html`, + "", m()}, + // #emptydisposition + {`; filename=foo.html`, + "", m()}, + // #doublecolon + {`: inline; attachment; filename=foo.html`, + "", m()}, + // #attandinline + {`inline; attachment; filename=foo.html`, + "", m()}, + // #attandinline2 + {`attachment; inline; filename=foo.html`, + "", m()}, + // #attbrokenquotedfn + {`attachment; filename="foo.html".txt`, + "", m()}, + // #attbrokenquotedfn2 + {`attachment; filename="bar`, + "", m()}, + // #attbrokenquotedfn3 + {`attachment; filename=foo"bar;baz"qux`, + "", m()}, + // #attmultinstances + {`attachment; filename=foo.html, attachment; filename=bar.html`, + "", m()}, + // #attmissingdelim + {`attachment; foo=foo filename=bar`, + "", m()}, + // #attmissingdelim2 + {`attachment; filename=bar foo=foo`, + "", m()}, + // #attmissingdelim3 + {`attachment filename=bar`, + "", m()}, + // #attreversed + {`filename=foo.html; attachment`, + "", m()}, + // #attconfusedparam + {`attachment; xfilename=foo.html`, + "attachment", + m("xfilename", "foo.html")}, + // #attcdate + {`attachment; creation-date="Wed, 12 Feb 1997 16:29:51 -0500"`, + "attachment", + m("creation-date", "Wed, 12 Feb 1997 16:29:51 -0500")}, + // #attmdate + {`attachment; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"`, + "attachment", + m("modification-date", "Wed, 12 Feb 1997 16:29:51 -0500")}, + // #dispext + {`foobar`, "foobar", m()}, + // #dispextbadfn + {`attachment; example="filename=example.txt"`, + "attachment", + m("example", "filename=example.txt")}, + // #attwithfn2231utf8 + {`attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html`, + "attachment", + m("filename", "foo-ä-€.html")}, + // #attwithfn2231noc + {`attachment; filename*=''foo-%c3%a4-%e2%82%ac.html`, + "attachment", + m()}, + // #attwithfn2231utf8comp + {`attachment; filename*=UTF-8''foo-a%cc%88.html`, + "attachment", + m("filename", "foo-ä.html")}, + // #attwithfn2231ws2 + {`attachment; filename*= UTF-8''foo-%c3%a4.html`, + "attachment", + m("filename", "foo-ä.html")}, + // #attwithfn2231ws3 + {`attachment; filename* =UTF-8''foo-%c3%a4.html`, + "attachment", + m("filename", "foo-ä.html")}, + // #attwithfn2231quot + {`attachment; filename*="UTF-8''foo-%c3%a4.html"`, + "attachment", + m("filename", "foo-ä.html")}, + // #attwithfn2231quot2 + {`attachment; filename*="foo%20bar.html"`, + "attachment", + m()}, + // #attwithfn2231singleqmissing + {`attachment; filename*=UTF-8'foo-%c3%a4.html`, + "attachment", + m()}, + // #attwithfn2231nbadpct1 + {`attachment; filename*=UTF-8''foo%`, + "attachment", + m()}, + // #attwithfn2231nbadpct2 + {`attachment; filename*=UTF-8''f%oo.html`, + "attachment", + m()}, + // #attwithfn2231dpct + {`attachment; filename*=UTF-8''A-%2541.html`, + "attachment", + m("filename", "A-%41.html")}, + // #attfncont + {`attachment; filename*0="foo."; filename*1="html"`, + "attachment", + m("filename", "foo.html")}, + // #attfncontenc + {`attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1=".html"`, + "attachment", + m("filename", "foo-ä.html")}, + // #attfncontlz + {`attachment; filename*0="foo"; filename*01="bar"`, + "attachment", + m("filename", "foo")}, + // #attfncontnc + {`attachment; filename*0="foo"; filename*2="bar"`, + "attachment", + m("filename", "foo")}, + // #attfnconts1 + {`attachment; filename*1="foo."; filename*2="html"`, + "attachment", m()}, + // #attfncontord + {`attachment; filename*1="bar"; filename*0="foo"`, + "attachment", + m("filename", "foobar")}, + // #attfnboth + {`attachment; filename="foo-ae.html"; filename*=UTF-8''foo-%c3%a4.html`, + "attachment", + m("filename", "foo-ä.html")}, + // #attfnboth2 + {`attachment; filename*=UTF-8''foo-%c3%a4.html; filename="foo-ae.html"`, + "attachment", + m("filename", "foo-ä.html")}, + // #attfnboth3 + {`attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4; filename*=ISO-8859-1''currency-sign%3d%a4`, + "attachment", + m()}, + // #attnewandfn + {`attachment; foobar=x; filename="foo.html"`, + "attachment", + m("foobar", "x", "filename", "foo.html")}, + + // Browsers also just send UTF-8 directly without RFC 2231, + // at least when the source page is served with UTF-8. + {`form-data; firstname="Брэд"; lastname="Фицпатрик"`, + "form-data", + m("firstname", "Брэд", "lastname", "Фицпатрик")}, + + // Empty string used to be mishandled. + {`foo; bar=""`, "foo", m("bar", "")}, + + // Microsoft browsers in intranet mode do not think they need to escape \ in file name. + {`form-data; name="file"; filename="C:\dev\go\robots.txt"`, "form-data", m("name", "file", "filename", `C:\dev\go\robots.txt`)}, + {`form-data; name="file"; filename="C:\新建文件夹\中文第二次测试.mp4"`, "form-data", m("name", "file", "filename", `C:\新建文件夹\中文第二次测试.mp4`)}, + + // issue #46323 (https://github.com/golang/go/issues/46323) + { + // example from rfc2231-p.3 (https://datatracker.ietf.org/doc/html/rfc2231) + `message/external-body; access-type=URL; + URL*0="ftp://"; + URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar";`, // <-- trailing semicolon + `message/external-body`, + m("access-type", "URL", "url", "ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"), + }, + + // Issue #48866: duplicate parameters containing equal values should be allowed + {`text; charset=utf-8; charset=utf-8; format=fixed`, "text", m("charset", "utf-8", "format", "fixed")}, + {`text; charset=utf-8; format=flowed; charset=utf-8`, "text", m("charset", "utf-8", "format", "flowed")}, + + // Issue #76236: '{' and '}' are token chars. + {"attachment; filename={file}.png", "attachment", m("filename", "{file}.png")}, + } +} + +func TestParseMediaType(t *testing.T) { + for _, test := range parseMediaTypeTests { + mt, params, err := ParseMediaType(test.in) + if err != nil { + if test.t != "" { + t.Errorf("for input %#q, unexpected error: %v", test.in, err) + continue + } + continue + } + if g, e := mt, test.t; g != e { + t.Errorf("for input %#q, expected type %q, got %q", + test.in, e, g) + continue + } + if len(params) == 0 && len(test.p) == 0 { + continue + } + if !maps.Equal(params, test.p) { + t.Errorf("for input %#q, wrong params.\n"+ + "expected: %#v\n"+ + " got: %#v", + test.in, test.p, params) + } + } +} + +func BenchmarkParseMediaType(b *testing.B) { + for range b.N { + for _, test := range parseMediaTypeTests { + ParseMediaType(test.in) + } + } +} + +type badMediaTypeTest struct { + in string + mt string + err string +} + +var badMediaTypeTests = []badMediaTypeTest{ + {"bogus ;=========", "bogus", "mime: invalid media parameter"}, + // The following example is from real email delivered by gmail (error: missing semicolon) + // and it is there to check behavior described in #19498 + {"application/pdf; x-mac-type=\"3F3F3F3F\"; x-mac-creator=\"3F3F3F3F\" name=\"a.pdf\";", + "application/pdf", "mime: invalid media parameter"}, + {"bogus/", "", "mime: expected token after slash"}, + {"bogus/bogus", "", "mime: unexpected content after media subtype"}, + // Tests from http://greenbytes.de/tech/tc2231/ + {`"attachment"`, "attachment", "mime: no media type"}, + {"attachment; filename=foo,bar.html", "attachment", "mime: invalid media parameter"}, + {"attachment; ;filename=foo", "attachment", "mime: invalid media parameter"}, + {"attachment; filename=foo bar.html", "attachment", "mime: invalid media parameter"}, + {`attachment; filename="foo.html"; filename="bar.html"`, "attachment", "mime: duplicate parameter name"}, + {"attachment; filename=foo[1](2).html", "attachment", "mime: invalid media parameter"}, + {"attachment; filename=foo-ä.html", "attachment", "mime: invalid media parameter"}, + {"attachment; filename=foo-ä.html", "attachment", "mime: invalid media parameter"}, + {`attachment; filename *=UTF-8''foo-%c3%a4.html`, "attachment", "mime: invalid media parameter"}, +} + +func TestParseMediaTypeBogus(t *testing.T) { + for _, tt := range badMediaTypeTests { + mt, params, err := ParseMediaType(tt.in) + if err == nil { + t.Errorf("ParseMediaType(%q) = nil error; want parse error", tt.in) + continue + } + if err.Error() != tt.err { + t.Errorf("ParseMediaType(%q) = err %q; want %q", tt.in, err.Error(), tt.err) + } + if params != nil { + t.Errorf("ParseMediaType(%q): got non-nil params on error", tt.in) + } + if err != ErrInvalidMediaParameter && mt != "" { + t.Errorf("ParseMediaType(%q): got unexpected non-empty media type string", tt.in) + } + if err == ErrInvalidMediaParameter && mt != tt.mt { + t.Errorf("ParseMediaType(%q): in case of invalid parameters: expected type %q, got %q", tt.in, tt.mt, mt) + } + } +} + +func BenchmarkParseMediaTypeBogus(b *testing.B) { + for range b.N { + for _, test := range badMediaTypeTests { + ParseMediaType(test.in) + } + } +} + +type formatTest struct { + typ string + params map[string]string + want string +} + +var formatTests = []formatTest{ + {"noslash", map[string]string{"X": "Y"}, "noslash; x=Y"}, // e.g. Content-Disposition values (RFC 2183); issue 11289 + {"foo bar/baz", nil, ""}, + {"foo/bar baz", nil, ""}, + {"attachment", map[string]string{"filename": "ĄĄŽŽČČŠŠ"}, "attachment; filename*=utf-8''%C4%84%C4%84%C5%BD%C5%BD%C4%8C%C4%8C%C5%A0%C5%A0"}, + {"attachment", map[string]string{"filename": "ÁÁÊÊÇÇÎÎ"}, "attachment; filename*=utf-8''%C3%81%C3%81%C3%8A%C3%8A%C3%87%C3%87%C3%8E%C3%8E"}, + {"attachment", map[string]string{"filename": "数据统计.png"}, "attachment; filename*=utf-8''%E6%95%B0%E6%8D%AE%E7%BB%9F%E8%AE%A1.png"}, + {"foo/BAR", nil, "foo/bar"}, + {"foo/BAR", map[string]string{"X": "Y"}, "foo/bar; x=Y"}, + {"foo/BAR", map[string]string{"space": "With space"}, `foo/bar; space="With space"`}, + {"foo/BAR", map[string]string{"quote": `With "quote`}, `foo/bar; quote="With \"quote"`}, + {"foo/BAR", map[string]string{"bslash": `With \backslash`}, `foo/bar; bslash="With \\backslash"`}, + {"foo/BAR", map[string]string{"both": `With \backslash and "quote`}, `foo/bar; both="With \\backslash and \"quote"`}, + {"foo/BAR", map[string]string{"": "empty attribute"}, ""}, + {"foo/BAR", map[string]string{"bad attribute": "baz"}, ""}, + {"foo/BAR", map[string]string{"nonascii": "not an ascii character: ä"}, "foo/bar; nonascii*=utf-8''not%20an%20ascii%20character%3A%20%C3%A4"}, + {"foo/BAR", map[string]string{"ctl": "newline: \n nil: \000"}, "foo/bar; ctl*=utf-8''newline%3A%20%0A%20nil%3A%20%00"}, + {"foo/bar", map[string]string{"a": "av", "b": "bv", "c": "cv"}, "foo/bar; a=av; b=bv; c=cv"}, + {"foo/bar", map[string]string{"0": "'", "9": "'"}, "foo/bar; 0='; 9='"}, + {"foo", map[string]string{"bar": ""}, `foo; bar=""`}, +} + +func TestFormatMediaType(t *testing.T) { + for i, tt := range formatTests { + got := FormatMediaType(tt.typ, tt.params) + if got != tt.want { + t.Errorf("%d. FormatMediaType(%q, %v) = %q; want %q", i, tt.typ, tt.params, got, tt.want) + } + if got == "" { + continue + } + typ, params, err := ParseMediaType(got) + if err != nil { + t.Errorf("%d. ParseMediaType(%q) err: %v", i, got, err) + } + if typ != strings.ToLower(tt.typ) { + t.Errorf("%d. ParseMediaType(%q) typ = %q; want %q", i, got, typ, tt.typ) + } + for k, v := range tt.params { + k = strings.ToLower(k) + if params[k] != v { + t.Errorf("%d. ParseMediaType(%q) params[%s] = %q; want %q", i, got, k, params[k], v) + } + } + } +} diff --git a/go/src/mime/type.go b/go/src/mime/type.go new file mode 100644 index 0000000000000000000000000000000000000000..58cc22fdb0135c331b0cc2d3fd6f409d6eca807e --- /dev/null +++ b/go/src/mime/type.go @@ -0,0 +1,268 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package mime implements parts of the MIME spec. +package mime + +import ( + "fmt" + "slices" + "strings" + "sync" +) + +var ( + mimeTypes sync.Map // map[string]string; ".Z" => "application/x-compress" + mimeTypesLower sync.Map // map[string]string; ".z" => "application/x-compress" + + // extensions maps from MIME type to list of lowercase file + // extensions: "image/jpeg" => [".jfif", ".jpg", ".jpeg", ".pjp", ".pjpeg"] + extensionsMu sync.Mutex // Guards stores (but not loads) on extensions. + extensions sync.Map // map[string][]string; slice values are append-only. +) + +// setMimeTypes is used by initMime's non-test path, and by tests. +func setMimeTypes(lowerExt, mixExt map[string]string) { + mimeTypes.Clear() + mimeTypesLower.Clear() + extensions.Clear() + + for k, v := range lowerExt { + mimeTypesLower.Store(k, v) + } + for k, v := range mixExt { + mimeTypes.Store(k, v) + } + + extensionsMu.Lock() + defer extensionsMu.Unlock() + for k, v := range lowerExt { + justType, _, err := ParseMediaType(v) + if err != nil { + panic(err) + } + var exts []string + if ei, ok := extensions.Load(justType); ok { + exts = ei.([]string) + } + extensions.Store(justType, append(exts, k)) + } +} + +// A type is listed here if both Firefox and Chrome included them in their own +// lists. In the case where they contradict they are deconflicted using IANA's +// listed media types https://www.iana.org/assignments/media-types/media-types.xhtml +// +// Chrome's MIME mappings to file extensions are defined at +// https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/net/base/mime_util.cc +// +// Firefox's MIME types can be found at +// https://github.com/mozilla-firefox/firefox/blob/main/netwerk/mime/nsMimeTypes.h +// and the mappings to file extensions at +// https://github.com/mozilla-firefox/firefox/blob/main/uriloader/exthandler/nsExternalHelperAppService.cpp +var builtinTypesLower = map[string]string{ + ".ai": "application/postscript", + ".apk": "application/vnd.android.package-archive", + ".apng": "image/apng", + ".avif": "image/avif", + ".bin": "application/octet-stream", + ".bmp": "image/bmp", + ".com": "application/octet-stream", + ".css": "text/css; charset=utf-8", + ".csv": "text/csv; charset=utf-8", + ".doc": "application/msword", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".ehtml": "text/html; charset=utf-8", + ".eml": "message/rfc822", + ".eps": "application/postscript", + ".exe": "application/octet-stream", + ".flac": "audio/flac", + ".gif": "image/gif", + ".gz": "application/gzip", + ".htm": "text/html; charset=utf-8", + ".html": "text/html; charset=utf-8", + ".ico": "image/vnd.microsoft.icon", + ".ics": "text/calendar; charset=utf-8", + ".jfif": "image/jpeg", + ".jpeg": "image/jpeg", + ".jpg": "image/jpeg", + ".js": "text/javascript; charset=utf-8", + ".json": "application/json", + ".m4a": "audio/mp4", + ".mjs": "text/javascript; charset=utf-8", + ".mp3": "audio/mpeg", + ".mp4": "video/mp4", + ".oga": "audio/ogg", + ".ogg": "audio/ogg", + ".ogv": "video/ogg", + ".opus": "audio/ogg", + ".pdf": "application/pdf", + ".pjp": "image/jpeg", + ".pjpeg": "image/jpeg", + ".png": "image/png", + ".ppt": "application/vnd.ms-powerpoint", + ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ".ps": "application/postscript", + ".rdf": "application/rdf+xml", + ".rtf": "application/rtf", + ".shtml": "text/html; charset=utf-8", + ".svg": "image/svg+xml", + ".text": "text/plain; charset=utf-8", + ".tif": "image/tiff", + ".tiff": "image/tiff", + ".txt": "text/plain; charset=utf-8", + ".vtt": "text/vtt; charset=utf-8", + ".wasm": "application/wasm", + ".wav": "audio/wav", + ".webm": "audio/webm", + ".webp": "image/webp", + ".xbl": "text/xml; charset=utf-8", + ".xbm": "image/x-xbitmap", + ".xht": "application/xhtml+xml", + ".xhtml": "application/xhtml+xml", + ".xls": "application/vnd.ms-excel", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".xml": "text/xml; charset=utf-8", + ".xsl": "text/xml; charset=utf-8", + ".zip": "application/zip", +} + +var once sync.Once // guards initMime + +var testInitMime, osInitMime func() + +func initMime() { + if fn := testInitMime; fn != nil { + fn() + } else { + setMimeTypes(builtinTypesLower, builtinTypesLower) + osInitMime() + } +} + +// TypeByExtension returns the MIME type associated with the file extension ext. +// The extension ext should begin with a leading dot, as in ".html". +// When ext has no associated type, TypeByExtension returns "". +// +// Extensions are looked up first case-sensitively, then case-insensitively. +// +// The built-in table is small but on unix it is augmented by the local +// system's MIME-info database or mime.types file(s) if available under one or +// more of these names: +// +// /usr/local/share/mime/globs2 +// /usr/share/mime/globs2 +// /etc/mime.types +// /etc/apache2/mime.types +// /etc/apache/mime.types +// /etc/httpd/conf/mime.types +// +// On Windows, MIME types are extracted from the registry. +// +// Text types have the charset parameter set to "utf-8" by default. +func TypeByExtension(ext string) string { + once.Do(initMime) + + // Case-sensitive lookup. + if v, ok := mimeTypes.Load(ext); ok { + return v.(string) + } + + // Case-insensitive lookup. + // Optimistically assume a short ASCII extension and be + // allocation-free in that case. + var buf [10]byte + lower := buf[:0] + const utf8RuneSelf = 0x80 // from utf8 package, but not importing it. + for i := 0; i < len(ext); i++ { + c := ext[i] + if c >= utf8RuneSelf { + // Slow path. + si, _ := mimeTypesLower.Load(strings.ToLower(ext)) + s, _ := si.(string) + return s + } + if 'A' <= c && c <= 'Z' { + lower = append(lower, c+('a'-'A')) + } else { + lower = append(lower, c) + } + } + si, _ := mimeTypesLower.Load(string(lower)) + s, _ := si.(string) + return s +} + +// ExtensionsByType returns the extensions known to be associated with the MIME +// type typ. The returned extensions will each begin with a leading dot, as in +// ".html". When typ has no associated extensions, ExtensionsByType returns an +// nil slice. +// +// The built-in table is small but on unix it is augmented by the local +// system's MIME-info database or mime.types file(s) if available under one or +// more of these names: +// +// /usr/local/share/mime/globs2 +// /usr/share/mime/globs2 +// /etc/mime.types +// /etc/apache2/mime.types +// /etc/apache/mime.types +// /etc/httpd/conf/mime.types +// +// On Windows, extensions are extracted from the registry. +func ExtensionsByType(typ string) ([]string, error) { + justType, _, err := ParseMediaType(typ) + if err != nil { + return nil, err + } + + once.Do(initMime) + s, ok := extensions.Load(justType) + if !ok { + return nil, nil + } + ret := append([]string(nil), s.([]string)...) + slices.Sort(ret) + return ret, nil +} + +// AddExtensionType sets the MIME type associated with +// the extension ext to typ. The extension should begin with +// a leading dot, as in ".html". +func AddExtensionType(ext, typ string) error { + if !strings.HasPrefix(ext, ".") { + return fmt.Errorf("mime: extension %q missing leading dot", ext) + } + once.Do(initMime) + return setExtensionType(ext, typ) +} + +func setExtensionType(extension, mimeType string) error { + justType, param, err := ParseMediaType(mimeType) + if err != nil { + return err + } + if strings.HasPrefix(mimeType, "text/") && param["charset"] == "" { + param["charset"] = "utf-8" + mimeType = FormatMediaType(mimeType, param) + } + extLower := strings.ToLower(extension) + + mimeTypes.Store(extension, mimeType) + mimeTypesLower.Store(extLower, mimeType) + + extensionsMu.Lock() + defer extensionsMu.Unlock() + var exts []string + if ei, ok := extensions.Load(justType); ok { + exts = ei.([]string) + } + for _, v := range exts { + if v == extLower { + return nil + } + } + extensions.Store(justType, append(exts, extLower)) + return nil +} diff --git a/go/src/mime/type_dragonfly.go b/go/src/mime/type_dragonfly.go new file mode 100644 index 0000000000000000000000000000000000000000..d09d74a9cce251236f2831a3ef71575fdd138c87 --- /dev/null +++ b/go/src/mime/type_dragonfly.go @@ -0,0 +1,9 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +func init() { + typeFiles = append(typeFiles, "/usr/local/etc/mime.types") +} diff --git a/go/src/mime/type_freebsd.go b/go/src/mime/type_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..d09d74a9cce251236f2831a3ef71575fdd138c87 --- /dev/null +++ b/go/src/mime/type_freebsd.go @@ -0,0 +1,9 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +func init() { + typeFiles = append(typeFiles, "/usr/local/etc/mime.types") +} diff --git a/go/src/mime/type_openbsd.go b/go/src/mime/type_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..c3b1abb99fc0a457373b9f01b8d45fc7e7251154 --- /dev/null +++ b/go/src/mime/type_openbsd.go @@ -0,0 +1,9 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +func init() { + typeFiles = append(typeFiles, "/usr/share/misc/mime.types") +} diff --git a/go/src/mime/type_plan9.go b/go/src/mime/type_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..14ff973405186392163ed42dd5db5b1d6e47fec7 --- /dev/null +++ b/go/src/mime/type_plan9.go @@ -0,0 +1,57 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import ( + "bufio" + "os" + "strings" +) + +func init() { + osInitMime = initMimePlan9 +} + +func initMimePlan9() { + for _, filename := range typeFiles { + loadMimeFile(filename) + } +} + +var typeFiles = []string{ + "/sys/lib/mimetype", +} + +func initMimeForTests() map[string]string { + typeFiles = []string{"testdata/test.types.plan9"} + return map[string]string{ + ".t1": "application/test", + ".t2": "text/test; charset=utf-8", + ".pNg": "image/png", + } +} + +func loadMimeFile(filename string) { + f, err := os.Open(filename) + if err != nil { + return + } + defer f.Close() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + fields := strings.Fields(scanner.Text()) + if len(fields) <= 2 || fields[0][0] != '.' { + continue + } + if fields[1] == "-" || fields[2] == "-" { + continue + } + setExtensionType(fields[0], fields[1]+"/"+fields[2]) + } + if err := scanner.Err(); err != nil { + panic(err) + } +} diff --git a/go/src/mime/type_test.go b/go/src/mime/type_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f4ec8c8754e69fd373bc37f02e59a988b8b46a3f --- /dev/null +++ b/go/src/mime/type_test.go @@ -0,0 +1,268 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import ( + "internal/asan" + "slices" + "strings" + "sync" + "testing" +) + +func setMimeInit(fn func()) (cleanup func()) { + once = sync.Once{} + testInitMime = fn + return func() { + testInitMime = nil + once = sync.Once{} + } +} + +func clearMimeTypes() { + setMimeTypes(map[string]string{}, map[string]string{}) +} + +func setType(ext, typ string) { + if !strings.HasPrefix(ext, ".") { + panic("missing leading dot") + } + if err := setExtensionType(ext, typ); err != nil { + panic("bad test data: " + err.Error()) + } +} + +func TestTypeByExtension(t *testing.T) { + once = sync.Once{} + // initMimeForTests returns the platform-specific extension => + // type tests. On Unix and Plan 9, this also tests the parsing + // of MIME text files (in testdata/*). On Windows, we test the + // real registry on the machine and assume that ".png" exists + // there, which empirically it always has, for all versions of + // Windows. + typeTests := initMimeForTests() + + for ext, want := range typeTests { + val := TypeByExtension(ext) + if val != want { + t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want) + } + } +} + +func TestTypeByExtension_LocalData(t *testing.T) { + cleanup := setMimeInit(func() { + clearMimeTypes() + setType(".foo", "x/foo") + setType(".bar", "x/bar") + setType(".Bar", "x/bar; capital=1") + }) + defer cleanup() + + tests := map[string]string{ + ".foo": "x/foo", + ".bar": "x/bar", + ".Bar": "x/bar; capital=1", + ".sdlkfjskdlfj": "", + ".t1": "", // testdata shouldn't be used + } + + for ext, want := range tests { + val := TypeByExtension(ext) + if val != want { + t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want) + } + } +} + +func TestTypeByExtensionCase(t *testing.T) { + const custom = "test/test; charset=iso-8859-1" + const caps = "test/test; WAS=ALLCAPS" + + cleanup := setMimeInit(func() { + clearMimeTypes() + setType(".TEST", caps) + setType(".tesT", custom) + }) + defer cleanup() + + // case-sensitive lookup + if got := TypeByExtension(".tesT"); got != custom { + t.Fatalf("for .tesT, got %q; want %q", got, custom) + } + if got := TypeByExtension(".TEST"); got != caps { + t.Fatalf("for .TEST, got %q; want %s", got, caps) + } + + // case-insensitive + if got := TypeByExtension(".TesT"); got != custom { + t.Fatalf("for .TesT, got %q; want %q", got, custom) + } +} + +func TestExtensionsByType(t *testing.T) { + cleanup := setMimeInit(func() { + clearMimeTypes() + setType(".gif", "image/gif") + setType(".a", "foo/letter") + setType(".b", "foo/letter") + setType(".B", "foo/letter") + setType(".PNG", "image/png") + }) + defer cleanup() + + tests := []struct { + typ string + want []string + wantErr string + }{ + {typ: "image/gif", want: []string{".gif"}}, + {typ: "image/png", want: []string{".png"}}, // lowercase + {typ: "foo/letter", want: []string{".a", ".b"}}, + {typ: "x/unknown", want: nil}, + } + + for _, tt := range tests { + got, err := ExtensionsByType(tt.typ) + if err != nil && tt.wantErr != "" && strings.Contains(err.Error(), tt.wantErr) { + continue + } + if err != nil { + t.Errorf("ExtensionsByType(%q) error: %v", tt.typ, err) + continue + } + if tt.wantErr != "" { + t.Errorf("ExtensionsByType(%q) = %q, %v; want error substring %q", tt.typ, got, err, tt.wantErr) + continue + } + if !slices.Equal(got, tt.want) { + t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want) + } + } +} + +func TestLookupMallocs(t *testing.T) { + if asan.Enabled { + t.Skip("test allocates more with -asan; see #70079") + } + n := testing.AllocsPerRun(10000, func() { + TypeByExtension(".html") + TypeByExtension(".HtML") + }) + if n > 0 { + t.Errorf("allocs = %v; want 0", n) + } +} + +func BenchmarkTypeByExtension(b *testing.B) { + initMime() + b.ResetTimer() + + for _, ext := range []string{ + ".html", + ".HTML", + ".unused", + } { + b.Run(ext, func(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + TypeByExtension(ext) + } + }) + }) + } +} + +func BenchmarkExtensionsByType(b *testing.B) { + initMime() + b.ResetTimer() + + for _, typ := range []string{ + "text/html", + "text/html; charset=utf-8", + "application/octet-stream", + } { + b.Run(typ, func(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + if _, err := ExtensionsByType(typ); err != nil { + b.Fatal(err) + } + } + }) + }) + } +} + +func TestExtensionsByType2(t *testing.T) { + cleanup := setMimeInit(func() { + clearMimeTypes() + // Initialize built-in types like in type.go before osInitMime. + setMimeTypes(builtinTypesLower, builtinTypesLower) + }) + defer cleanup() + + tests := []struct { + typ string + want []string + }{ + {typ: "application/postscript", want: []string{".ai", ".eps", ".ps"}}, + {typ: "application/vnd.android.package-archive", want: []string{".apk"}}, + {typ: "image/apng", want: []string{".apng"}}, + {typ: "image/avif", want: []string{".avif"}}, + {typ: "application/octet-stream", want: []string{".bin", ".com", ".exe"}}, + {typ: "image/bmp", want: []string{".bmp"}}, + {typ: "text/css; charset=utf-8", want: []string{".css"}}, + {typ: "text/csv; charset=utf-8", want: []string{".csv"}}, + {typ: "application/msword", want: []string{".doc"}}, + {typ: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", want: []string{".docx"}}, + {typ: "text/html; charset=utf-8", want: []string{".ehtml", ".htm", ".html", ".shtml"}}, + {typ: "message/rfc822", want: []string{".eml"}}, + {typ: "audio/flac", want: []string{".flac"}}, + {typ: "image/gif", want: []string{".gif"}}, + {typ: "application/gzip", want: []string{".gz"}}, + {typ: "image/vnd.microsoft.icon", want: []string{".ico"}}, + {typ: "text/calendar; charset=utf-8", want: []string{".ics"}}, + {typ: "image/jpeg", want: []string{".jfif", ".jpeg", ".jpg", ".pjp", ".pjpeg"}}, + {typ: "text/javascript; charset=utf-8", want: []string{".js", ".mjs"}}, + {typ: "application/json", want: []string{".json"}}, + {typ: "audio/mp4", want: []string{".m4a"}}, + {typ: "audio/mpeg", want: []string{".mp3"}}, + {typ: "video/mp4", want: []string{".mp4"}}, + {typ: "audio/ogg", want: []string{".oga", ".ogg", ".opus"}}, + {typ: "video/ogg", want: []string{".ogv"}}, + {typ: "application/pdf", want: []string{".pdf"}}, + {typ: "image/png", want: []string{".png"}}, + {typ: "application/vnd.ms-powerpoint", want: []string{".ppt"}}, + {typ: "application/vnd.openxmlformats-officedocument.presentationml.presentation", want: []string{".pptx"}}, + {typ: "application/rdf+xml", want: []string{".rdf"}}, + {typ: "application/rtf", want: []string{".rtf"}}, + {typ: "image/svg+xml", want: []string{".svg"}}, + {typ: "text/plain; charset=utf-8", want: []string{".text", ".txt"}}, + {typ: "image/tiff", want: []string{".tif", ".tiff"}}, + {typ: "text/vtt; charset=utf-8", want: []string{".vtt"}}, + {typ: "application/wasm", want: []string{".wasm"}}, + {typ: "audio/wav", want: []string{".wav"}}, + {typ: "audio/webm", want: []string{".webm"}}, + {typ: "image/webp", want: []string{".webp"}}, + {typ: "text/xml; charset=utf-8", want: []string{".xbl", ".xml", ".xsl"}}, + {typ: "image/x-xbitmap", want: []string{".xbm"}}, + {typ: "application/xhtml+xml", want: []string{".xht", ".xhtml"}}, + {typ: "application/vnd.ms-excel", want: []string{".xls"}}, + {typ: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", want: []string{".xlsx"}}, + {typ: "application/zip", want: []string{".zip"}}, + } + + for _, tt := range tests { + got, err := ExtensionsByType(tt.typ) + if err != nil { + t.Errorf("ExtensionsByType(%q): %v", tt.typ, err) + continue + } + if !slices.Equal(got, tt.want) { + t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want) + } + } +} diff --git a/go/src/mime/type_unix.go b/go/src/mime/type_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..90414c1a18d06fa745be402f66b731a61923e4a1 --- /dev/null +++ b/go/src/mime/type_unix.go @@ -0,0 +1,126 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || (js && wasm) || wasip1 + +package mime + +import ( + "bufio" + "os" + "strings" +) + +func init() { + osInitMime = initMimeUnix +} + +// See https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-0.21.html +// for the FreeDesktop Shared MIME-info Database specification. +var mimeGlobs = []string{ + "/usr/local/share/mime/globs2", + "/usr/share/mime/globs2", +} + +// Common locations for mime.types files on unix. +var typeFiles = []string{ + "/etc/mime.types", + "/etc/apache2/mime.types", + "/etc/apache/mime.types", + "/etc/httpd/conf/mime.types", +} + +func loadMimeGlobsFile(filename string) error { + f, err := os.Open(filename) + if err != nil { + return err + } + defer f.Close() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + // Each line should be of format: weight:mimetype:glob[:morefields...] + fields := strings.Split(scanner.Text(), ":") + if len(fields) < 3 || len(fields[0]) < 1 || len(fields[2]) < 3 { + continue + } else if fields[0][0] == '#' || fields[2][0] != '*' || fields[2][1] != '.' { + continue + } + + extension := fields[2][1:] + if strings.ContainsAny(extension, "?*[") { + // Not a bare extension, but a glob. Ignore for now: + // - we do not have an implementation for this glob + // syntax (translation to path/filepath.Match could + // be possible) + // - support for globs with weight ordering would have + // performance impact to all lookups to support the + // rarely seen glob entries + // - trying to match glob metacharacters literally is + // not useful + continue + } + if _, ok := mimeTypes.Load(extension); ok { + // We've already seen this extension. + // The file is in weight order, so we keep + // the first entry that we see. + continue + } + + setExtensionType(extension, fields[1]) + } + if err := scanner.Err(); err != nil { + panic(err) + } + return nil +} + +func loadMimeFile(filename string) { + f, err := os.Open(filename) + if err != nil { + return + } + defer f.Close() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + fields := strings.Fields(scanner.Text()) + if len(fields) <= 1 || fields[0][0] == '#' { + continue + } + mimeType := fields[0] + for _, ext := range fields[1:] { + if ext[0] == '#' { + break + } + setExtensionType("."+ext, mimeType) + } + } + if err := scanner.Err(); err != nil { + panic(err) + } +} + +func initMimeUnix() { + for _, filename := range mimeGlobs { + if err := loadMimeGlobsFile(filename); err == nil { + return // Stop checking more files if mimetype database is found. + } + } + + // Fallback if no system-generated mimetype database exists. + for _, filename := range typeFiles { + loadMimeFile(filename) + } +} + +func initMimeForTests() map[string]string { + mimeGlobs = []string{""} + typeFiles = []string{"testdata/test.types"} + return map[string]string{ + ".T1": "application/test", + ".t2": "text/test; charset=utf-8", + ".png": "image/png", + } +} diff --git a/go/src/mime/type_unix_test.go b/go/src/mime/type_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7b8db79d272a986b3a0df156a5489187d0fabf80 --- /dev/null +++ b/go/src/mime/type_unix_test.go @@ -0,0 +1,44 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || (js && wasm) + +package mime + +import ( + "testing" +) + +func initMimeUnixTest(t *testing.T) { + once.Do(initMime) + err := loadMimeGlobsFile("testdata/test.types.globs2") + if err != nil { + t.Fatal(err) + } + + loadMimeFile("testdata/test.types") +} + +func TestTypeByExtensionUNIX(t *testing.T) { + initMimeUnixTest(t) + typeTests := map[string]string{ + ".T1": "application/test", + ".t2": "text/test; charset=utf-8", + ".t3": "document/test", + ".t4": "example/test", + ".png": "image/png", + ",v": "", + "~": "", + ".foo?ar": "", + ".foo*r": "", + ".foo[1-3]": "", + } + + for ext, want := range typeTests { + val := TypeByExtension(ext) + if val != want { + t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want) + } + } +} diff --git a/go/src/mime/type_windows.go b/go/src/mime/type_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..93802141c532d0f79daeecd356d022a89cbd6167 --- /dev/null +++ b/go/src/mime/type_windows.go @@ -0,0 +1,52 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import ( + "internal/syscall/windows/registry" +) + +func init() { + osInitMime = initMimeWindows +} + +func initMimeWindows() { + names, err := registry.CLASSES_ROOT.ReadSubKeyNames() + if err != nil { + return + } + for _, name := range names { + if len(name) < 2 || name[0] != '.' { // looking for extensions only + continue + } + k, err := registry.OpenKey(registry.CLASSES_ROOT, name, registry.READ) + if err != nil { + continue + } + v, _, err := k.GetStringValue("Content Type") + k.Close() + if err != nil { + continue + } + + // There is a long-standing problem on Windows: the + // registry sometimes records that the ".js" extension + // should be "text/plain". See issue #32350. While + // normally local configuration should override + // defaults, this problem is common enough that we + // handle it here by ignoring that registry setting. + if name == ".js" && (v == "text/plain" || v == "text/plain; charset=utf-8") { + continue + } + + setExtensionType(name, v) + } +} + +func initMimeForTests() map[string]string { + return map[string]string{ + ".PnG": "image/png", + } +} diff --git a/go/src/net/addrselect.go b/go/src/net/addrselect.go new file mode 100644 index 0000000000000000000000000000000000000000..0ff8ec37c8de35cdfa2cb2b7c8dbc5f99d233dba --- /dev/null +++ b/go/src/net/addrselect.go @@ -0,0 +1,368 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Minimal RFC 6724 address selection. + +package net + +import ( + "net/netip" + "slices" +) + +func sortByRFC6724(addrs []IPAddr) { + if len(addrs) < 2 { + return + } + sortByRFC6724withSrcs(addrs, srcAddrs(addrs)) +} + +func sortByRFC6724withSrcs(addrs []IPAddr, srcs []netip.Addr) { + if len(addrs) != len(srcs) { + panic("internal error") + } + addrInfos := make([]byRFC6724Info, len(addrs)) + for i, v := range addrs { + addrAttrIP, _ := netip.AddrFromSlice(v.IP) + addrInfos[i] = byRFC6724Info{ + addr: addrs[i], + addrAttr: ipAttrOf(addrAttrIP), + src: srcs[i], + srcAttr: ipAttrOf(srcs[i]), + } + } + slices.SortStableFunc(addrInfos, compareByRFC6724) + for i := range addrInfos { + addrs[i] = addrInfos[i].addr + } +} + +// srcAddrs tries to UDP-connect to each address to see if it has a +// route. (This doesn't send any packets). The destination port +// number is irrelevant. +func srcAddrs(addrs []IPAddr) []netip.Addr { + srcs := make([]netip.Addr, len(addrs)) + dst := UDPAddr{Port: 53} + for i := range addrs { + dst.IP = addrs[i].IP + dst.Zone = addrs[i].Zone + c, err := DialUDP("udp", nil, &dst) + if err == nil { + if src, ok := c.LocalAddr().(*UDPAddr); ok { + srcs[i], _ = netip.AddrFromSlice(src.IP) + } + c.Close() + } + } + return srcs +} + +type ipAttr struct { + Scope scope + Precedence uint8 + Label uint8 +} + +func ipAttrOf(ip netip.Addr) ipAttr { + if !ip.IsValid() { + return ipAttr{} + } + match := rfc6724policyTable.Classify(ip) + return ipAttr{ + Scope: classifyScope(ip), + Precedence: match.Precedence, + Label: match.Label, + } +} + +type byRFC6724Info struct { + addr IPAddr + addrAttr ipAttr + src netip.Addr + srcAttr ipAttr +} + +// compareByRFC6724 compares two byRFC6724Info records and returns an integer +// indicating the order. It follows the algorithm and variable names from +// RFC 6724 section 6. Returns -1 if a is preferred, 1 if b is preferred, +// and 0 if they are equal. +func compareByRFC6724(a, b byRFC6724Info) int { + DA := a.addr.IP + DB := b.addr.IP + SourceDA := a.src + SourceDB := b.src + attrDA := &a.addrAttr + attrDB := &b.addrAttr + attrSourceDA := &a.srcAttr + attrSourceDB := &b.srcAttr + + const preferDA = -1 + const preferDB = 1 + + // Rule 1: Avoid unusable destinations. + // If DB is known to be unreachable or if Source(DB) is undefined, then + // prefer DA. Similarly, if DA is known to be unreachable or if + // Source(DA) is undefined, then prefer DB. + if !SourceDA.IsValid() && !SourceDB.IsValid() { + return 0 // "equal" + } + if !SourceDB.IsValid() { + return preferDA + } + if !SourceDA.IsValid() { + return preferDB + } + + // Rule 2: Prefer matching scope. + // If Scope(DA) = Scope(Source(DA)) and Scope(DB) <> Scope(Source(DB)), + // then prefer DA. Similarly, if Scope(DA) <> Scope(Source(DA)) and + // Scope(DB) = Scope(Source(DB)), then prefer DB. + if attrDA.Scope == attrSourceDA.Scope && attrDB.Scope != attrSourceDB.Scope { + return preferDA + } + if attrDA.Scope != attrSourceDA.Scope && attrDB.Scope == attrSourceDB.Scope { + return preferDB + } + + // Rule 3: Avoid deprecated addresses. + // If Source(DA) is deprecated and Source(DB) is not, then prefer DB. + // Similarly, if Source(DA) is not deprecated and Source(DB) is + // deprecated, then prefer DA. + + // TODO(bradfitz): implement? low priority for now. + + // Rule 4: Prefer home addresses. + // If Source(DA) is simultaneously a home address and care-of address + // and Source(DB) is not, then prefer DA. Similarly, if Source(DB) is + // simultaneously a home address and care-of address and Source(DA) is + // not, then prefer DB. + + // TODO(bradfitz): implement? low priority for now. + + // Rule 5: Prefer matching label. + // If Label(Source(DA)) = Label(DA) and Label(Source(DB)) <> Label(DB), + // then prefer DA. Similarly, if Label(Source(DA)) <> Label(DA) and + // Label(Source(DB)) = Label(DB), then prefer DB. + if attrSourceDA.Label == attrDA.Label && + attrSourceDB.Label != attrDB.Label { + return preferDA + } + if attrSourceDA.Label != attrDA.Label && + attrSourceDB.Label == attrDB.Label { + return preferDB + } + + // Rule 6: Prefer higher precedence. + // If Precedence(DA) > Precedence(DB), then prefer DA. Similarly, if + // Precedence(DA) < Precedence(DB), then prefer DB. + if attrDA.Precedence > attrDB.Precedence { + return preferDA + } + if attrDA.Precedence < attrDB.Precedence { + return preferDB + } + + // Rule 7: Prefer native transport. + // If DA is reached via an encapsulating transition mechanism (e.g., + // IPv6 in IPv4) and DB is not, then prefer DB. Similarly, if DB is + // reached via encapsulation and DA is not, then prefer DA. + + // TODO(bradfitz): implement? low priority for now. + + // Rule 8: Prefer smaller scope. + // If Scope(DA) < Scope(DB), then prefer DA. Similarly, if Scope(DA) > + // Scope(DB), then prefer DB. + if attrDA.Scope < attrDB.Scope { + return preferDA + } + if attrDA.Scope > attrDB.Scope { + return preferDB + } + + // Rule 9: Use the longest matching prefix. + // When DA and DB belong to the same address family (both are IPv6 or + // both are IPv4 [but see below]): If CommonPrefixLen(Source(DA), DA) > + // CommonPrefixLen(Source(DB), DB), then prefer DA. Similarly, if + // CommonPrefixLen(Source(DA), DA) < CommonPrefixLen(Source(DB), DB), + // then prefer DB. + // + // However, applying this rule to IPv4 addresses causes + // problems (see issues 13283 and 18518), so limit to IPv6. + if DA.To4() == nil && DB.To4() == nil { + commonA := commonPrefixLen(SourceDA, DA) + commonB := commonPrefixLen(SourceDB, DB) + + if commonA > commonB { + return preferDA + } + if commonA < commonB { + return preferDB + } + } + + // Rule 10: Otherwise, leave the order unchanged. + // If DA preceded DB in the original list, prefer DA. + // Otherwise, prefer DB. + return 0 // "equal" +} + +type policyTableEntry struct { + Prefix netip.Prefix + Precedence uint8 + Label uint8 +} + +type policyTable []policyTableEntry + +// RFC 6724 section 2.1. +// Items are sorted by the size of their Prefix.Mask.Size, +var rfc6724policyTable = policyTable{ + { + // "::1/128" + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}), 128), + Precedence: 50, + Label: 0, + }, + { + // "::ffff:0:0/96" + // IPv4-compatible, etc. + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}), 96), + Precedence: 35, + Label: 4, + }, + { + // "::/96" + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{}), 96), + Precedence: 1, + Label: 3, + }, + { + // "2001::/32" + // Teredo + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0x20, 0x01}), 32), + Precedence: 5, + Label: 5, + }, + { + // "2002::/16" + // 6to4 + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0x20, 0x02}), 16), + Precedence: 30, + Label: 2, + }, + { + // "3ffe::/16" + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0x3f, 0xfe}), 16), + Precedence: 1, + Label: 12, + }, + { + // "fec0::/10" + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0xfe, 0xc0}), 10), + Precedence: 1, + Label: 11, + }, + { + // "fc00::/7" + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0xfc}), 7), + Precedence: 3, + Label: 13, + }, + { + // "::/0" + Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{}), 0), + Precedence: 40, + Label: 1, + }, +} + +// Classify returns the policyTableEntry of the entry with the longest +// matching prefix that contains ip. +// The table t must be sorted from largest mask size to smallest. +func (t policyTable) Classify(ip netip.Addr) policyTableEntry { + // Prefix.Contains() will not match an IPv6 prefix for an IPv4 address. + if ip.Is4() { + ip = netip.AddrFrom16(ip.As16()) + } + for _, ent := range t { + if ent.Prefix.Contains(ip) { + return ent + } + } + return policyTableEntry{} +} + +// RFC 6724 section 3.1. +type scope uint8 + +const ( + scopeInterfaceLocal scope = 0x1 + scopeLinkLocal scope = 0x2 + scopeAdminLocal scope = 0x4 + scopeSiteLocal scope = 0x5 + scopeOrgLocal scope = 0x8 + scopeGlobal scope = 0xe +) + +func classifyScope(ip netip.Addr) scope { + if ip.IsLoopback() || ip.IsLinkLocalUnicast() { + return scopeLinkLocal + } + ipv6 := ip.Is6() && !ip.Is4In6() + ipv6AsBytes := ip.As16() + if ipv6 && ip.IsMulticast() { + return scope(ipv6AsBytes[1] & 0xf) + } + // Site-local addresses are defined in RFC 3513 section 2.5.6 + // (and deprecated in RFC 3879). + if ipv6 && ipv6AsBytes[0] == 0xfe && ipv6AsBytes[1]&0xc0 == 0xc0 { + return scopeSiteLocal + } + return scopeGlobal +} + +// commonPrefixLen reports the length of the longest prefix (looking +// at the most significant, or leftmost, bits) that the +// two addresses have in common, up to the length of a's prefix (i.e., +// the portion of the address not including the interface ID). +// +// If a or b is an IPv4 address as an IPv6 address, the IPv4 addresses +// are compared (with max common prefix length of 32). +// If a and b are different IP versions, 0 is returned. +// +// See https://tools.ietf.org/html/rfc6724#section-2.2 +func commonPrefixLen(a netip.Addr, b IP) (cpl int) { + if b4 := b.To4(); b4 != nil { + b = b4 + } + aAsSlice := a.AsSlice() + if len(aAsSlice) != len(b) { + return 0 + } + // If IPv6, only up to the prefix (first 64 bits) + if len(aAsSlice) > 8 { + aAsSlice = aAsSlice[:8] + b = b[:8] + } + for len(aAsSlice) > 0 { + if aAsSlice[0] == b[0] { + cpl += 8 + aAsSlice = aAsSlice[1:] + b = b[1:] + continue + } + bits := 8 + ab, bb := aAsSlice[0], b[0] + for { + ab >>= 1 + bb >>= 1 + bits-- + if ab == bb { + cpl += bits + return + } + } + } + return +} diff --git a/go/src/net/addrselect_test.go b/go/src/net/addrselect_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7e8134d754447b2d97eef3b8e4e979a5f1a729d1 --- /dev/null +++ b/go/src/net/addrselect_test.go @@ -0,0 +1,312 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris + +package net + +import ( + "net/netip" + "reflect" + "testing" +) + +func TestSortByRFC6724(t *testing.T) { + tests := []struct { + in []IPAddr + srcs []netip.Addr + want []IPAddr + reverse bool // also test it starting backwards + }{ + // Examples from RFC 6724 section 10.2: + + // Prefer matching scope. + { + in: []IPAddr{ + {IP: ParseIP("2001:db8:1::1")}, + {IP: ParseIP("198.51.100.121")}, + }, + srcs: []netip.Addr{ + netip.MustParseAddr("2001:db8:1::2"), + netip.MustParseAddr("169.254.13.78"), + }, + want: []IPAddr{ + {IP: ParseIP("2001:db8:1::1")}, + {IP: ParseIP("198.51.100.121")}, + }, + reverse: true, + }, + + // Prefer matching scope. + { + in: []IPAddr{ + {IP: ParseIP("2001:db8:1::1")}, + {IP: ParseIP("198.51.100.121")}, + }, + srcs: []netip.Addr{ + netip.MustParseAddr("fe80::1"), + netip.MustParseAddr("198.51.100.117"), + }, + want: []IPAddr{ + {IP: ParseIP("198.51.100.121")}, + {IP: ParseIP("2001:db8:1::1")}, + }, + reverse: true, + }, + + // Prefer higher precedence. + { + in: []IPAddr{ + {IP: ParseIP("2001:db8:1::1")}, + {IP: ParseIP("10.1.2.3")}, + }, + srcs: []netip.Addr{ + netip.MustParseAddr("2001:db8:1::2"), + netip.MustParseAddr("10.1.2.4"), + }, + want: []IPAddr{ + {IP: ParseIP("2001:db8:1::1")}, + {IP: ParseIP("10.1.2.3")}, + }, + reverse: true, + }, + + // Prefer smaller scope. + { + in: []IPAddr{ + {IP: ParseIP("2001:db8:1::1")}, + {IP: ParseIP("fe80::1")}, + }, + srcs: []netip.Addr{ + netip.MustParseAddr("2001:db8:1::2"), + netip.MustParseAddr("fe80::2"), + }, + want: []IPAddr{ + {IP: ParseIP("fe80::1")}, + {IP: ParseIP("2001:db8:1::1")}, + }, + reverse: true, + }, + + // Issue 13283. Having a 10/8 source address does not + // mean we should prefer 23/8 destination addresses. + { + in: []IPAddr{ + {IP: ParseIP("54.83.193.112")}, + {IP: ParseIP("184.72.238.214")}, + {IP: ParseIP("23.23.172.185")}, + {IP: ParseIP("75.101.148.21")}, + {IP: ParseIP("23.23.134.56")}, + {IP: ParseIP("23.21.50.150")}, + }, + srcs: []netip.Addr{ + netip.MustParseAddr("10.2.3.4"), + netip.MustParseAddr("10.2.3.4"), + netip.MustParseAddr("10.2.3.4"), + netip.MustParseAddr("10.2.3.4"), + netip.MustParseAddr("10.2.3.4"), + netip.MustParseAddr("10.2.3.4"), + }, + want: []IPAddr{ + {IP: ParseIP("54.83.193.112")}, + {IP: ParseIP("184.72.238.214")}, + {IP: ParseIP("23.23.172.185")}, + {IP: ParseIP("75.101.148.21")}, + {IP: ParseIP("23.23.134.56")}, + {IP: ParseIP("23.21.50.150")}, + }, + reverse: false, + }, + } + for i, tt := range tests { + inCopy := make([]IPAddr, len(tt.in)) + copy(inCopy, tt.in) + srcCopy := make([]netip.Addr, len(tt.in)) + copy(srcCopy, tt.srcs) + sortByRFC6724withSrcs(inCopy, srcCopy) + if !reflect.DeepEqual(inCopy, tt.want) { + t.Errorf("test %d:\nin = %s\ngot: %s\nwant: %s\n", i, tt.in, inCopy, tt.want) + } + if tt.reverse { + copy(inCopy, tt.in) + copy(srcCopy, tt.srcs) + for j := 0; j < len(inCopy)/2; j++ { + k := len(inCopy) - j - 1 + inCopy[j], inCopy[k] = inCopy[k], inCopy[j] + srcCopy[j], srcCopy[k] = srcCopy[k], srcCopy[j] + } + sortByRFC6724withSrcs(inCopy, srcCopy) + if !reflect.DeepEqual(inCopy, tt.want) { + t.Errorf("test %d, starting backwards:\nin = %s\ngot: %s\nwant: %s\n", i, tt.in, inCopy, tt.want) + } + } + + } + +} + +func TestRFC6724PolicyTableOrder(t *testing.T) { + for i := 0; i < len(rfc6724policyTable)-1; i++ { + if !(rfc6724policyTable[i].Prefix.Bits() >= rfc6724policyTable[i+1].Prefix.Bits()) { + t.Errorf("rfc6724policyTable item number %d sorted in wrong order = %d bits, next item = %d bits;", i, rfc6724policyTable[i].Prefix.Bits(), rfc6724policyTable[i+1].Prefix.Bits()) + } + } +} + +func TestRFC6724PolicyTableContent(t *testing.T) { + expectedRfc6724policyTable := policyTable{ + { + Prefix: netip.MustParsePrefix("::1/128"), + Precedence: 50, + Label: 0, + }, + { + Prefix: netip.MustParsePrefix("::ffff:0:0/96"), + Precedence: 35, + Label: 4, + }, + { + Prefix: netip.MustParsePrefix("::/96"), + Precedence: 1, + Label: 3, + }, + { + Prefix: netip.MustParsePrefix("2001::/32"), + Precedence: 5, + Label: 5, + }, + { + Prefix: netip.MustParsePrefix("2002::/16"), + Precedence: 30, + Label: 2, + }, + { + Prefix: netip.MustParsePrefix("3ffe::/16"), + Precedence: 1, + Label: 12, + }, + { + Prefix: netip.MustParsePrefix("fec0::/10"), + Precedence: 1, + Label: 11, + }, + { + Prefix: netip.MustParsePrefix("fc00::/7"), + Precedence: 3, + Label: 13, + }, + { + Prefix: netip.MustParsePrefix("::/0"), + Precedence: 40, + Label: 1, + }, + } + if !reflect.DeepEqual(rfc6724policyTable, expectedRfc6724policyTable) { + t.Errorf("rfc6724policyTable has wrong contend = %v; want %v", rfc6724policyTable, expectedRfc6724policyTable) + } +} + +func TestRFC6724PolicyTableClassify(t *testing.T) { + tests := []struct { + ip netip.Addr + want policyTableEntry + }{ + { + ip: netip.MustParseAddr("127.0.0.1"), + want: policyTableEntry{ + Prefix: netip.MustParsePrefix("::ffff:0:0/96"), + Precedence: 35, + Label: 4, + }, + }, + { + ip: netip.MustParseAddr("2601:645:8002:a500:986f:1db8:c836:bd65"), + want: policyTableEntry{ + Prefix: netip.MustParsePrefix("::/0"), + Precedence: 40, + Label: 1, + }, + }, + { + ip: netip.MustParseAddr("::1"), + want: policyTableEntry{ + Prefix: netip.MustParsePrefix("::1/128"), + Precedence: 50, + Label: 0, + }, + }, + { + ip: netip.MustParseAddr("2002::ab12"), + want: policyTableEntry{ + Prefix: netip.MustParsePrefix("2002::/16"), + Precedence: 30, + Label: 2, + }, + }, + } + for i, tt := range tests { + got := rfc6724policyTable.Classify(tt.ip) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("%d. Classify(%s) = %v; want %v", i, tt.ip, got, tt.want) + } + } +} + +func TestRFC6724ClassifyScope(t *testing.T) { + tests := []struct { + ip netip.Addr + want scope + }{ + {netip.MustParseAddr("127.0.0.1"), scopeLinkLocal}, // rfc6724#section-3.2 + {netip.MustParseAddr("::1"), scopeLinkLocal}, // rfc4007#section-4 + {netip.MustParseAddr("169.254.1.2"), scopeLinkLocal}, // rfc6724#section-3.2 + {netip.MustParseAddr("fec0::1"), scopeSiteLocal}, + {netip.MustParseAddr("8.8.8.8"), scopeGlobal}, + + {netip.MustParseAddr("ff02::"), scopeLinkLocal}, // IPv6 multicast + {netip.MustParseAddr("ff05::"), scopeSiteLocal}, // IPv6 multicast + {netip.MustParseAddr("ff04::"), scopeAdminLocal}, // IPv6 multicast + {netip.MustParseAddr("ff0e::"), scopeGlobal}, // IPv6 multicast + + {netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xe0, 0, 0, 0}), scopeGlobal}, // IPv4 link-local multicast as 16 bytes + {netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xe0, 2, 2, 2}), scopeGlobal}, // IPv4 global multicast as 16 bytes + {netip.AddrFrom4([4]byte{0xe0, 0, 0, 0}), scopeGlobal}, // IPv4 link-local multicast as 4 bytes + {netip.AddrFrom4([4]byte{0xe0, 2, 2, 2}), scopeGlobal}, // IPv4 global multicast as 4 bytes + } + for i, tt := range tests { + got := classifyScope(tt.ip) + if got != tt.want { + t.Errorf("%d. classifyScope(%s) = %x; want %x", i, tt.ip, got, tt.want) + } + } +} + +func TestRFC6724CommonPrefixLength(t *testing.T) { + tests := []struct { + a netip.Addr + b IP + want int + }{ + {netip.MustParseAddr("fe80::1"), ParseIP("fe80::2"), 64}, + {netip.MustParseAddr("fe81::1"), ParseIP("fe80::2"), 15}, + {netip.MustParseAddr("127.0.0.1"), ParseIP("fe80::1"), 0}, // diff size + {netip.AddrFrom4([4]byte{1, 2, 3, 4}), IP{1, 2, 3, 4}, 32}, + {netip.AddrFrom4([4]byte{1, 2, 255, 255}), IP{1, 2, 0, 0}, 16}, + {netip.AddrFrom4([4]byte{1, 2, 127, 255}), IP{1, 2, 0, 0}, 17}, + {netip.AddrFrom4([4]byte{1, 2, 63, 255}), IP{1, 2, 0, 0}, 18}, + {netip.AddrFrom4([4]byte{1, 2, 31, 255}), IP{1, 2, 0, 0}, 19}, + {netip.AddrFrom4([4]byte{1, 2, 15, 255}), IP{1, 2, 0, 0}, 20}, + {netip.AddrFrom4([4]byte{1, 2, 7, 255}), IP{1, 2, 0, 0}, 21}, + {netip.AddrFrom4([4]byte{1, 2, 3, 255}), IP{1, 2, 0, 0}, 22}, + {netip.AddrFrom4([4]byte{1, 2, 1, 255}), IP{1, 2, 0, 0}, 23}, + {netip.AddrFrom4([4]byte{1, 2, 0, 255}), IP{1, 2, 0, 0}, 24}, + } + for i, tt := range tests { + got := commonPrefixLen(tt.a, tt.b) + if got != tt.want { + t.Errorf("%d. commonPrefixLen(%s, %s) = %d; want %d", i, tt.a, tt.b, got, tt.want) + } + } + +} diff --git a/go/src/net/cgo_aix.go b/go/src/net/cgo_aix.go new file mode 100644 index 0000000000000000000000000000000000000000..f3478148b4f60e352dec179b9c5e8304c446f6e2 --- /dev/null +++ b/go/src/net/cgo_aix.go @@ -0,0 +1,24 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo + +package net + +/* +#include +#include + +#include +*/ +import "C" + +import "unsafe" + +const cgoAddrInfoFlags = C.AI_CANONNAME + +func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error) { + gerrno, err := C.getnameinfo(sa, C.size_t(salen), (*C.char)(unsafe.Pointer(&b[0])), C.size_t(len(b)), nil, 0, C.NI_NAMEREQD) + return int(gerrno), err +} diff --git a/go/src/net/cgo_android.go b/go/src/net/cgo_android.go new file mode 100644 index 0000000000000000000000000000000000000000..5ab8b5fedea13aacbdc9bb0758c5e4b9da232b73 --- /dev/null +++ b/go/src/net/cgo_android.go @@ -0,0 +1,12 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo + +package net + +//#include +import "C" + +const cgoAddrInfoFlags = C.AI_CANONNAME diff --git a/go/src/net/cgo_bsd.go b/go/src/net/cgo_bsd.go new file mode 100644 index 0000000000000000000000000000000000000000..082e91faa8afb737bbbe92f95202872d560939da --- /dev/null +++ b/go/src/net/cgo_bsd.go @@ -0,0 +1,14 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo && (dragonfly || freebsd) + +package net + +/* +#include +*/ +import "C" + +const cgoAddrInfoFlags = (C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL) & C.AI_MASK diff --git a/go/src/net/cgo_darwin.go b/go/src/net/cgo_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..129dd937fe0778c48a656dc99390e5f0f3be2073 --- /dev/null +++ b/go/src/net/cgo_darwin.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "internal/syscall/unix" + +const cgoAddrInfoFlags = (unix.AI_CANONNAME | unix.AI_V4MAPPED | unix.AI_ALL) & unix.AI_MASK diff --git a/go/src/net/cgo_linux.go b/go/src/net/cgo_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..de6e87f17622df6a46a73c1b99ae2e21be6672c4 --- /dev/null +++ b/go/src/net/cgo_linux.go @@ -0,0 +1,20 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !android && cgo && !netgo + +package net + +/* +#include +*/ +import "C" + +// NOTE(rsc): In theory there are approximately balanced +// arguments for and against including AI_ADDRCONFIG +// in the flags (it includes IPv4 results only on IPv4 systems, +// and similarly for IPv6), but in practice setting it causes +// getaddrinfo to return the wrong canonical name on Linux. +// So definitely leave it out. +const cgoAddrInfoFlags = C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL diff --git a/go/src/net/cgo_netbsd.go b/go/src/net/cgo_netbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..03392e8ff34c596a979e6b20469e8f636a4925c2 --- /dev/null +++ b/go/src/net/cgo_netbsd.go @@ -0,0 +1,14 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo + +package net + +/* +#include +*/ +import "C" + +const cgoAddrInfoFlags = C.AI_CANONNAME diff --git a/go/src/net/cgo_openbsd.go b/go/src/net/cgo_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..03392e8ff34c596a979e6b20469e8f636a4925c2 --- /dev/null +++ b/go/src/net/cgo_openbsd.go @@ -0,0 +1,14 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo + +package net + +/* +#include +*/ +import "C" + +const cgoAddrInfoFlags = C.AI_CANONNAME diff --git a/go/src/net/cgo_resnew.go b/go/src/net/cgo_resnew.go new file mode 100644 index 0000000000000000000000000000000000000000..3f21c5c4c4fd5bb899cbe9a174b681c905f45c5a --- /dev/null +++ b/go/src/net/cgo_resnew.go @@ -0,0 +1,22 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo && ((linux && !android) || netbsd || solaris) + +package net + +/* +#include +#include + +#include +*/ +import "C" + +import "unsafe" + +func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error) { + gerrno, err := C.getnameinfo(sa, salen, (*C.char)(unsafe.Pointer(&b[0])), C.socklen_t(len(b)), nil, 0, C.NI_NAMEREQD) + return int(gerrno), err +} diff --git a/go/src/net/cgo_resold.go b/go/src/net/cgo_resold.go new file mode 100644 index 0000000000000000000000000000000000000000..37c75527f95c0dedf8b36792cc94fb22eb89abc9 --- /dev/null +++ b/go/src/net/cgo_resold.go @@ -0,0 +1,22 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo && (android || freebsd || dragonfly || openbsd) + +package net + +/* +#include +#include + +#include +*/ +import "C" + +import "unsafe" + +func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error) { + gerrno, err := C.getnameinfo(sa, salen, (*C.char)(unsafe.Pointer(&b[0])), C.size_t(len(b)), nil, 0, C.NI_NAMEREQD) + return int(gerrno), err +} diff --git a/go/src/net/cgo_socknew.go b/go/src/net/cgo_socknew.go new file mode 100644 index 0000000000000000000000000000000000000000..fbb9e10f3401967f2018f477392fb8428f7df752 --- /dev/null +++ b/go/src/net/cgo_socknew.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo && (android || linux || solaris) + +package net + +/* +#include +#include + +#include +*/ +import "C" + +import ( + "syscall" + "unsafe" +) + +func cgoSockaddrInet4(ip IP) *C.struct_sockaddr { + sa := syscall.RawSockaddrInet4{Family: syscall.AF_INET} + copy(sa.Addr[:], ip) + return (*C.struct_sockaddr)(unsafe.Pointer(&sa)) +} + +func cgoSockaddrInet6(ip IP, zone int) *C.struct_sockaddr { + sa := syscall.RawSockaddrInet6{Family: syscall.AF_INET6, Scope_id: uint32(zone)} + copy(sa.Addr[:], ip) + return (*C.struct_sockaddr)(unsafe.Pointer(&sa)) +} diff --git a/go/src/net/cgo_sockold.go b/go/src/net/cgo_sockold.go new file mode 100644 index 0000000000000000000000000000000000000000..d0a99e073d82c2b98c812b01969cba08761a1350 --- /dev/null +++ b/go/src/net/cgo_sockold.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo && (aix || dragonfly || freebsd || netbsd || openbsd) + +package net + +/* +#include +#include + +#include +*/ +import "C" + +import ( + "syscall" + "unsafe" +) + +func cgoSockaddrInet4(ip IP) *C.struct_sockaddr { + sa := syscall.RawSockaddrInet4{Len: syscall.SizeofSockaddrInet4, Family: syscall.AF_INET} + copy(sa.Addr[:], ip) + return (*C.struct_sockaddr)(unsafe.Pointer(&sa)) +} + +func cgoSockaddrInet6(ip IP, zone int) *C.struct_sockaddr { + sa := syscall.RawSockaddrInet6{Len: syscall.SizeofSockaddrInet6, Family: syscall.AF_INET6, Scope_id: uint32(zone)} + copy(sa.Addr[:], ip) + return (*C.struct_sockaddr)(unsafe.Pointer(&sa)) +} diff --git a/go/src/net/cgo_solaris.go b/go/src/net/cgo_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..98a0e819565d3fb58fe5e7a4d7e6feda2c2ee9ee --- /dev/null +++ b/go/src/net/cgo_solaris.go @@ -0,0 +1,15 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo + +package net + +/* +#cgo LDFLAGS: -lsocket -lnsl +#include +*/ +import "C" + +const cgoAddrInfoFlags = C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL diff --git a/go/src/net/cgo_stub.go b/go/src/net/cgo_stub.go new file mode 100644 index 0000000000000000000000000000000000000000..640f5a4fd65a552a2503255a3117c8f02bde9339 --- /dev/null +++ b/go/src/net/cgo_stub.go @@ -0,0 +1,40 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file holds stub versions of the cgo functions called on Unix systems. +// We build this file: +// - if using the netgo build tag on a Unix system +// - on a Unix system without the cgo resolver functions +// (Darwin always provides the cgo functions, in cgo_unix_syscall.go) +// - on wasip1, where cgo is never available + +//go:build (netgo && unix) || (unix && !cgo && !darwin) || js || wasip1 + +package net + +import "context" + +// cgoAvailable set to false to indicate that the cgo resolver +// is not available on this system. +const cgoAvailable = false + +func cgoLookupHost(ctx context.Context, name string) (addrs []string, err error) { + panic("cgo stub: cgo not available") +} + +func cgoLookupPort(ctx context.Context, network, service string) (port int, err error) { + panic("cgo stub: cgo not available") +} + +func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error) { + panic("cgo stub: cgo not available") +} + +func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error) { + panic("cgo stub: cgo not available") +} + +func cgoLookupPTR(ctx context.Context, addr string) (ptrs []string, err error) { + panic("cgo stub: cgo not available") +} diff --git a/go/src/net/cgo_unix.go b/go/src/net/cgo_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..7d970cfeaba9e916ca503ede1de13eef15edf908 --- /dev/null +++ b/go/src/net/cgo_unix.go @@ -0,0 +1,381 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is called cgo_unix.go, but to allow syscalls-to-libc-based +// implementations to share the code, it does not use cgo directly. +// Instead of C.foo it uses _C_foo, which is defined in either +// cgo_unix_cgo.go or cgo_unix_syscall.go + +//go:build !netgo && ((cgo && unix) || darwin) + +package net + +import ( + "context" + "errors" + "internal/bytealg" + "net/netip" + "runtime" + "syscall" + "unsafe" + + "golang.org/x/net/dns/dnsmessage" +) + +// cgoAvailable set to true to indicate that the cgo resolver +// is available on this system. +const cgoAvailable = true + +// An addrinfoErrno represents a getaddrinfo, getnameinfo-specific +// error number. It's a signed number and a zero value is a non-error +// by convention. +type addrinfoErrno int + +func (eai addrinfoErrno) Error() string { return _C_gai_strerror(_C_int(eai)) } +func (eai addrinfoErrno) Temporary() bool { return eai == _C_EAI_AGAIN } +func (eai addrinfoErrno) Timeout() bool { return false } + +// isAddrinfoErrno is just for testing purposes. +func (eai addrinfoErrno) isAddrinfoErrno() {} + +// doBlockingWithCtx executes a blocking function in a separate goroutine when the provided +// context is cancellable. It is intended for use with calls that don't support context +// cancellation (cgo, syscalls). blocking func may still be running after this function finishes. +// For the duration of the execution of the blocking function, the thread is 'acquired' using [acquireThread], +// blocking might not be executed when the context gets canceled early. +func doBlockingWithCtx[T any](ctx context.Context, lookupName string, blocking func() (T, error)) (T, error) { + if err := acquireThread(ctx); err != nil { + var zero T + return zero, newDNSError(mapErr(err), lookupName, "") + } + + if ctx.Done() == nil { + defer releaseThread() + return blocking() + } + + type result struct { + res T + err error + } + + res := make(chan result, 1) + go func() { + defer releaseThread() + var r result + r.res, r.err = blocking() + res <- r + }() + + select { + case r := <-res: + return r.res, r.err + case <-ctx.Done(): + var zero T + return zero, newDNSError(mapErr(ctx.Err()), lookupName, "") + } +} + +func cgoLookupHost(ctx context.Context, name string) (hosts []string, err error) { + addrs, err := cgoLookupIP(ctx, "ip", name) + if err != nil { + return nil, err + } + for _, addr := range addrs { + hosts = append(hosts, addr.String()) + } + return hosts, nil +} + +func cgoLookupPort(ctx context.Context, network, service string) (port int, err error) { + var hints _C_struct_addrinfo + switch network { + case "ip": // no hints + case "tcp", "tcp4", "tcp6": + *_C_ai_socktype(&hints) = _C_SOCK_STREAM + *_C_ai_protocol(&hints) = _C_IPPROTO_TCP + case "udp", "udp4", "udp6": + *_C_ai_socktype(&hints) = _C_SOCK_DGRAM + *_C_ai_protocol(&hints) = _C_IPPROTO_UDP + default: + return 0, &DNSError{Err: "unknown network", Name: network + "/" + service} + } + switch ipVersion(network) { + case '4': + *_C_ai_family(&hints) = _C_AF_INET + case '6': + *_C_ai_family(&hints) = _C_AF_INET6 + } + + return doBlockingWithCtx(ctx, network+"/"+service, func() (int, error) { + return cgoLookupServicePort(&hints, network, service) + }) +} + +func cgoLookupServicePort(hints *_C_struct_addrinfo, network, service string) (port int, err error) { + cservice, err := syscall.ByteSliceFromString(service) + if err != nil { + return 0, &DNSError{Err: err.Error(), Name: network + "/" + service} + } + // Lowercase the C service name. + for i, b := range cservice[:len(service)] { + cservice[i] = lowerASCII(b) + } + var res *_C_struct_addrinfo + gerrno, err := _C_getaddrinfo(nil, (*_C_char)(unsafe.Pointer(&cservice[0])), hints, &res) + if gerrno != 0 { + switch gerrno { + case _C_EAI_SYSTEM: + if err == nil { // see golang.org/issue/6232 + err = syscall.EMFILE + } + return 0, newDNSError(err, network+"/"+service, "") + case _C_EAI_SERVICE, _C_EAI_NONAME: // Darwin returns EAI_NONAME. + return 0, newDNSError(errUnknownPort, network+"/"+service, "") + default: + return 0, newDNSError(addrinfoErrno(gerrno), network+"/"+service, "") + } + } + defer _C_freeaddrinfo(res) + + for r := res; r != nil; r = *_C_ai_next(r) { + switch *_C_ai_family(r) { + case _C_AF_INET: + sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r))) + p := (*[2]byte)(unsafe.Pointer(&sa.Port)) + return int(p[0])<<8 | int(p[1]), nil + case _C_AF_INET6: + sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r))) + p := (*[2]byte)(unsafe.Pointer(&sa.Port)) + return int(p[0])<<8 | int(p[1]), nil + } + } + return 0, newDNSError(errUnknownPort, network+"/"+service, "") +} + +func cgoLookupHostIP(network, name string) (addrs []IPAddr, err error) { + var hints _C_struct_addrinfo + *_C_ai_flags(&hints) = cgoAddrInfoFlags + *_C_ai_socktype(&hints) = _C_SOCK_STREAM + *_C_ai_family(&hints) = _C_AF_UNSPEC + switch ipVersion(network) { + case '4': + *_C_ai_family(&hints) = _C_AF_INET + case '6': + *_C_ai_family(&hints) = _C_AF_INET6 + } + + h, err := syscall.BytePtrFromString(name) + if err != nil { + return nil, &DNSError{Err: err.Error(), Name: name} + } + var res *_C_struct_addrinfo + gerrno, err := _C_getaddrinfo((*_C_char)(unsafe.Pointer(h)), nil, &hints, &res) + if gerrno != 0 { + switch gerrno { + case _C_EAI_SYSTEM: + if err == nil { + // err should not be nil, but sometimes getaddrinfo returns + // gerrno == _C_EAI_SYSTEM with err == nil on Linux. + // The report claims that it happens when we have too many + // open files, so use syscall.EMFILE (too many open files in system). + // Most system calls would return ENFILE (too many open files), + // so at the least EMFILE should be easy to recognize if this + // comes up again. golang.org/issue/6232. + err = syscall.EMFILE + } + return nil, newDNSError(err, name, "") + case _C_EAI_NONAME, _C_EAI_NODATA: + return nil, newDNSError(errNoSuchHost, name, "") + case _C_EAI_ADDRFAMILY: + if runtime.GOOS == "freebsd" { + // FreeBSD began returning EAI_ADDRFAMILY for valid hosts without + // an A record in 13.2. We previously returned "no such host" for + // this case. + // + // https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=273912 + return nil, newDNSError(errNoSuchHost, name, "") + } + fallthrough + default: + return nil, newDNSError(addrinfoErrno(gerrno), name, "") + } + + } + defer _C_freeaddrinfo(res) + + for r := res; r != nil; r = *_C_ai_next(r) { + // We only asked for SOCK_STREAM, but check anyhow. + if *_C_ai_socktype(r) != _C_SOCK_STREAM { + continue + } + switch *_C_ai_family(r) { + case _C_AF_INET: + sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r))) + addr := IPAddr{IP: copyIP(sa.Addr[:])} + addrs = append(addrs, addr) + case _C_AF_INET6: + sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r))) + addr := IPAddr{IP: copyIP(sa.Addr[:]), Zone: zoneCache.name(int(sa.Scope_id))} + addrs = append(addrs, addr) + } + } + return addrs, nil +} + +func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error) { + return doBlockingWithCtx(ctx, name, func() ([]IPAddr, error) { + return cgoLookupHostIP(network, name) + }) +} + +// These are roughly enough for the following: +// +// Source Encoding Maximum length of single name entry +// Unicast DNS ASCII or <=253 + a NUL terminator +// Unicode in RFC 5892 252 * total number of labels + delimiters + a NUL terminator +// Multicast DNS UTF-8 in RFC 5198 or <=253 + a NUL terminator +// the same as unicast DNS ASCII <=253 + a NUL terminator +// Local database various depends on implementation +const ( + nameinfoLen = 64 + maxNameinfoLen = 4096 +) + +func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error) { + ip, err := netip.ParseAddr(addr) + if err != nil { + return nil, &DNSError{Err: "invalid address", Name: addr} + } + sa, salen := cgoSockaddr(IP(ip.AsSlice()), ip.Zone()) + if sa == nil { + return nil, &DNSError{Err: "invalid address " + ip.String(), Name: addr} + } + + return doBlockingWithCtx(ctx, addr, func() ([]string, error) { + return cgoLookupAddrPTR(addr, sa, salen) + }) +} + +func cgoLookupAddrPTR(addr string, sa *_C_struct_sockaddr, salen _C_socklen_t) (names []string, err error) { + var gerrno int + var b []byte + for l := nameinfoLen; l <= maxNameinfoLen; l *= 2 { + b = make([]byte, l) + gerrno, err = cgoNameinfoPTR(b, sa, salen) + if gerrno == 0 || gerrno != _C_EAI_OVERFLOW { + break + } + } + if gerrno != 0 { + switch gerrno { + case _C_EAI_SYSTEM: + if err == nil { // see golang.org/issue/6232 + err = syscall.EMFILE + } + return nil, newDNSError(err, addr, "") + case _C_EAI_NONAME: + return nil, newDNSError(errNoSuchHost, addr, "") + default: + return nil, newDNSError(addrinfoErrno(gerrno), addr, "") + } + } + if i := bytealg.IndexByte(b, 0); i != -1 { + b = b[:i] + } + return []string{absDomainName(string(b))}, nil +} + +func cgoSockaddr(ip IP, zone string) (*_C_struct_sockaddr, _C_socklen_t) { + if ip4 := ip.To4(); ip4 != nil { + return cgoSockaddrInet4(ip4), _C_socklen_t(syscall.SizeofSockaddrInet4) + } + if ip6 := ip.To16(); ip6 != nil { + return cgoSockaddrInet6(ip6, zoneCache.index(zone)), _C_socklen_t(syscall.SizeofSockaddrInet6) + } + return nil, 0 +} + +func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error) { + resources, err := resSearch(ctx, name, int(dnsmessage.TypeCNAME), int(dnsmessage.ClassINET)) + if err != nil { + return "", err + } + cname, err = parseCNAMEFromResources(resources) + if err != nil { + return "", err + } + return cname, nil +} + +// resSearch will make a call to the 'res_nsearch' routine in the C library +// and parse the output as a slice of DNS resources. +func resSearch(ctx context.Context, hostname string, rtype, class int) ([]dnsmessage.Resource, error) { + return doBlockingWithCtx(ctx, hostname, func() ([]dnsmessage.Resource, error) { + return cgoResSearch(hostname, rtype, class) + }) +} + +func cgoResSearch(hostname string, rtype, class int) ([]dnsmessage.Resource, error) { + resStateSize := unsafe.Sizeof(_C_struct___res_state{}) + var state *_C_struct___res_state + if resStateSize > 0 { + mem := _C_malloc(resStateSize) + defer _C_free(mem) + memSlice := unsafe.Slice((*byte)(mem), resStateSize) + clear(memSlice) + state = (*_C_struct___res_state)(unsafe.Pointer(&memSlice[0])) + } + if err := _C_res_ninit(state); err != nil { + return nil, errors.New("res_ninit failure: " + err.Error()) + } + defer _C_res_nclose(state) + + // Some res_nsearch implementations (like macOS) do not set errno. + // They set h_errno, which is not per-thread and useless to us. + // res_nsearch returns the size of the DNS response packet. + // But if the DNS response packet contains failure-like response codes, + // res_search returns -1 even though it has copied the packet into buf, + // giving us no way to find out how big the packet is. + // For now, we are willing to take res_search's word that there's nothing + // useful in the response, even though there *is* a response. + bufSize := maxDNSPacketSize + buf := (*_C_uchar)(_C_malloc(uintptr(bufSize))) + defer func() { + // Free in a closure which captures buf to pick up a reallocated buffer from below. + _C_free(unsafe.Pointer(buf)) + }() + + s, err := syscall.BytePtrFromString(hostname) + if err != nil { + return nil, err + } + + var size int + for { + size = _C_res_nsearch(state, (*_C_char)(unsafe.Pointer(s)), class, rtype, buf, bufSize) + if size <= 0 || size > 0xffff { + return nil, errors.New("res_nsearch failure") + } + if size <= bufSize { + break + } + + // Allocate a bigger buffer to fit the entire msg. + _C_free(unsafe.Pointer(buf)) + bufSize = size + buf = (*_C_uchar)(_C_malloc(uintptr(bufSize))) + } + + var p dnsmessage.Parser + if _, err := p.Start(unsafe.Slice((*byte)(unsafe.Pointer(buf)), size)); err != nil { + return nil, err + } + p.SkipAllQuestions() + resources, err := p.AllAnswers() + if err != nil { + return nil, err + } + return resources, nil +} diff --git a/go/src/net/cgo_unix_cgo.go b/go/src/net/cgo_unix_cgo.go new file mode 100644 index 0000000000000000000000000000000000000000..c4b8197c620458fa9871ed872a5133730c668b79 --- /dev/null +++ b/go/src/net/cgo_unix_cgo.go @@ -0,0 +1,86 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cgo && !netgo && unix && !darwin + +package net + +/* +#define _GNU_SOURCE 1 + +#cgo CFLAGS: -fno-stack-protector +#include +#include +#include +#include +#include +#include +#include + +#ifndef EAI_NODATA +#define EAI_NODATA -5 +#endif + +// If nothing else defined EAI_ADDRFAMILY, make sure it has a value. +#ifndef EAI_ADDRFAMILY +#define EAI_ADDRFAMILY -9 +#endif + +// If nothing else defined EAI_OVERFLOW, make sure it has a value. +#ifndef EAI_OVERFLOW +#define EAI_OVERFLOW -12 +#endif +*/ +import "C" +import "unsafe" + +const ( + _C_AF_INET = C.AF_INET + _C_AF_INET6 = C.AF_INET6 + _C_AF_UNSPEC = C.AF_UNSPEC + _C_EAI_ADDRFAMILY = C.EAI_ADDRFAMILY + _C_EAI_AGAIN = C.EAI_AGAIN + _C_EAI_NODATA = C.EAI_NODATA + _C_EAI_NONAME = C.EAI_NONAME + _C_EAI_SERVICE = C.EAI_SERVICE + _C_EAI_OVERFLOW = C.EAI_OVERFLOW + _C_EAI_SYSTEM = C.EAI_SYSTEM + _C_IPPROTO_TCP = C.IPPROTO_TCP + _C_IPPROTO_UDP = C.IPPROTO_UDP + _C_SOCK_DGRAM = C.SOCK_DGRAM + _C_SOCK_STREAM = C.SOCK_STREAM +) + +type ( + _C_char = C.char + _C_uchar = C.uchar + _C_int = C.int + _C_uint = C.uint + _C_socklen_t = C.socklen_t + _C_struct_addrinfo = C.struct_addrinfo + _C_struct_sockaddr = C.struct_sockaddr +) + +func _C_malloc(n uintptr) unsafe.Pointer { return C.malloc(C.size_t(n)) } +func _C_free(p unsafe.Pointer) { C.free(p) } + +func _C_ai_addr(ai *_C_struct_addrinfo) **_C_struct_sockaddr { return &ai.ai_addr } +func _C_ai_family(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_family } +func _C_ai_flags(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_flags } +func _C_ai_next(ai *_C_struct_addrinfo) **_C_struct_addrinfo { return &ai.ai_next } +func _C_ai_protocol(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_protocol } +func _C_ai_socktype(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_socktype } + +func _C_freeaddrinfo(ai *_C_struct_addrinfo) { + C.freeaddrinfo(ai) +} + +func _C_gai_strerror(eai _C_int) string { + return C.GoString(C.gai_strerror(eai)) +} + +func _C_getaddrinfo(hostname, servname *_C_char, hints *_C_struct_addrinfo, res **_C_struct_addrinfo) (int, error) { + x, err := C.getaddrinfo(hostname, servname, hints, res) + return int(x), err +} diff --git a/go/src/net/cgo_unix_cgo_res.go b/go/src/net/cgo_unix_cgo_res.go new file mode 100644 index 0000000000000000000000000000000000000000..c5f30238a13c8f0ce25f1b0656725ef04c00e965 --- /dev/null +++ b/go/src/net/cgo_unix_cgo_res.go @@ -0,0 +1,38 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// res_search, for cgo systems where that is thread-safe. + +//go:build cgo && !netgo && (linux || openbsd) + +package net + +/* +#include +#include +#include +#include +#include +#include +#include +#include + +#cgo !android,!openbsd LDFLAGS: -lresolv +*/ +import "C" + +type _C_struct___res_state = struct{} + +func _C_res_ninit(state *_C_struct___res_state) error { + return nil +} + +func _C_res_nclose(state *_C_struct___res_state) { + return +} + +func _C_res_nsearch(state *_C_struct___res_state, dname *_C_char, class, typ int, ans *_C_uchar, anslen int) int { + x := C.res_search(dname, C.int(class), C.int(typ), ans, C.int(anslen)) + return int(x) +} diff --git a/go/src/net/cgo_unix_cgo_resn.go b/go/src/net/cgo_unix_cgo_resn.go new file mode 100644 index 0000000000000000000000000000000000000000..4fc747b5a339079a086b85cc54f29b1b04e7b84f --- /dev/null +++ b/go/src/net/cgo_unix_cgo_resn.go @@ -0,0 +1,39 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// res_nsearch, for cgo systems where that's available. + +//go:build cgo && !netgo && unix && !(darwin || linux || openbsd) + +package net + +/* +#include +#include +#include +#include +#include +#include +#include +#include + +#cgo !aix,!dragonfly,!freebsd LDFLAGS: -lresolv +*/ +import "C" + +type _C_struct___res_state = C.struct___res_state + +func _C_res_ninit(state *_C_struct___res_state) error { + _, err := C.res_ninit(state) + return err +} + +func _C_res_nclose(state *_C_struct___res_state) { + C.res_nclose(state) +} + +func _C_res_nsearch(state *_C_struct___res_state, dname *_C_char, class, typ int, ans *_C_uchar, anslen int) int { + x := C.res_nsearch(state, dname, C.int(class), C.int(typ), ans, C.int(anslen)) + return int(x) +} diff --git a/go/src/net/cgo_unix_syscall.go b/go/src/net/cgo_unix_syscall.go new file mode 100644 index 0000000000000000000000000000000000000000..6b7ef74bd2b94559b46a86a7fddf8691b2871538 --- /dev/null +++ b/go/src/net/cgo_unix_syscall.go @@ -0,0 +1,100 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !netgo && darwin + +package net + +import ( + "internal/syscall/unix" + "runtime" + "syscall" + "unsafe" +) + +const ( + _C_AF_INET = syscall.AF_INET + _C_AF_INET6 = syscall.AF_INET6 + _C_AF_UNSPEC = syscall.AF_UNSPEC + _C_EAI_ADDRFAMILY = unix.EAI_ADDRFAMILY + _C_EAI_AGAIN = unix.EAI_AGAIN + _C_EAI_NONAME = unix.EAI_NONAME + _C_EAI_SERVICE = unix.EAI_SERVICE + _C_EAI_NODATA = unix.EAI_NODATA + _C_EAI_OVERFLOW = unix.EAI_OVERFLOW + _C_EAI_SYSTEM = unix.EAI_SYSTEM + _C_IPPROTO_TCP = syscall.IPPROTO_TCP + _C_IPPROTO_UDP = syscall.IPPROTO_UDP + _C_SOCK_DGRAM = syscall.SOCK_DGRAM + _C_SOCK_STREAM = syscall.SOCK_STREAM +) + +type ( + _C_char = byte + _C_int = int32 + _C_uchar = byte + _C_uint = uint32 + _C_socklen_t = int + _C_struct___res_state = unix.ResState + _C_struct_addrinfo = unix.Addrinfo + _C_struct_sockaddr = syscall.RawSockaddr +) + +func _C_free(p unsafe.Pointer) { runtime.KeepAlive(p) } + +func _C_malloc(n uintptr) unsafe.Pointer { + if n <= 0 { + n = 1 + } + return unsafe.Pointer(&make([]byte, n)[0]) +} + +func _C_ai_addr(ai *_C_struct_addrinfo) **_C_struct_sockaddr { return &ai.Addr } +func _C_ai_family(ai *_C_struct_addrinfo) *_C_int { return &ai.Family } +func _C_ai_flags(ai *_C_struct_addrinfo) *_C_int { return &ai.Flags } +func _C_ai_next(ai *_C_struct_addrinfo) **_C_struct_addrinfo { return &ai.Next } +func _C_ai_protocol(ai *_C_struct_addrinfo) *_C_int { return &ai.Protocol } +func _C_ai_socktype(ai *_C_struct_addrinfo) *_C_int { return &ai.Socktype } + +func _C_freeaddrinfo(ai *_C_struct_addrinfo) { + unix.Freeaddrinfo(ai) +} + +func _C_gai_strerror(eai _C_int) string { + return unix.GaiStrerror(int(eai)) +} + +func _C_getaddrinfo(hostname, servname *byte, hints *_C_struct_addrinfo, res **_C_struct_addrinfo) (int, error) { + return unix.Getaddrinfo(hostname, servname, hints, res) +} + +func _C_res_ninit(state *_C_struct___res_state) error { + unix.ResNinit(state) + return nil +} + +func _C_res_nsearch(state *_C_struct___res_state, dname *_C_char, class, typ int, ans *_C_char, anslen int) int { + x, _ := unix.ResNsearch(state, dname, class, typ, ans, anslen) + return x +} + +func _C_res_nclose(state *_C_struct___res_state) { + unix.ResNclose(state) +} + +func cgoNameinfoPTR(b []byte, sa *syscall.RawSockaddr, salen int) (int, error) { + return unix.Getnameinfo(sa, salen, &b[0], len(b), nil, 0, unix.NI_NAMEREQD) +} + +func cgoSockaddrInet4(ip IP) *syscall.RawSockaddr { + sa := syscall.RawSockaddrInet4{Len: syscall.SizeofSockaddrInet4, Family: syscall.AF_INET} + copy(sa.Addr[:], ip) + return (*syscall.RawSockaddr)(unsafe.Pointer(&sa)) +} + +func cgoSockaddrInet6(ip IP, zone int) *syscall.RawSockaddr { + sa := syscall.RawSockaddrInet6{Len: syscall.SizeofSockaddrInet6, Family: syscall.AF_INET6, Scope_id: uint32(zone)} + copy(sa.Addr[:], ip) + return (*syscall.RawSockaddr)(unsafe.Pointer(&sa)) +} diff --git a/go/src/net/cgo_unix_test.go b/go/src/net/cgo_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9aaeccc5f057090a3ee2bdc184c801b5f7b1cff2 --- /dev/null +++ b/go/src/net/cgo_unix_test.go @@ -0,0 +1,79 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !netgo && ((cgo && unix) || darwin) + +package net + +import ( + "context" + "internal/testenv" + "testing" +) + +func TestCgoLookupIP(t *testing.T) { + defer dnsWaitGroup.Wait() + ctx := context.Background() + _, err := cgoLookupIP(ctx, "ip", "localhost") + if err != nil { + t.Error(err) + } +} + +func TestCgoLookupIPWithCancel(t *testing.T) { + defer dnsWaitGroup.Wait() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + _, err := cgoLookupIP(ctx, "ip", "localhost") + if err != nil { + t.Error(err) + } +} + +func TestCgoLookupPort(t *testing.T) { + defer dnsWaitGroup.Wait() + ctx := context.Background() + _, err := cgoLookupPort(ctx, "tcp", "smtp") + if err != nil { + t.Error(err) + } +} + +func TestCgoLookupPortWithCancel(t *testing.T) { + defer dnsWaitGroup.Wait() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + _, err := cgoLookupPort(ctx, "tcp", "smtp") + if err != nil { + t.Error(err) + } +} + +func TestCgoLookupPTR(t *testing.T) { + defer dnsWaitGroup.Wait() + ctx := context.Background() + _, err := cgoLookupPTR(ctx, "127.0.0.1") + if err != nil { + t.Error(err) + } +} + +func TestCgoLookupPTRWithCancel(t *testing.T) { + defer dnsWaitGroup.Wait() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + _, err := cgoLookupPTR(ctx, "127.0.0.1") + if err != nil { + t.Error(err) + } +} + +func TestCgoLookupCNAME(t *testing.T) { + mustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + defer dnsWaitGroup.Wait() + if _, err := cgoLookupCNAME(t.Context(), "www.iana.org."); err != nil { + t.Error(err) + } +} diff --git a/go/src/net/conf.go b/go/src/net/conf.go new file mode 100644 index 0000000000000000000000000000000000000000..92c5618d1ec2217ff50bdffe38a63d5b19773ed6 --- /dev/null +++ b/go/src/net/conf.go @@ -0,0 +1,535 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "internal/bytealg" + "internal/godebug" + "internal/stringslite" + "io/fs" + "os" + "runtime" + "sync" +) + +// The net package's name resolution is rather complicated. +// There are two main approaches, go and cgo. +// The cgo resolver uses C functions like getaddrinfo. +// The go resolver reads system files directly and +// sends DNS packets directly to servers. +// +// The netgo build tag prefers the go resolver. +// The netcgo build tag prefers the cgo resolver. +// +// The netgo build tag also prohibits the use of the cgo tool. +// However, on Darwin, Plan 9, and Windows the cgo resolver is still available. +// On those systems the cgo resolver does not require the cgo tool. +// (The term "cgo resolver" was locked in by GODEBUG settings +// at a time when the cgo resolver did require the cgo tool.) +// +// Adding netdns=go to GODEBUG will prefer the go resolver. +// Adding netdns=cgo to GODEBUG will prefer the cgo resolver. +// +// The Resolver struct has a PreferGo field that user code +// may set to prefer the go resolver. It is documented as being +// equivalent to adding netdns=go to GODEBUG. +// +// When deciding which resolver to use, we first check the PreferGo field. +// If that is not set, we check the GODEBUG setting. +// If that is not set, we check the netgo or netcgo build tag. +// If none of those are set, we normally prefer the go resolver by default. +// However, if the cgo resolver is available, +// there is a complex set of conditions for which we prefer the cgo resolver. +// +// Other files define the netGoBuildTag, netCgoBuildTag, and cgoAvailable +// constants. + +// conf is used to determine name resolution configuration. +type conf struct { + netGo bool // prefer go approach, based on build tag and GODEBUG + netCgo bool // prefer cgo approach, based on build tag and GODEBUG + + dnsDebugLevel int // from GODEBUG + + preferCgo bool // if no explicit preference, use cgo + + goos string // copy of runtime.GOOS, used for testing + mdnsTest mdnsTest // assume /etc/mdns.allow exists, for testing +} + +// mdnsTest is for testing only. +type mdnsTest int + +const ( + mdnsFromSystem mdnsTest = iota + mdnsAssumeExists + mdnsAssumeDoesNotExist +) + +var ( + confOnce sync.Once // guards init of confVal via initConfVal + confVal = &conf{goos: runtime.GOOS} +) + +// systemConf returns the machine's network configuration. +func systemConf() *conf { + confOnce.Do(initConfVal) + return confVal +} + +// initConfVal initializes confVal based on the environment +// that will not change during program execution. +func initConfVal() { + dnsMode, debugLevel := goDebugNetDNS() + confVal.netGo = netGoBuildTag || dnsMode == "go" + confVal.netCgo = netCgoBuildTag || dnsMode == "cgo" + confVal.dnsDebugLevel = debugLevel + + if confVal.dnsDebugLevel > 0 { + defer func() { + if confVal.dnsDebugLevel > 1 { + println("go package net: confVal.netCgo =", confVal.netCgo, " netGo =", confVal.netGo) + } + if dnsMode != "go" && dnsMode != "cgo" && dnsMode != "" { + println("go package net: GODEBUG=netdns contains an invalid dns mode, ignoring it") + } + switch { + case netGoBuildTag || !cgoAvailable: + if dnsMode == "cgo" { + println("go package net: ignoring GODEBUG=netdns=cgo as the binary was compiled without support for the cgo resolver") + } else { + println("go package net: using the Go DNS resolver") + } + case netCgoBuildTag: + if dnsMode == "go" { + println("go package net: GODEBUG setting forcing use of the Go resolver") + } else { + println("go package net: using the cgo DNS resolver") + } + default: + if dnsMode == "go" { + println("go package net: GODEBUG setting forcing use of the Go resolver") + } else if dnsMode == "cgo" { + println("go package net: GODEBUG setting forcing use of the cgo resolver") + } else { + println("go package net: dynamic selection of DNS resolver") + } + } + }() + } + + // The remainder of this function sets preferCgo based on + // conditions that will not change during program execution. + + // By default, prefer the go resolver. + confVal.preferCgo = false + + // If the cgo resolver is not available, we can't prefer it. + if !cgoAvailable { + return + } + + // Some operating systems always prefer the cgo resolver. + if goosPrefersCgo() { + confVal.preferCgo = true + return + } + + // The remaining checks are specific to Unix systems. + switch runtime.GOOS { + case "plan9", "windows", "js", "wasip1": + return + } + + // If any environment-specified resolver options are specified, + // prefer the cgo resolver. + // Note that LOCALDOMAIN can change behavior merely by being + // specified with the empty string. + _, localDomainDefined := os.LookupEnv("LOCALDOMAIN") + if localDomainDefined || os.Getenv("RES_OPTIONS") != "" || os.Getenv("HOSTALIASES") != "" { + confVal.preferCgo = true + return + } + + // OpenBSD apparently lets you override the location of resolv.conf + // with ASR_CONFIG. If we notice that, defer to libc. + if runtime.GOOS == "openbsd" && os.Getenv("ASR_CONFIG") != "" { + confVal.preferCgo = true + return + } +} + +// goosPrefersCgo reports whether the GOOS value passed in prefers +// the cgo resolver. +func goosPrefersCgo() bool { + switch runtime.GOOS { + // Historically on Windows and Plan 9 we prefer the + // cgo resolver (which doesn't use the cgo tool) rather than + // the go resolver. This is because originally these + // systems did not support the go resolver. + // Keep it this way for better compatibility. + // Perhaps we can revisit this some day. + case "windows", "plan9": + return true + + // Darwin pops up annoying dialog boxes if programs try to + // do their own DNS requests, so prefer cgo. + case "darwin", "ios": + return true + + // DNS requests don't work on Android, so prefer the cgo resolver. + // Issue #10714. + case "android": + return true + + default: + return false + } +} + +// mustUseGoResolver reports whether a DNS lookup of any sort is +// required to use the go resolver. The provided Resolver is optional. +// This will report true if the cgo resolver is not available. +func (c *conf) mustUseGoResolver(r *Resolver) bool { + if !cgoAvailable { + return true + } + + if runtime.GOOS == "plan9" { + // TODO(bradfitz): for now we only permit use of the PreferGo + // implementation when there's a non-nil Resolver with a + // non-nil Dialer. This is a sign that the code is trying + // to use their DNS-speaking net.Conn (such as an in-memory + // DNS cache) and they don't want to actually hit the network. + // Once we add support for looking the default DNS servers + // from plan9, though, then we can relax this. + if r == nil || r.Dial == nil { + return false + } + } + + return c.netGo || r.preferGo() +} + +// addrLookupOrder determines which strategy to use to resolve addresses. +// The provided Resolver is optional. nil means to not consider its options. +// It also returns dnsConfig when it was used to determine the lookup order. +func (c *conf) addrLookupOrder(r *Resolver, addr string) (ret hostLookupOrder, dnsConf *dnsConfig) { + if c.dnsDebugLevel > 1 { + defer func() { + print("go package net: addrLookupOrder(", addr, ") = ", ret.String(), "\n") + }() + } + return c.lookupOrder(r, "") +} + +// hostLookupOrder determines which strategy to use to resolve hostname. +// The provided Resolver is optional. nil means to not consider its options. +// It also returns dnsConfig when it was used to determine the lookup order. +func (c *conf) hostLookupOrder(r *Resolver, hostname string) (ret hostLookupOrder, dnsConf *dnsConfig) { + if c.dnsDebugLevel > 1 { + defer func() { + print("go package net: hostLookupOrder(", hostname, ") = ", ret.String(), "\n") + }() + } + return c.lookupOrder(r, hostname) +} + +func (c *conf) lookupOrder(r *Resolver, hostname string) (ret hostLookupOrder, dnsConf *dnsConfig) { + // fallbackOrder is the order we return if we can't figure it out. + var fallbackOrder hostLookupOrder + + var canUseCgo bool + if c.mustUseGoResolver(r) { + // Go resolver was explicitly requested + // or cgo resolver is not available. + // Figure out the order below. + fallbackOrder = hostLookupFilesDNS + canUseCgo = false + } else if c.netCgo { + // Cgo resolver was explicitly requested. + return hostLookupCgo, nil + } else if c.preferCgo { + // Given a choice, we prefer the cgo resolver. + return hostLookupCgo, nil + } else { + // Neither resolver was explicitly requested + // and we have no preference. + + if bytealg.IndexByteString(hostname, '\\') != -1 || bytealg.IndexByteString(hostname, '%') != -1 { + // Don't deal with special form hostnames + // with backslashes or '%'. + return hostLookupCgo, nil + } + + // If something is unrecognized, use cgo. + fallbackOrder = hostLookupCgo + canUseCgo = true + } + + // On systems that don't use /etc/resolv.conf or /etc/nsswitch.conf, we are done. + switch c.goos { + case "windows", "plan9", "android", "ios": + return fallbackOrder, nil + } + + // Try to figure out the order to use for searches. + // If we don't recognize something, use fallbackOrder. + // That will use cgo unless the Go resolver was explicitly requested. + // If we do figure out the order, return something other + // than fallbackOrder to use the Go resolver with that order. + + dnsConf = getSystemDNSConfig() + + if canUseCgo && dnsConf.err != nil && !errors.Is(dnsConf.err, fs.ErrNotExist) && !errors.Is(dnsConf.err, fs.ErrPermission) { + // We can't read the resolv.conf file, so use cgo if we can. + return hostLookupCgo, dnsConf + } + + if canUseCgo && dnsConf.unknownOpt { + // We didn't recognize something in resolv.conf, + // so use cgo if we can. + return hostLookupCgo, dnsConf + } + + // OpenBSD is unique and doesn't use nsswitch.conf. + // It also doesn't support mDNS. + if c.goos == "openbsd" { + // OpenBSD's resolv.conf manpage says that a + // non-existent resolv.conf means "lookup" defaults + // to only "files", without DNS lookups. + if errors.Is(dnsConf.err, fs.ErrNotExist) { + return hostLookupFiles, dnsConf + } + + lookup := dnsConf.lookup + if len(lookup) == 0 { + // https://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/resolv.conf.5 + // "If the lookup keyword is not used in the + // system's resolv.conf file then the assumed + // order is 'bind file'" + return hostLookupDNSFiles, dnsConf + } + if len(lookup) < 1 || len(lookup) > 2 { + // We don't recognize this format. + return fallbackOrder, dnsConf + } + switch lookup[0] { + case "bind": + if len(lookup) == 2 { + if lookup[1] == "file" { + return hostLookupDNSFiles, dnsConf + } + // Unrecognized. + return fallbackOrder, dnsConf + } + return hostLookupDNS, dnsConf + case "file": + if len(lookup) == 2 { + if lookup[1] == "bind" { + return hostLookupFilesDNS, dnsConf + } + // Unrecognized. + return fallbackOrder, dnsConf + } + return hostLookupFiles, dnsConf + default: + // Unrecognized. + return fallbackOrder, dnsConf + } + + // We always return before this point. + // The code below is for non-OpenBSD. + } + + // Canonicalize the hostname by removing any trailing dot. + hostname = stringslite.TrimSuffix(hostname, ".") + + nss := getSystemNSS() + srcs := nss.sources["hosts"] + // If /etc/nsswitch.conf doesn't exist or doesn't specify any + // sources for "hosts", assume Go's DNS will work fine. + if errors.Is(nss.err, fs.ErrNotExist) || (nss.err == nil && len(srcs) == 0) { + if canUseCgo && c.goos == "solaris" { + // illumos defaults to + // "nis [NOTFOUND=return] files", + // which the go resolver doesn't support. + return hostLookupCgo, dnsConf + } + + return hostLookupFilesDNS, dnsConf + } + if nss.err != nil { + // We failed to parse or open nsswitch.conf, so + // we have nothing to base an order on. + return fallbackOrder, dnsConf + } + + var hasDNSSource bool + var hasDNSSourceChecked bool + + var filesSource, dnsSource bool + var first string + for i, src := range srcs { + if src.source == "files" || src.source == "dns" { + if canUseCgo && !src.standardCriteria() { + // non-standard; let libc deal with it. + return hostLookupCgo, dnsConf + } + if src.source == "files" { + filesSource = true + } else { + hasDNSSource = true + hasDNSSourceChecked = true + dnsSource = true + } + if first == "" { + first = src.source + } + continue + } + + if canUseCgo { + switch { + case hostname != "" && src.source == "myhostname": + // Let the cgo resolver handle myhostname + // if we are looking up the local hostname. + if isLocalhost(hostname) || isGateway(hostname) || isOutbound(hostname) { + return hostLookupCgo, dnsConf + } + hn, err := getHostname() + if err != nil || stringsEqualFold(hostname, hn) { + return hostLookupCgo, dnsConf + } + continue + case hostname != "" && stringslite.HasPrefix(src.source, "mdns"): + if stringsHasSuffixFold(hostname, ".local") { + // Per RFC 6762, the ".local" TLD is special. And + // because Go's native resolver doesn't do mDNS or + // similar local resolution mechanisms, assume that + // libc might (via Avahi, etc) and use cgo. + return hostLookupCgo, dnsConf + } + + // We don't parse mdns.allow files. They're rare. If one + // exists, it might list other TLDs (besides .local) or even + // '*', so just let libc deal with it. + var haveMDNSAllow bool + switch c.mdnsTest { + case mdnsFromSystem: + _, err := os.Stat("/etc/mdns.allow") + if err != nil && !errors.Is(err, fs.ErrNotExist) { + // Let libc figure out what is going on. + return hostLookupCgo, dnsConf + } + haveMDNSAllow = err == nil + case mdnsAssumeExists: + haveMDNSAllow = true + case mdnsAssumeDoesNotExist: + haveMDNSAllow = false + } + if haveMDNSAllow { + return hostLookupCgo, dnsConf + } + continue + default: + // Some source we don't know how to deal with. + return hostLookupCgo, dnsConf + } + } + + if !hasDNSSourceChecked { + hasDNSSourceChecked = true + for _, v := range srcs[i+1:] { + if v.source == "dns" { + hasDNSSource = true + break + } + } + } + + // If we saw a source we don't recognize, which can only + // happen if we can't use the cgo resolver, treat it as DNS, + // but only when there is no dns in all other sources. + if !hasDNSSource { + dnsSource = true + if first == "" { + first = "dns" + } + } + } + + // Cases where Go can handle it without cgo and C thread overhead, + // or where the Go resolver has been forced. + switch { + case filesSource && dnsSource: + if first == "files" { + return hostLookupFilesDNS, dnsConf + } else { + return hostLookupDNSFiles, dnsConf + } + case filesSource: + return hostLookupFiles, dnsConf + case dnsSource: + return hostLookupDNS, dnsConf + } + + // Something weird. Fallback to the default. + return fallbackOrder, dnsConf +} + +var netdns = godebug.New("netdns") + +// goDebugNetDNS parses the value of the GODEBUG "netdns" value. +// The netdns value can be of the form: +// +// 1 // debug level 1 +// 2 // debug level 2 +// cgo // use cgo for DNS lookups +// go // use go for DNS lookups +// cgo+1 // use cgo for DNS lookups + debug level 1 +// 1+cgo // same +// cgo+2 // same, but debug level 2 +// +// etc. +func goDebugNetDNS() (dnsMode string, debugLevel int) { + goDebug := netdns.Value() + parsePart := func(s string) { + if s == "" { + return + } + if '0' <= s[0] && s[0] <= '9' { + debugLevel, _, _ = dtoi(s) + } else { + dnsMode = s + } + } + if i := bytealg.IndexByteString(goDebug, '+'); i != -1 { + parsePart(goDebug[:i]) + parsePart(goDebug[i+1:]) + return + } + parsePart(goDebug) + return +} + +// isLocalhost reports whether h should be considered a "localhost" +// name for the myhostname NSS module. +func isLocalhost(h string) bool { + return stringsEqualFold(h, "localhost") || stringsEqualFold(h, "localhost.localdomain") || stringsHasSuffixFold(h, ".localhost") || stringsHasSuffixFold(h, ".localhost.localdomain") +} + +// isGateway reports whether h should be considered a "gateway" +// name for the myhostname NSS module. +func isGateway(h string) bool { + return stringsEqualFold(h, "_gateway") +} + +// isOutbound reports whether h should be considered an "outbound" +// name for the myhostname NSS module. +func isOutbound(h string) bool { + return stringsEqualFold(h, "_outbound") +} diff --git a/go/src/net/conf_test.go b/go/src/net/conf_test.go new file mode 100644 index 0000000000000000000000000000000000000000..6ebd6be635c95ad7a4379eb2d4d5c82f9574d832 --- /dev/null +++ b/go/src/net/conf_test.go @@ -0,0 +1,461 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "io/fs" + "os" + "testing" + "time" +) + +type nssHostTest struct { + host string + localhost string + want hostLookupOrder +} + +func nssStr(t *testing.T, s string) *nssConf { + f, err := os.CreateTemp(t.TempDir(), "nss") + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteString(s); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + return parseNSSConfFile(f.Name()) +} + +// represents a dnsConfig returned by parsing a nonexistent resolv.conf +var defaultResolvConf = &dnsConfig{ + servers: defaultNS, + ndots: 1, + timeout: 5, + attempts: 2, + err: fs.ErrNotExist, +} + +func TestConfHostLookupOrder(t *testing.T) { + // These tests are written for a system with cgo available, + // without using the netgo tag. + if netGoBuildTag { + t.Skip("skipping test because net package built with netgo tag") + } + if !cgoAvailable { + t.Skip("skipping test because cgo resolver not available") + } + + tests := []struct { + name string + c *conf + nss *nssConf + resolver *Resolver + resolv *dnsConfig + hostTests []nssHostTest + }{ + { + name: "force", + c: &conf{ + preferCgo: true, + netCgo: true, + }, + resolv: defaultResolvConf, + nss: nssStr(t, "foo: bar"), + hostTests: []nssHostTest{ + {"foo.local", "myhostname", hostLookupCgo}, + {"google.com", "myhostname", hostLookupCgo}, + }, + }, + { + name: "netgo_dns_before_files", + c: &conf{ + netGo: true, + }, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: dns files"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupDNSFiles}, + }, + }, + { + name: "netgo_fallback_on_cgo", + c: &conf{ + netGo: true, + }, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: dns files something_custom"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupDNSFiles}, + }, + }, + { + name: "ubuntu_trusty_avahi", + c: &conf{ + mdnsTest: mdnsAssumeDoesNotExist, + }, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4"), + hostTests: []nssHostTest{ + {"foo.local", "myhostname", hostLookupCgo}, + {"foo.local.", "myhostname", hostLookupCgo}, + {"foo.LOCAL", "myhostname", hostLookupCgo}, + {"foo.LOCAL.", "myhostname", hostLookupCgo}, + {"google.com", "myhostname", hostLookupFilesDNS}, + }, + }, + { + name: "freebsdlinux_no_resolv_conf", + c: &conf{ + goos: "freebsd", + }, + resolv: defaultResolvConf, + nss: nssStr(t, "foo: bar"), + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}}, + }, + // On OpenBSD, no resolv.conf means no DNS. + { + name: "openbsd_no_resolv_conf", + c: &conf{ + goos: "openbsd", + }, + resolv: defaultResolvConf, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFiles}}, + }, + { + name: "solaris_no_nsswitch", + c: &conf{ + goos: "solaris", + }, + resolv: defaultResolvConf, + nss: &nssConf{err: fs.ErrNotExist}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}}, + }, + { + name: "openbsd_lookup_bind_file", + c: &conf{ + goos: "openbsd", + }, + resolv: &dnsConfig{lookup: []string{"bind", "file"}}, + hostTests: []nssHostTest{ + {"google.com", "myhostname", hostLookupDNSFiles}, + {"foo.local", "myhostname", hostLookupDNSFiles}, + }, + }, + { + name: "openbsd_lookup_file_bind", + c: &conf{ + goos: "openbsd", + }, + resolv: &dnsConfig{lookup: []string{"file", "bind"}}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}}, + }, + { + name: "openbsd_lookup_bind", + c: &conf{ + goos: "openbsd", + }, + resolv: &dnsConfig{lookup: []string{"bind"}}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupDNS}}, + }, + { + name: "openbsd_lookup_file", + c: &conf{ + goos: "openbsd", + }, + resolv: &dnsConfig{lookup: []string{"file"}}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFiles}}, + }, + { + name: "openbsd_lookup_yp", + c: &conf{ + goos: "openbsd", + }, + resolv: &dnsConfig{lookup: []string{"file", "bind", "yp"}}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}}, + }, + { + name: "openbsd_lookup_two", + c: &conf{ + goos: "openbsd", + }, + resolv: &dnsConfig{lookup: []string{"file", "foo"}}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}}, + }, + { + name: "openbsd_lookup_empty", + c: &conf{ + goos: "openbsd", + }, + resolv: &dnsConfig{lookup: nil}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupDNSFiles}}, + }, + { + name: "linux_no_nsswitch.conf", + c: &conf{ + goos: "linux", + }, + resolv: defaultResolvConf, + nss: &nssConf{err: fs.ErrNotExist}, + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}}, + }, + { + name: "linux_empty_nsswitch.conf", + c: &conf{ + goos: "linux", + }, + resolv: defaultResolvConf, + nss: nssStr(t, ""), + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}}, + }, + { + name: "files_mdns_dns", + c: &conf{ + mdnsTest: mdnsAssumeDoesNotExist, + }, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: files mdns dns"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupFilesDNS}, + {"x.local", "myhostname", hostLookupCgo}, + }, + }, + { + name: "dns_special_hostnames", + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: dns"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupDNS}, + {"x\\.com", "myhostname", hostLookupCgo}, // punt on weird glibc escape + {"foo.com%en0", "myhostname", hostLookupCgo}, // and IPv6 zones + }, + }, + { + name: "mdns_allow", + c: &conf{ + mdnsTest: mdnsAssumeExists, + }, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: files mdns dns"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupCgo}, + {"x.local", "myhostname", hostLookupCgo}, + }, + }, + { + name: "files_dns", + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: files dns"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupFilesDNS}, + {"x", "myhostname", hostLookupFilesDNS}, + {"x.local", "myhostname", hostLookupFilesDNS}, + }, + }, + { + name: "dns_files", + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: dns files"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupDNSFiles}, + {"x", "myhostname", hostLookupDNSFiles}, + {"x.local", "myhostname", hostLookupDNSFiles}, + }, + }, + { + name: "something_custom", + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: dns files something_custom"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupCgo}, + }, + }, + { + name: "myhostname", + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: files dns myhostname"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupFilesDNS}, + {"myhostname", "myhostname", hostLookupCgo}, + {"myHostname", "myhostname", hostLookupCgo}, + {"myhostname.dot", "myhostname.dot", hostLookupCgo}, + {"myHostname.dot", "myhostname.dot", hostLookupCgo}, + {"_gateway", "myhostname", hostLookupCgo}, + {"_Gateway", "myhostname", hostLookupCgo}, + {"_outbound", "myhostname", hostLookupCgo}, + {"_Outbound", "myhostname", hostLookupCgo}, + {"localhost", "myhostname", hostLookupCgo}, + {"Localhost", "myhostname", hostLookupCgo}, + {"anything.localhost", "myhostname", hostLookupCgo}, + {"Anything.localhost", "myhostname", hostLookupCgo}, + {"localhost.localdomain", "myhostname", hostLookupCgo}, + {"Localhost.Localdomain", "myhostname", hostLookupCgo}, + {"anything.localhost.localdomain", "myhostname", hostLookupCgo}, + {"Anything.Localhost.Localdomain", "myhostname", hostLookupCgo}, + {"somehostname", "myhostname", hostLookupFilesDNS}, + }, + }, + { + name: "ubuntu14.04.02", + c: &conf{ + mdnsTest: mdnsAssumeDoesNotExist, + }, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: files myhostname mdns4_minimal [NOTFOUND=return] dns mdns4"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupFilesDNS}, + {"somehostname", "myhostname", hostLookupFilesDNS}, + {"myhostname", "myhostname", hostLookupCgo}, + }, + }, + // Debian Squeeze is just "dns,files", but lists all + // the default criteria for dns, but then has a + // non-standard but redundant notfound=return for the + // files. + { + name: "debian_squeeze", + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: dns [success=return notfound=continue unavail=continue tryagain=continue] files [notfound=return]"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupDNSFiles}, + {"somehostname", "myhostname", hostLookupDNSFiles}, + }, + }, + { + name: "resolv.conf-unknown", + c: &conf{}, + resolv: &dnsConfig{servers: defaultNS, ndots: 1, timeout: 5, attempts: 2, unknownOpt: true}, + nss: nssStr(t, "foo: bar"), + hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}}, + }, + // Issue 24393: make sure "Resolver.PreferGo = true" acts like netgo. + { + name: "resolver-prefergo", + resolver: &Resolver{PreferGo: true}, + c: &conf{ + preferCgo: true, + netCgo: true, + }, + resolv: defaultResolvConf, + nss: nssStr(t, ""), + hostTests: []nssHostTest{ + {"localhost", "myhostname", hostLookupFilesDNS}, + }, + }, + { + name: "unknown-source", + resolver: &Resolver{PreferGo: true}, + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: resolve files"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupDNSFiles}, + }, + }, + { + name: "dns-among-unknown-sources", + resolver: &Resolver{PreferGo: true}, + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: mymachines files dns"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupFilesDNS}, + }, + }, + { + name: "dns-among-unknown-sources-2", + resolver: &Resolver{PreferGo: true}, + c: &conf{}, + resolv: defaultResolvConf, + nss: nssStr(t, "hosts: dns mymachines files"), + hostTests: []nssHostTest{ + {"x.com", "myhostname", hostLookupDNSFiles}, + }, + }, + } + + origGetHostname := getHostname + defer func() { getHostname = origGetHostname }() + defer setSystemNSS(getSystemNSS(), 0) + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + for _, tt := range tests { + if !conf.forceUpdateConf(tt.resolv, time.Now().Add(time.Hour)) { + t.Errorf("%s: failed to change resolv config", tt.name) + } + for _, ht := range tt.hostTests { + getHostname = func() (string, error) { return ht.localhost, nil } + setSystemNSS(tt.nss, time.Hour) + + gotOrder, _ := tt.c.hostLookupOrder(tt.resolver, ht.host) + if gotOrder != ht.want { + t.Errorf("%s: hostLookupOrder(%q) = %v; want %v", tt.name, ht.host, gotOrder, ht.want) + } + } + } +} + +func TestAddrLookupOrder(t *testing.T) { + // This test is written for a system with cgo available, + // without using the netgo tag. + if netGoBuildTag { + t.Skip("skipping test because net package built with netgo tag") + } + if !cgoAvailable { + t.Skip("skipping test because cgo resolver not available") + } + + defer setSystemNSS(getSystemNSS(), 0) + c, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer c.teardown() + + if !c.forceUpdateConf(defaultResolvConf, time.Now().Add(time.Hour)) { + t.Fatal("failed to change resolv config") + } + + setSystemNSS(nssStr(t, "hosts: files myhostname dns"), time.Hour) + cnf := &conf{} + order, _ := cnf.addrLookupOrder(nil, "192.0.2.1") + if order != hostLookupCgo { + t.Errorf("addrLookupOrder returned: %v, want cgo", order) + } + + setSystemNSS(nssStr(t, "hosts: files mdns4 dns"), time.Hour) + order, _ = cnf.addrLookupOrder(nil, "192.0.2.1") + if order != hostLookupCgo { + t.Errorf("addrLookupOrder returned: %v, want cgo", order) + } + +} + +func setSystemNSS(nss *nssConf, addDur time.Duration) { + nssConfig.mu.Lock() + nssConfig.nssConf = nss + nssConfig.mu.Unlock() + nssConfig.acquireSema() + nssConfig.lastChecked = time.Now().Add(addDur) + nssConfig.releaseSema() +} + +func TestSystemConf(t *testing.T) { + systemConf() +} diff --git a/go/src/net/conn_test.go b/go/src/net/conn_test.go new file mode 100644 index 0000000000000000000000000000000000000000..87097e10ee3281c46744fad7d713fc7335f4a7d2 --- /dev/null +++ b/go/src/net/conn_test.go @@ -0,0 +1,63 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements API tests across platforms and should never have a build +// constraint. + +package net + +import ( + "testing" + "time" +) + +// someTimeout is used just to test that net.Conn implementations +// don't explode when their SetFooDeadline methods are called. +// It isn't actually used for testing timeouts. +const someTimeout = 1 * time.Hour + +func TestConnAndListener(t *testing.T) { + for i, network := range []string{"tcp", "unix", "unixpacket"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("skipping %s test", network) + } + + ls := newLocalServer(t, network) + defer ls.teardown() + ch := make(chan error, 1) + handler := func(ls *localServer, ln Listener) { ls.transponder(ln, ch) } + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + if ls.Listener.Addr().Network() != network { + t.Fatalf("got %s; want %s", ls.Listener.Addr().Network(), network) + } + + c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if c.LocalAddr().Network() != network || c.RemoteAddr().Network() != network { + t.Fatalf("got %s->%s; want %s->%s", c.LocalAddr().Network(), c.RemoteAddr().Network(), network, network) + } + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + + if _, err := c.Write([]byte("CONN AND LISTENER TEST")); err != nil { + t.Fatal(err) + } + rb := make([]byte, 128) + if _, err := c.Read(rb); err != nil { + t.Fatal(err) + } + + for err := range ch { + t.Errorf("#%d: %v", i, err) + } + }) + } +} diff --git a/go/src/net/dial.go b/go/src/net/dial.go new file mode 100644 index 0000000000000000000000000000000000000000..a87c57603a813ce70e64584da345507d1144db7d --- /dev/null +++ b/go/src/net/dial.go @@ -0,0 +1,999 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "internal/bytealg" + "internal/godebug" + "internal/nettrace" + "net/netip" + "syscall" + "time" +) + +const ( + // defaultTCPKeepAliveIdle is a default constant value for TCP_KEEPIDLE. + // See go.dev/issue/31510 for details. + defaultTCPKeepAliveIdle = 15 * time.Second + + // defaultTCPKeepAliveInterval is a default constant value for TCP_KEEPINTVL. + // It is the same as defaultTCPKeepAliveIdle, see go.dev/issue/31510 for details. + defaultTCPKeepAliveInterval = 15 * time.Second + + // defaultTCPKeepAliveCount is a default constant value for TCP_KEEPCNT. + defaultTCPKeepAliveCount = 9 + + // For the moment, MultiPath TCP is used by default with listeners, if + // available, but not with dialers. + // See go.dev/issue/56539 + defaultMPTCPEnabledListen = true + defaultMPTCPEnabledDial = false +) + +// The type of service offered +// +// 0 == MPTCP disabled +// 1 == MPTCP enabled +// 2 == MPTCP enabled on listeners only +// 3 == MPTCP enabled on dialers only +var multipathtcp = godebug.New("multipathtcp") + +// mptcpStatusDial is a tristate for Multipath TCP on clients, +// see go.dev/issue/56539 +type mptcpStatusDial uint8 + +const ( + // The value 0 is the system default, linked to defaultMPTCPEnabledDial + mptcpUseDefaultDial mptcpStatusDial = iota + mptcpEnabledDial + mptcpDisabledDial +) + +func (m *mptcpStatusDial) get() bool { + switch *m { + case mptcpEnabledDial: + return true + case mptcpDisabledDial: + return false + } + + // If MPTCP is forced via GODEBUG=multipathtcp=1 + if multipathtcp.Value() == "1" || multipathtcp.Value() == "3" { + multipathtcp.IncNonDefault() + + return true + } + + return defaultMPTCPEnabledDial +} + +func (m *mptcpStatusDial) set(use bool) { + if use { + *m = mptcpEnabledDial + } else { + *m = mptcpDisabledDial + } +} + +// mptcpStatusListen is a tristate for Multipath TCP on servers, +// see go.dev/issue/56539 +type mptcpStatusListen uint8 + +const ( + // The value 0 is the system default, linked to defaultMPTCPEnabledListen + mptcpUseDefaultListen mptcpStatusListen = iota + mptcpEnabledListen + mptcpDisabledListen +) + +func (m *mptcpStatusListen) get() bool { + switch *m { + case mptcpEnabledListen: + return true + case mptcpDisabledListen: + return false + } + + // If MPTCP is disabled via GODEBUG=multipathtcp=0 or only + // enabled on dialers, but not on listeners. + if multipathtcp.Value() == "0" || multipathtcp.Value() == "3" { + multipathtcp.IncNonDefault() + + return false + } + + return defaultMPTCPEnabledListen +} + +func (m *mptcpStatusListen) set(use bool) { + if use { + *m = mptcpEnabledListen + } else { + *m = mptcpDisabledListen + } +} + +// A Dialer contains options for connecting to an address. +// +// The zero value for each field is equivalent to dialing +// without that option. Dialing with the zero value of Dialer +// is therefore equivalent to just calling the [Dial] function. +// +// It is safe to call Dialer's methods concurrently. +type Dialer struct { + // Timeout is the maximum amount of time a dial will wait for + // a connect to complete. If Deadline is also set, it may fail + // earlier. + // + // The default is no timeout. + // + // When using TCP and dialing a host name with multiple IP + // addresses, the timeout may be divided between them. + // + // With or without a timeout, the operating system may impose + // its own earlier timeout. For instance, TCP timeouts are + // often around 3 minutes. + Timeout time.Duration + + // Deadline is the absolute point in time after which dials + // will fail. If Timeout is set, it may fail earlier. + // Zero means no deadline, or dependent on the operating system + // as with the Timeout option. + Deadline time.Time + + // LocalAddr is the local address to use when dialing an + // address. The address must be of a compatible type for the + // network being dialed. + // If nil, a local address is automatically chosen. + LocalAddr Addr + + // DualStack previously enabled RFC 6555 Fast Fallback + // support, also known as "Happy Eyeballs", in which IPv4 is + // tried soon if IPv6 appears to be misconfigured and + // hanging. + // + // Deprecated: Fast Fallback is enabled by default. To + // disable, set FallbackDelay to a negative value. + DualStack bool + + // FallbackDelay specifies the length of time to wait before + // spawning a RFC 6555 Fast Fallback connection. That is, this + // is the amount of time to wait for IPv6 to succeed before + // assuming that IPv6 is misconfigured and falling back to + // IPv4. + // + // If zero, a default delay of 300ms is used. + // A negative value disables Fast Fallback support. + FallbackDelay time.Duration + + // KeepAlive specifies the interval between keep-alive + // probes for an active network connection. + // + // KeepAlive is ignored if KeepAliveConfig.Enable is true. + // + // If zero, keep-alive probes are sent with a default value + // (currently 15 seconds), if supported by the protocol and operating + // system. Network protocols or operating systems that do + // not support keep-alive ignore this field. + // If negative, keep-alive probes are disabled. + KeepAlive time.Duration + + // KeepAliveConfig specifies the keep-alive probe configuration + // for an active network connection, when supported by the + // protocol and operating system. + // + // If KeepAliveConfig.Enable is true, keep-alive probes are enabled. + // If KeepAliveConfig.Enable is false and KeepAlive is negative, + // keep-alive probes are disabled. + KeepAliveConfig KeepAliveConfig + + // Resolver optionally specifies an alternate resolver to use. + Resolver *Resolver + + // Cancel is an optional channel whose closure indicates that + // the dial should be canceled. Not all types of dials support + // cancellation. + // + // Deprecated: Use DialContext instead. + Cancel <-chan struct{} + + // If Control is not nil, it is called after creating the network + // connection but before actually dialing. + // + // Network and address parameters passed to Control function are not + // necessarily the ones passed to Dial. Calling Dial with TCP networks + // will cause the Control function to be called with "tcp4" or "tcp6", + // UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6", + // and other known networks are passed as-is. + // + // Control is ignored if ControlContext is not nil. + Control func(network, address string, c syscall.RawConn) error + + // If ControlContext is not nil, it is called after creating the network + // connection but before actually dialing. + // + // Network and address parameters passed to ControlContext function are not + // necessarily the ones passed to Dial. Calling Dial with TCP networks + // will cause the ControlContext function to be called with "tcp4" or "tcp6", + // UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6", + // and other known networks are passed as-is. + // + // If ControlContext is not nil, Control is ignored. + ControlContext func(ctx context.Context, network, address string, c syscall.RawConn) error + + // If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be + // used, any call to Dial with "tcp(4|6)" as network will use MPTCP if + // supported by the operating system. + mptcpStatus mptcpStatusDial +} + +func (d *Dialer) dualStack() bool { return d.FallbackDelay >= 0 } + +func minNonzeroTime(a, b time.Time) time.Time { + if a.IsZero() { + return b + } + if b.IsZero() || a.Before(b) { + return a + } + return b +} + +// deadline returns the earliest of: +// - now+Timeout +// - d.Deadline +// - the context's deadline +// +// Or zero, if none of Timeout, Deadline, or context's deadline is set. +func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time) { + if d.Timeout != 0 { // including negative, for historical reasons + earliest = now.Add(d.Timeout) + } + if d, ok := ctx.Deadline(); ok { + earliest = minNonzeroTime(earliest, d) + } + return minNonzeroTime(earliest, d.Deadline) +} + +func (d *Dialer) resolver() *Resolver { + if d.Resolver != nil { + return d.Resolver + } + return DefaultResolver +} + +// partialDeadline returns the deadline to use for a single address, +// when multiple addresses are pending. +func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error) { + if deadline.IsZero() { + return deadline, nil + } + timeRemaining := deadline.Sub(now) + if timeRemaining <= 0 { + return time.Time{}, errTimeout + } + // Tentatively allocate equal time to each remaining address. + timeout := timeRemaining / time.Duration(addrsRemaining) + // If the time per address is too short, steal from the end of the list. + const saneMinimum = 2 * time.Second + if timeout < saneMinimum { + if timeRemaining < saneMinimum { + timeout = timeRemaining + } else { + timeout = saneMinimum + } + } + return now.Add(timeout), nil +} + +func (d *Dialer) fallbackDelay() time.Duration { + if d.FallbackDelay > 0 { + return d.FallbackDelay + } else { + return 300 * time.Millisecond + } +} + +func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error) { + i := bytealg.LastIndexByteString(network, ':') + if i < 0 { // no colon + switch network { + case "tcp", "tcp4", "tcp6": + case "udp", "udp4", "udp6": + case "ip", "ip4", "ip6": + if needsProto { + return "", 0, UnknownNetworkError(network) + } + case "unix", "unixgram", "unixpacket": + default: + return "", 0, UnknownNetworkError(network) + } + return network, 0, nil + } + afnet = network[:i] + switch afnet { + case "ip", "ip4", "ip6": + protostr := network[i+1:] + proto, i, ok := dtoi(protostr) + if !ok || i != len(protostr) { + proto, err = lookupProtocol(ctx, protostr) + if err != nil { + return "", 0, err + } + } + return afnet, proto, nil + } + return "", 0, UnknownNetworkError(network) +} + +// resolveAddrList resolves addr using hint and returns a list of +// addresses. The result contains at least one address when error is +// nil. +func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error) { + afnet, _, err := parseNetwork(ctx, network, true) + if err != nil { + return nil, err + } + if op == "dial" && addr == "" { + return nil, errMissingAddress + } + switch afnet { + case "unix", "unixgram", "unixpacket": + addr, err := ResolveUnixAddr(afnet, addr) + if err != nil { + return nil, err + } + if op == "dial" && hint != nil && addr.Network() != hint.Network() { + return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()} + } + return addrList{addr}, nil + } + addrs, err := r.internetAddrList(ctx, afnet, addr) + if err != nil || op != "dial" || hint == nil { + return addrs, err + } + var ( + tcp *TCPAddr + udp *UDPAddr + ip *IPAddr + wildcard bool + ) + switch hint := hint.(type) { + case *TCPAddr: + tcp = hint + wildcard = tcp.isWildcard() + case *UDPAddr: + udp = hint + wildcard = udp.isWildcard() + case *IPAddr: + ip = hint + wildcard = ip.isWildcard() + } + naddrs := addrs[:0] + for _, addr := range addrs { + if addr.Network() != hint.Network() { + return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()} + } + switch addr := addr.(type) { + case *TCPAddr: + if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(tcp.IP) { + continue + } + naddrs = append(naddrs, addr) + case *UDPAddr: + if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(udp.IP) { + continue + } + naddrs = append(naddrs, addr) + case *IPAddr: + if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(ip.IP) { + continue + } + naddrs = append(naddrs, addr) + } + } + if len(naddrs) == 0 { + return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: hint.String()} + } + return naddrs, nil +} + +// MultipathTCP reports whether MPTCP will be used. +// +// This method doesn't check if MPTCP is supported by the operating +// system or not. +func (d *Dialer) MultipathTCP() bool { + return d.mptcpStatus.get() +} + +// SetMultipathTCP directs the [Dial] methods to use, or not use, MPTCP, +// if supported by the operating system. This method overrides the +// system default and the GODEBUG=multipathtcp=... setting if any. +// +// If MPTCP is not available on the host or not supported by the server, +// the Dial methods will fall back to TCP. +func (d *Dialer) SetMultipathTCP(use bool) { + d.mptcpStatus.set(use) +} + +// Dial connects to the address on the named network. +// +// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), +// "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" +// (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and +// "unixpacket". +// +// For TCP and UDP networks, the address has the form "host:port". +// The host must be a literal IP address, or a host name that can be +// resolved to IP addresses. +// The port must be a literal port number or a service name. +// If the host is a literal IPv6 address it must be enclosed in square +// brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80". +// The zone specifies the scope of the literal IPv6 address as defined +// in RFC 4007. +// The functions [JoinHostPort] and [SplitHostPort] manipulate a pair of +// host and port in this form. +// When using TCP, and the host resolves to multiple IP addresses, +// Dial will try each IP address in order until one succeeds. +// +// Examples: +// +// Dial("tcp", "golang.org:http") +// Dial("tcp", "192.0.2.1:http") +// Dial("tcp", "198.51.100.1:80") +// Dial("udp", "[2001:db8::1]:domain") +// Dial("udp", "[fe80::1%lo0]:53") +// Dial("tcp", ":80") +// +// For IP networks, the network must be "ip", "ip4" or "ip6" followed +// by a colon and a literal protocol number or a protocol name, and +// the address has the form "host". The host must be a literal IP +// address or a literal IPv6 address with zone. +// It depends on each operating system how the operating system +// behaves with a non-well known protocol number such as "0" or "255". +// +// Examples: +// +// Dial("ip4:1", "192.0.2.1") +// Dial("ip6:ipv6-icmp", "2001:db8::1") +// Dial("ip6:58", "fe80::1%lo0") +// +// For TCP, UDP and IP networks, if the host is empty or a literal +// unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for +// TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is +// assumed. +// +// For Unix networks, the address must be a file system path. +func Dial(network, address string) (Conn, error) { + var d Dialer + return d.Dial(network, address) +} + +// DialTimeout acts like [Dial] but takes a timeout. +// +// The timeout includes name resolution, if required. +// When using TCP, and the host in the address parameter resolves to +// multiple IP addresses, the timeout is spread over each consecutive +// dial, such that each is given an appropriate fraction of the time +// to connect. +// +// See func Dial for a description of the network and address +// parameters. +func DialTimeout(network, address string, timeout time.Duration) (Conn, error) { + d := Dialer{Timeout: timeout} + return d.Dial(network, address) +} + +// sysDialer contains a Dial's parameters and configuration. +type sysDialer struct { + Dialer + network, address string + testHookDialTCP func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error) +} + +// Dial connects to the address on the named network. +// +// See func Dial for a description of the network and address +// parameters. +// +// Dial uses [context.Background] internally; to specify the context, use +// [Dialer.DialContext]. +func (d *Dialer) Dial(network, address string) (Conn, error) { + return d.DialContext(context.Background(), network, address) +} + +// DialContext connects to the address on the named network using +// the provided context. +// +// The provided Context must be non-nil. If the context expires before +// the connection is complete, an error is returned. Once successfully +// connected, any expiration of the context will not affect the +// connection. +// +// When using TCP, and the host in the address parameter resolves to multiple +// network addresses, any dial timeout (from d.Timeout or ctx) is spread +// over each consecutive dial, such that each is given an appropriate +// fraction of the time to connect. +// For example, if a host has 4 IP addresses and the timeout is 1 minute, +// the connect to each single address will be given 15 seconds to complete +// before trying the next one. +// +// See func [Dial] for a description of the network and address +// parameters. +func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) { + ctx, cancel := d.dialCtx(ctx) + defer cancel() + + // Shadow the nettrace (if any) during resolve so Connect events don't fire for DNS lookups. + resolveCtx := ctx + if trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace); trace != nil { + shadow := *trace + shadow.ConnectStart = nil + shadow.ConnectDone = nil + resolveCtx = context.WithValue(resolveCtx, nettrace.TraceKey{}, &shadow) + } + + addrs, err := d.resolver().resolveAddrList(resolveCtx, "dial", network, address, d.LocalAddr) + if err != nil { + return nil, &OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err} + } + + sd := &sysDialer{ + Dialer: *d, + network: network, + address: address, + } + + var primaries, fallbacks addrList + if d.dualStack() && network == "tcp" { + primaries, fallbacks = addrs.partition(isIPv4) + } else { + primaries = addrs + } + + return sd.dialParallel(ctx, primaries, fallbacks) +} + +func (d *Dialer) dialCtx(ctx context.Context) (context.Context, context.CancelFunc) { + if ctx == nil { + panic("nil context") + } + deadline := d.deadline(ctx, time.Now()) + var cancel1, cancel2 context.CancelFunc + if !deadline.IsZero() { + testHookStepTime() + if d, ok := ctx.Deadline(); !ok || deadline.Before(d) { + var subCtx context.Context + subCtx, cancel1 = context.WithDeadline(ctx, deadline) + ctx = subCtx + } + } + if oldCancel := d.Cancel; oldCancel != nil { + subCtx, cancel2 := context.WithCancel(ctx) + go func() { + select { + case <-oldCancel: + cancel2() + case <-subCtx.Done(): + } + }() + ctx = subCtx + } + return ctx, func() { + if cancel1 != nil { + cancel1() + } + if cancel2 != nil { + cancel2() + } + } +} + +// DialTCP acts like Dial for TCP networks using the provided context. +// +// The provided Context must be non-nil. If the context expires before +// the connection is complete, an error is returned. Once successfully +// connected, any expiration of the context will not affect the +// connection. +// +// The network must be a TCP network name; see func Dial for details. +func (d *Dialer) DialTCP(ctx context.Context, network string, laddr netip.AddrPort, raddr netip.AddrPort) (*TCPConn, error) { + ctx, cancel := d.dialCtx(ctx) + defer cancel() + return dialTCP(ctx, d, network, TCPAddrFromAddrPort(laddr), TCPAddrFromAddrPort(raddr)) +} + +// DialUDP acts like Dial for UDP networks using the provided context. +// +// The provided Context must be non-nil. If the context expires before +// the connection is complete, an error is returned. Once successfully +// connected, any expiration of the context will not affect the +// connection. +// +// The network must be a UDP network name; see func Dial for details. +func (d *Dialer) DialUDP(ctx context.Context, network string, laddr netip.AddrPort, raddr netip.AddrPort) (*UDPConn, error) { + ctx, cancel := d.dialCtx(ctx) + defer cancel() + return dialUDP(ctx, d, network, UDPAddrFromAddrPort(laddr), UDPAddrFromAddrPort(raddr)) +} + +// DialIP acts like Dial for IP networks using the provided context. +// +// The provided Context must be non-nil. If the context expires before +// the connection is complete, an error is returned. Once successfully +// connected, any expiration of the context will not affect the +// connection. +// +// The network must be an IP network name; see func Dial for details. +func (d *Dialer) DialIP(ctx context.Context, network string, laddr netip.Addr, raddr netip.Addr) (*IPConn, error) { + ctx, cancel := d.dialCtx(ctx) + defer cancel() + return dialIP(ctx, d, network, ipAddrFromAddr(laddr), ipAddrFromAddr(raddr)) +} + +// DialUnix acts like Dial for Unix networks using the provided context. +// +// The provided Context must be non-nil. If the context expires before +// the connection is complete, an error is returned. Once successfully +// connected, any expiration of the context will not affect the +// connection. +// +// The network must be a Unix network name; see func Dial for details. +func (d *Dialer) DialUnix(ctx context.Context, network string, laddr *UnixAddr, raddr *UnixAddr) (*UnixConn, error) { + ctx, cancel := d.dialCtx(ctx) + defer cancel() + return dialUnix(ctx, d, network, laddr, raddr) +} + +// dialParallel races two copies of dialSerial, giving the first a +// head start. It returns the first established connection and +// closes the others. Otherwise it returns an error from the first +// primary address. +func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error) { + if len(fallbacks) == 0 { + return sd.dialSerial(ctx, primaries) + } + + returned := make(chan struct{}) + defer close(returned) + + type dialResult struct { + Conn + error + primary bool + done bool + } + results := make(chan dialResult) // unbuffered + + startRacer := func(ctx context.Context, primary bool) { + ras := primaries + if !primary { + ras = fallbacks + } + c, err := sd.dialSerial(ctx, ras) + select { + case results <- dialResult{Conn: c, error: err, primary: primary, done: true}: + case <-returned: + if c != nil { + c.Close() + } + } + } + + var primary, fallback dialResult + + // Start the main racer. + primaryCtx, primaryCancel := context.WithCancel(ctx) + defer primaryCancel() + go startRacer(primaryCtx, true) + + // Start the timer for the fallback racer. + fallbackTimer := time.NewTimer(sd.fallbackDelay()) + defer fallbackTimer.Stop() + + for { + select { + case <-fallbackTimer.C: + fallbackCtx, fallbackCancel := context.WithCancel(ctx) + defer fallbackCancel() + go startRacer(fallbackCtx, false) + + case res := <-results: + if res.error == nil { + return res.Conn, nil + } + if res.primary { + primary = res + } else { + fallback = res + } + if primary.done && fallback.done { + return nil, primary.error + } + if res.primary && fallbackTimer.Stop() { + // If we were able to stop the timer, that means it + // was running (hadn't yet started the fallback), but + // we just got an error on the primary path, so start + // the fallback immediately (in 0 nanoseconds). + fallbackTimer.Reset(0) + } + } + } +} + +// dialSerial connects to a list of addresses in sequence, returning +// either the first successful connection, or the first error. +func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error) { + var firstErr error // The error from the first address is most relevant. + + for i, ra := range ras { + select { + case <-ctx.Done(): + return nil, &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: mapErr(ctx.Err())} + default: + } + + dialCtx := ctx + if deadline, hasDeadline := ctx.Deadline(); hasDeadline { + partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i) + if err != nil { + // Ran out of time. + if firstErr == nil { + firstErr = &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: err} + } + break + } + if partialDeadline.Before(deadline) { + var cancel context.CancelFunc + dialCtx, cancel = context.WithDeadline(ctx, partialDeadline) + defer cancel() + } + } + + c, err := sd.dialSingle(dialCtx, ra) + if err == nil { + return c, nil + } + if firstErr == nil { + firstErr = err + } + } + + if firstErr == nil { + firstErr = &OpError{Op: "dial", Net: sd.network, Source: nil, Addr: nil, Err: errMissingAddress} + } + return nil, firstErr +} + +// dialSingle attempts to establish and returns a single connection to +// the destination address. +func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error) { + trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace) + if trace != nil { + raStr := ra.String() + if trace.ConnectStart != nil { + trace.ConnectStart(sd.network, raStr) + } + if trace.ConnectDone != nil { + defer func() { trace.ConnectDone(sd.network, raStr, err) }() + } + } + la := sd.LocalAddr + switch ra := ra.(type) { + case *TCPAddr: + la, _ := la.(*TCPAddr) + if sd.MultipathTCP() { + c, err = sd.dialMPTCP(ctx, la, ra) + } else { + c, err = sd.dialTCP(ctx, la, ra) + } + case *UDPAddr: + la, _ := la.(*UDPAddr) + c, err = sd.dialUDP(ctx, la, ra) + case *IPAddr: + la, _ := la.(*IPAddr) + c, err = sd.dialIP(ctx, la, ra) + case *UnixAddr: + la, _ := la.(*UnixAddr) + c, err = sd.dialUnix(ctx, la, ra) + default: + return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: &AddrError{Err: "unexpected address type", Addr: sd.address}} + } + if err != nil { + return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: err} // c is non-nil interface containing nil pointer + } + return c, nil +} + +// ListenConfig contains options for listening to an address. +type ListenConfig struct { + // If Control is not nil, it is called after creating the network + // connection but before binding it to the operating system. + // + // Network and address parameters passed to Control function are not + // necessarily the ones passed to Listen. Calling Listen with TCP networks + // will cause the Control function to be called with "tcp4" or "tcp6", + // UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6", + // and other known networks are passed as-is. + Control func(network, address string, c syscall.RawConn) error + + // KeepAlive specifies the keep-alive period for network + // connections accepted by this listener. + // + // KeepAlive is ignored if KeepAliveConfig.Enable is true. + // + // If zero, keep-alive are enabled if supported by the protocol + // and operating system. Network protocols or operating systems + // that do not support keep-alive ignore this field. + // If negative, keep-alive are disabled. + KeepAlive time.Duration + + // KeepAliveConfig specifies the keep-alive probe configuration + // for an active network connection, when supported by the + // protocol and operating system. + // + // If KeepAliveConfig.Enable is true, keep-alive probes are enabled. + // If KeepAliveConfig.Enable is false and KeepAlive is negative, + // keep-alive probes are disabled. + KeepAliveConfig KeepAliveConfig + + // If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be + // used, any call to Listen with "tcp(4|6)" as network will use MPTCP if + // supported by the operating system. + mptcpStatus mptcpStatusListen +} + +// MultipathTCP reports whether MPTCP will be used. +// +// This method doesn't check if MPTCP is supported by the operating +// system or not. +func (lc *ListenConfig) MultipathTCP() bool { + return lc.mptcpStatus.get() +} + +// SetMultipathTCP directs the [Listen] method to use, or not use, MPTCP, +// if supported by the operating system. This method overrides the +// system default and the GODEBUG=multipathtcp=... setting if any. +// +// If MPTCP is not available on the host or not supported by the client, +// the Listen method will fall back to TCP. +func (lc *ListenConfig) SetMultipathTCP(use bool) { + lc.mptcpStatus.set(use) +} + +// Listen announces on the local network address. +// +// See func Listen for a description of the network and address +// parameters. +// +// The ctx argument is used while resolving the address on which to listen; +// it does not affect the returned Listener. +func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error) { + addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil) + if err != nil { + return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err} + } + sl := &sysListener{ + ListenConfig: *lc, + network: network, + address: address, + } + var l Listener + la := addrs.first(isIPv4) + switch la := la.(type) { + case *TCPAddr: + if sl.MultipathTCP() { + l, err = sl.listenMPTCP(ctx, la) + } else { + l, err = sl.listenTCP(ctx, la) + } + case *UnixAddr: + l, err = sl.listenUnix(ctx, la) + default: + return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}} + } + if err != nil { + return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // l is non-nil interface containing nil pointer + } + return l, nil +} + +// ListenPacket announces on the local network address. +// +// See func ListenPacket for a description of the network and address +// parameters. +// +// The ctx argument is used while resolving the address on which to listen; +// it does not affect the returned PacketConn. +func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) { + addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil) + if err != nil { + return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err} + } + sl := &sysListener{ + ListenConfig: *lc, + network: network, + address: address, + } + var c PacketConn + la := addrs.first(isIPv4) + switch la := la.(type) { + case *UDPAddr: + c, err = sl.listenUDP(ctx, la) + case *IPAddr: + c, err = sl.listenIP(ctx, la) + case *UnixAddr: + c, err = sl.listenUnixgram(ctx, la) + default: + return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}} + } + if err != nil { + return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // c is non-nil interface containing nil pointer + } + return c, nil +} + +// sysListener contains a Listen's parameters and configuration. +type sysListener struct { + ListenConfig + network, address string +} + +// Listen announces on the local network address. +// +// The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket". +// +// For TCP networks, if the host in the address parameter is empty or +// a literal unspecified IP address, Listen listens on all available +// unicast and anycast IP addresses of the local system. +// To only use IPv4, use network "tcp4". +// The address can use a host name, but this is not recommended, +// because it will create a listener for at most one of the host's IP +// addresses. +// If the port in the address parameter is empty or "0", as in +// "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. +// The [Addr] method of [Listener] can be used to discover the chosen +// port. +// +// See func [Dial] for a description of the network and address +// parameters. +// +// Listen uses context.Background internally; to specify the context, use +// [ListenConfig.Listen]. +func Listen(network, address string) (Listener, error) { + var lc ListenConfig + return lc.Listen(context.Background(), network, address) +} + +// ListenPacket announces on the local network address. +// +// The network must be "udp", "udp4", "udp6", "unixgram", or an IP +// transport. The IP transports are "ip", "ip4", or "ip6" followed by +// a colon and a literal protocol number or a protocol name, as in +// "ip:1" or "ip:icmp". +// +// For UDP and IP networks, if the host in the address parameter is +// empty or a literal unspecified IP address, ListenPacket listens on +// all available IP addresses of the local system except multicast IP +// addresses. +// To only use IPv4, use network "udp4" or "ip4:proto". +// The address can use a host name, but this is not recommended, +// because it will create a listener for at most one of the host's IP +// addresses. +// If the port in the address parameter is empty or "0", as in +// "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. +// The LocalAddr method of [PacketConn] can be used to discover the +// chosen port. +// +// See func [Dial] for a description of the network and address +// parameters. +// +// ListenPacket uses context.Background internally; to specify the context, use +// [ListenConfig.ListenPacket]. +func ListenPacket(network, address string) (PacketConn, error) { + var lc ListenConfig + return lc.ListenPacket(context.Background(), network, address) +} diff --git a/go/src/net/dial_test.go b/go/src/net/dial_test.go new file mode 100644 index 0000000000000000000000000000000000000000..07a9b46ddb69ef450a8502c159d5418c2dad7cdb --- /dev/null +++ b/go/src/net/dial_test.go @@ -0,0 +1,1202 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "bufio" + "context" + "errors" + "fmt" + "internal/testenv" + "io" + "net/netip" + "os" + "runtime" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +var prohibitionaryDialArgTests = []struct { + network string + address string +}{ + {"tcp6", "127.0.0.1"}, + {"tcp6", "::ffff:127.0.0.1"}, +} + +func TestProhibitionaryDialArg(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + if !supportsIPv4map() { + t.Skip("mapping ipv4 address inside ipv6 address not supported") + } + + ln, err := Listen("tcp", "[::]:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + _, port, err := SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + + for i, tt := range prohibitionaryDialArgTests { + c, err := Dial(tt.network, JoinHostPort(tt.address, port)) + if err == nil { + c.Close() + t.Errorf("#%d: %v", i, err) + } + } +} + +func TestDialLocal(t *testing.T) { + ln := newLocalListener(t, "tcp") + defer ln.Close() + _, port, err := SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + c, err := Dial("tcp", JoinHostPort("", port)) + if err != nil { + t.Fatal(err) + } + c.Close() +} + +func TestDialerDualStackFDLeak(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("%s does not have full support of socktest", runtime.GOOS) + case "windows": + t.Skipf("not implemented a way to cancel dial racers in TCP SYN-SENT state on %s", runtime.GOOS) + case "openbsd": + testenv.SkipFlaky(t, 15157) + } + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + before := sw.Sockets() + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = lookupLocalhost + handler := func(dss *dualStackServer, ln Listener) { + for { + c, err := ln.Accept() + if err != nil { + return + } + c.Close() + } + } + dss, err := newDualStackServer() + if err != nil { + t.Fatal(err) + } + if err := dss.buildup(handler); err != nil { + dss.teardown() + t.Fatal(err) + } + + const N = 10 + var wg sync.WaitGroup + wg.Add(N) + d := &Dialer{DualStack: true, Timeout: 5 * time.Second} + for i := 0; i < N; i++ { + go func() { + defer wg.Done() + c, err := d.Dial("tcp", JoinHostPort("localhost", dss.port)) + if err != nil { + t.Error(err) + return + } + c.Close() + }() + } + wg.Wait() + dss.teardown() + after := sw.Sockets() + if len(after) != len(before) { + t.Errorf("got %d; want %d", len(after), len(before)) + } +} + +// Define a pair of blackholed (IPv4, IPv6) addresses, for which dialTCP is +// expected to hang until the timeout elapses. These addresses are reserved +// for benchmarking by RFC 6890. +const ( + slowDst4 = "198.18.0.254" + slowDst6 = "2001:2::254" +) + +// In some environments, the slow IPs may be explicitly unreachable, and fail +// more quickly than expected. This test hook prevents dialTCP from returning +// before the deadline. +func slowDialTCP(ctx context.Context, network string, laddr, raddr *TCPAddr) (*TCPConn, error) { + sd := &sysDialer{network: network, address: raddr.String()} + c, err := sd.doDialTCP(ctx, laddr, raddr) + if ParseIP(slowDst4).Equal(raddr.IP) || ParseIP(slowDst6).Equal(raddr.IP) { + // Wait for the deadline, or indefinitely if none exists. + <-ctx.Done() + } + return c, err +} + +func dialClosedPort(t *testing.T) (dialLatency time.Duration) { + // On most platforms, dialing a closed port should be nearly instantaneous — + // less than a few hundred milliseconds. However, on some platforms it may be + // much slower: on Windows and OpenBSD, it has been observed to take up to a + // few seconds. + + l, err := Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("dialClosedPort: Listen failed: %v", err) + } + addr := l.Addr().String() + l.Close() + + startTime := time.Now() + c, err := Dial("tcp", addr) + if err == nil { + c.Close() + } + elapsed := time.Since(startTime) + t.Logf("dialClosedPort: measured delay %v", elapsed) + return elapsed +} + +func TestDialParallel(t *testing.T) { + const instant time.Duration = 0 + const fallbackDelay = 200 * time.Millisecond + + nCopies := func(s string, n int) []string { + out := make([]string, n) + for i := 0; i < n; i++ { + out[i] = s + } + return out + } + + var testCases = []struct { + primaries []string + fallbacks []string + teardownNetwork string + expectOk bool + expectElapsed time.Duration + }{ + // These should just work on the first try. + {[]string{"127.0.0.1"}, []string{}, "", true, instant}, + {[]string{"::1"}, []string{}, "", true, instant}, + {[]string{"127.0.0.1", "::1"}, []string{slowDst6}, "tcp6", true, instant}, + {[]string{"::1", "127.0.0.1"}, []string{slowDst4}, "tcp4", true, instant}, + // Primary is slow; fallback should kick in. + {[]string{slowDst4}, []string{"::1"}, "", true, fallbackDelay}, + // Skip a "connection refused" in the primary thread. + {[]string{"127.0.0.1", "::1"}, []string{}, "tcp4", true, instant}, + {[]string{"::1", "127.0.0.1"}, []string{}, "tcp6", true, instant}, + // Skip a "connection refused" in the fallback thread. + {[]string{slowDst4, slowDst6}, []string{"::1", "127.0.0.1"}, "tcp6", true, fallbackDelay}, + // Primary refused, fallback without delay. + {[]string{"127.0.0.1"}, []string{"::1"}, "tcp4", true, instant}, + {[]string{"::1"}, []string{"127.0.0.1"}, "tcp6", true, instant}, + // Everything is refused. + {[]string{"127.0.0.1"}, []string{}, "tcp4", false, instant}, + // Nothing to do; fail instantly. + {[]string{}, []string{}, "", false, instant}, + // Connecting to tons of addresses should not trip the deadline. + {nCopies("::1", 1000), []string{}, "", true, instant}, + } + + // Convert a list of IP strings into TCPAddrs. + makeAddrs := func(ips []string, port string) addrList { + var out addrList + for _, ip := range ips { + addr, err := ResolveTCPAddr("tcp", JoinHostPort(ip, port)) + if err != nil { + t.Fatal(err) + } + out = append(out, addr) + } + return out + } + + for i, tt := range testCases { + t.Run(fmt.Sprint(i), func(t *testing.T) { + dialTCP := func(ctx context.Context, network string, laddr, raddr *TCPAddr) (*TCPConn, error) { + n := "tcp6" + if raddr.IP.To4() != nil { + n = "tcp4" + } + if n == tt.teardownNetwork { + return nil, errors.New("unreachable") + } + if r := raddr.IP.String(); r == slowDst4 || r == slowDst6 { + <-ctx.Done() + return nil, ctx.Err() + } + return &TCPConn{}, nil + } + + primaries := makeAddrs(tt.primaries, "80") + fallbacks := makeAddrs(tt.fallbacks, "80") + d := Dialer{ + FallbackDelay: fallbackDelay, + } + const forever = 60 * time.Minute + if tt.expectElapsed == instant { + d.FallbackDelay = forever + } + startTime := time.Now() + sd := &sysDialer{ + Dialer: d, + network: "tcp", + address: "?", + testHookDialTCP: dialTCP, + } + c, err := sd.dialParallel(context.Background(), primaries, fallbacks) + elapsed := time.Since(startTime) + + if c != nil { + c.Close() + } + + if tt.expectOk && err != nil { + t.Errorf("#%d: got %v; want nil", i, err) + } else if !tt.expectOk && err == nil { + t.Errorf("#%d: got nil; want non-nil", i) + } + + if elapsed < tt.expectElapsed || elapsed >= forever { + t.Errorf("#%d: got %v; want >= %v, < forever", i, elapsed, tt.expectElapsed) + } + + // Repeat each case, ensuring that it can be canceled. + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + wg.Add(1) + go func() { + time.Sleep(5 * time.Millisecond) + cancel() + wg.Done() + }() + // Ignore errors, since all we care about is that the + // call can be canceled. + c, _ = sd.dialParallel(ctx, primaries, fallbacks) + if c != nil { + c.Close() + } + wg.Wait() + }) + } +} + +func lookupSlowFast(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + switch host { + case "slow6loopback4": + // Returns a slow IPv6 address, and a local IPv4 address. + return []IPAddr{ + {IP: ParseIP(slowDst6)}, + {IP: ParseIP("127.0.0.1")}, + }, nil + default: + return fn(ctx, network, host) + } +} + +func TestDialerFallbackDelay(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = lookupSlowFast + + origTestHookDialTCP := testHookDialTCP + defer func() { testHookDialTCP = origTestHookDialTCP }() + testHookDialTCP = slowDialTCP + + var testCases = []struct { + dualstack bool + delay time.Duration + expectElapsed time.Duration + }{ + // Use a very brief delay, which should fallback immediately. + {true, 1 * time.Nanosecond, 0}, + // Use a 200ms explicit timeout. + {true, 200 * time.Millisecond, 200 * time.Millisecond}, + // The default is 300ms. + {true, 0, 300 * time.Millisecond}, + } + + handler := func(dss *dualStackServer, ln Listener) { + for { + c, err := ln.Accept() + if err != nil { + return + } + c.Close() + } + } + dss, err := newDualStackServer() + if err != nil { + t.Fatal(err) + } + defer dss.teardown() + if err := dss.buildup(handler); err != nil { + t.Fatal(err) + } + + for i, tt := range testCases { + d := &Dialer{DualStack: tt.dualstack, FallbackDelay: tt.delay} + + startTime := time.Now() + c, err := d.Dial("tcp", JoinHostPort("slow6loopback4", dss.port)) + elapsed := time.Since(startTime) + if err == nil { + c.Close() + } else if tt.dualstack { + t.Error(err) + } + expectMin := tt.expectElapsed - 1*time.Millisecond + expectMax := tt.expectElapsed + 95*time.Millisecond + if elapsed < expectMin { + t.Errorf("#%d: got %v; want >= %v", i, elapsed, expectMin) + } + if elapsed > expectMax { + t.Errorf("#%d: got %v; want <= %v", i, elapsed, expectMax) + } + } +} + +func TestDialParallelSpuriousConnection(t *testing.T) { + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + var readDeadline time.Time + if td, ok := t.Deadline(); ok { + const arbitraryCleanupMargin = 1 * time.Second + readDeadline = td.Add(-arbitraryCleanupMargin) + } else { + readDeadline = time.Now().Add(5 * time.Second) + } + + var closed sync.WaitGroup + closed.Add(2) + handler := func(dss *dualStackServer, ln Listener) { + // Accept one connection per address. + c, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + + // Workaround for https://go.dev/issue/37795. + // On arm64 macOS (current as of macOS 12.4), + // reading from a socket at the same time as the client + // is closing it occasionally hangs for 60 seconds before + // returning ECONNRESET. Sleep for a bit to give the + // socket time to close before trying to read from it. + if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { + time.Sleep(10 * time.Millisecond) + } + + // The client should close itself, without sending data. + c.SetReadDeadline(readDeadline) + var b [1]byte + if _, err := c.Read(b[:]); err != io.EOF { + t.Errorf("got %v; want %v", err, io.EOF) + } + c.Close() + closed.Done() + } + dss, err := newDualStackServer() + if err != nil { + t.Fatal(err) + } + defer dss.teardown() + if err := dss.buildup(handler); err != nil { + t.Fatal(err) + } + + const fallbackDelay = 100 * time.Millisecond + + var dialing sync.WaitGroup + dialing.Add(2) + origTestHookDialTCP := testHookDialTCP + defer func() { testHookDialTCP = origTestHookDialTCP }() + testHookDialTCP = func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error) { + // Wait until Happy Eyeballs kicks in and both connections are dialing, + // and inhibit cancellation. + // This forces dialParallel to juggle two successful connections. + dialing.Done() + dialing.Wait() + + // Now ignore the provided context (which will be canceled) and use a + // different one to make sure this completes with a valid connection, + // which we hope to be closed below: + sd := &sysDialer{network: net, address: raddr.String()} + return sd.doDialTCP(context.Background(), laddr, raddr) + } + + d := Dialer{ + FallbackDelay: fallbackDelay, + } + sd := &sysDialer{ + Dialer: d, + network: "tcp", + address: "?", + } + + makeAddr := func(ip string) addrList { + addr, err := ResolveTCPAddr("tcp", JoinHostPort(ip, dss.port)) + if err != nil { + t.Fatal(err) + } + return addrList{addr} + } + + // dialParallel returns one connection (and closes the other.) + c, err := sd.dialParallel(context.Background(), makeAddr("127.0.0.1"), makeAddr("::1")) + if err != nil { + t.Fatal(err) + } + c.Close() + + // The server should've seen both connections. + closed.Wait() +} + +func TestDialerPartialDeadline(t *testing.T) { + now := time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC) + var testCases = []struct { + now time.Time + deadline time.Time + addrs int + expectDeadline time.Time + expectErr error + }{ + // Regular division. + {now, now.Add(12 * time.Second), 1, now.Add(12 * time.Second), nil}, + {now, now.Add(12 * time.Second), 2, now.Add(6 * time.Second), nil}, + {now, now.Add(12 * time.Second), 3, now.Add(4 * time.Second), nil}, + // Bump against the 2-second sane minimum. + {now, now.Add(12 * time.Second), 999, now.Add(2 * time.Second), nil}, + // Total available is now below the sane minimum. + {now, now.Add(1900 * time.Millisecond), 999, now.Add(1900 * time.Millisecond), nil}, + // Null deadline. + {now, noDeadline, 1, noDeadline, nil}, + // Step the clock forward and cross the deadline. + {now.Add(-1 * time.Millisecond), now, 1, now, nil}, + {now.Add(0 * time.Millisecond), now, 1, noDeadline, errTimeout}, + {now.Add(1 * time.Millisecond), now, 1, noDeadline, errTimeout}, + } + for i, tt := range testCases { + deadline, err := partialDeadline(tt.now, tt.deadline, tt.addrs) + if err != tt.expectErr { + t.Errorf("#%d: got %v; want %v", i, err, tt.expectErr) + } + if !deadline.Equal(tt.expectDeadline) { + t.Errorf("#%d: got %v; want %v", i, deadline, tt.expectDeadline) + } + } +} + +// isEADDRINUSE reports whether err is syscall.EADDRINUSE. +var isEADDRINUSE = func(err error) bool { return false } + +func TestDialerLocalAddr(t *testing.T) { + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + type test struct { + network, raddr string + laddr Addr + error + } + var tests = []test{ + {"tcp4", "127.0.0.1", nil, nil}, + {"tcp4", "127.0.0.1", &TCPAddr{}, nil}, + {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil}, + {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil}, + {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("::")}, &AddrError{Err: "some error"}}, + {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, nil}, + {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, nil}, + {"tcp4", "127.0.0.1", &TCPAddr{IP: IPv6loopback}, errNoSuitableAddress}, + {"tcp4", "127.0.0.1", &UDPAddr{}, &AddrError{Err: "some error"}}, + {"tcp4", "127.0.0.1", &UnixAddr{}, &AddrError{Err: "some error"}}, + + {"tcp6", "::1", nil, nil}, + {"tcp6", "::1", &TCPAddr{}, nil}, + {"tcp6", "::1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil}, + {"tcp6", "::1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil}, + {"tcp6", "::1", &TCPAddr{IP: ParseIP("::")}, nil}, + {"tcp6", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, errNoSuitableAddress}, + {"tcp6", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, errNoSuitableAddress}, + {"tcp6", "::1", &TCPAddr{IP: IPv6loopback}, nil}, + {"tcp6", "::1", &UDPAddr{}, &AddrError{Err: "some error"}}, + {"tcp6", "::1", &UnixAddr{}, &AddrError{Err: "some error"}}, + + {"tcp", "127.0.0.1", nil, nil}, + {"tcp", "127.0.0.1", &TCPAddr{}, nil}, + {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil}, + {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil}, + {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, nil}, + {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, nil}, + {"tcp", "127.0.0.1", &TCPAddr{IP: IPv6loopback}, errNoSuitableAddress}, + {"tcp", "127.0.0.1", &UDPAddr{}, &AddrError{Err: "some error"}}, + {"tcp", "127.0.0.1", &UnixAddr{}, &AddrError{Err: "some error"}}, + + {"tcp", "::1", nil, nil}, + {"tcp", "::1", &TCPAddr{}, nil}, + {"tcp", "::1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil}, + {"tcp", "::1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil}, + {"tcp", "::1", &TCPAddr{IP: ParseIP("::")}, nil}, + {"tcp", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, errNoSuitableAddress}, + {"tcp", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, errNoSuitableAddress}, + {"tcp", "::1", &TCPAddr{IP: IPv6loopback}, nil}, + {"tcp", "::1", &UDPAddr{}, &AddrError{Err: "some error"}}, + {"tcp", "::1", &UnixAddr{}, &AddrError{Err: "some error"}}, + } + + issue34264Index := -1 + if supportsIPv4map() { + issue34264Index = len(tests) + tests = append(tests, test{ + "tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("::")}, nil, + }) + } else { + tests = append(tests, test{ + "tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("::")}, &AddrError{Err: "some error"}, + }) + } + + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = lookupLocalhost + handler := func(ls *localServer, ln Listener) { + for { + c, err := ln.Accept() + if err != nil { + return + } + c.Close() + } + } + var lss [2]*localServer + for i, network := range []string{"tcp4", "tcp6"} { + lss[i] = newLocalServer(t, network) + defer lss[i].teardown() + if err := lss[i].buildup(handler); err != nil { + t.Fatal(err) + } + } + + for i, tt := range tests { + d := &Dialer{LocalAddr: tt.laddr} + var addr string + ip := ParseIP(tt.raddr) + if ip.To4() != nil { + addr = lss[0].Listener.Addr().String() + } + if ip.To16() != nil && ip.To4() == nil { + addr = lss[1].Listener.Addr().String() + } + c, err := d.Dial(tt.network, addr) + if err == nil && tt.error != nil || err != nil && tt.error == nil { + if i == issue34264Index && runtime.GOOS == "freebsd" && isEADDRINUSE(err) { + // https://golang.org/issue/34264: FreeBSD through at least version 12.2 + // has been observed to fail with EADDRINUSE when dialing from an IPv6 + // local address to an IPv4 remote address. + t.Logf("%s %v->%s: got %v; want %v", tt.network, tt.laddr, tt.raddr, err, tt.error) + t.Logf("(spurious EADDRINUSE ignored on freebsd: see https://golang.org/issue/34264)") + } else { + t.Errorf("%s %v->%s: got %v; want %v", tt.network, tt.laddr, tt.raddr, err, tt.error) + } + } + if err != nil { + if perr := parseDialError(err); perr != nil { + t.Error(perr) + } + continue + } + c.Close() + } +} + +func TestDialerDualStack(t *testing.T) { + testenv.SkipFlaky(t, 13324) + + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + closedPortDelay := dialClosedPort(t) + + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = lookupLocalhost + handler := func(dss *dualStackServer, ln Listener) { + for { + c, err := ln.Accept() + if err != nil { + return + } + c.Close() + } + } + + var timeout = 150*time.Millisecond + closedPortDelay + for _, dualstack := range []bool{false, true} { + dss, err := newDualStackServer() + if err != nil { + t.Fatal(err) + } + defer dss.teardown() + if err := dss.buildup(handler); err != nil { + t.Fatal(err) + } + + d := &Dialer{DualStack: dualstack, Timeout: timeout} + for range dss.lns { + c, err := d.Dial("tcp", JoinHostPort("localhost", dss.port)) + if err != nil { + t.Error(err) + continue + } + switch addr := c.LocalAddr().(*TCPAddr); { + case addr.IP.To4() != nil: + dss.teardownNetwork("tcp4") + case addr.IP.To16() != nil && addr.IP.To4() == nil: + dss.teardownNetwork("tcp6") + } + c.Close() + } + } +} + +func TestDialerKeepAlive(t *testing.T) { + t.Cleanup(func() { + testHookSetKeepAlive = func(KeepAliveConfig) {} + }) + + handler := func(ls *localServer, ln Listener) { + for { + c, err := ln.Accept() + if err != nil { + return + } + c.Close() + } + } + ln := newLocalListener(t, "tcp", &ListenConfig{ + KeepAlive: -1, // prevent calling hook from accepting + }) + ls := (&streamListener{Listener: ln}).newLocalServer() + defer ls.teardown() + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + + tests := []struct { + ka time.Duration + expected time.Duration + }{ + {-1, -1}, + {0, 0}, + {5 * time.Second, 5 * time.Second}, + {30 * time.Second, 30 * time.Second}, + } + + var got time.Duration = -1 + testHookSetKeepAlive = func(cfg KeepAliveConfig) { got = cfg.Idle } + + for _, test := range tests { + got = -1 + d := Dialer{KeepAlive: test.ka} + c, err := d.Dial("tcp", ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + c.Close() + if got != test.expected { + t.Errorf("Dialer.KeepAlive = %v: SetKeepAlive set to %v, want %v", d.KeepAlive, got, test.expected) + } + } +} + +func TestDialCancel(t *testing.T) { + mustHaveExternalNetwork(t) + + blackholeIPPort := JoinHostPort(slowDst4, "1234") + if !supportsIPv4() { + blackholeIPPort = JoinHostPort(slowDst6, "1234") + } + + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + + const cancelTick = 5 // the timer tick we cancel the dial at + const timeoutTick = 100 + + var d Dialer + cancel := make(chan struct{}) + d.Cancel = cancel + errc := make(chan error, 1) + connc := make(chan Conn, 1) + go func() { + if c, err := d.Dial("tcp", blackholeIPPort); err != nil { + errc <- err + } else { + connc <- c + } + }() + ticks := 0 + for { + select { + case <-ticker.C: + ticks++ + if ticks == cancelTick { + close(cancel) + } + if ticks == timeoutTick { + t.Fatal("timeout waiting for dial to fail") + } + case c := <-connc: + c.Close() + t.Fatal("unexpected successful connection") + case err := <-errc: + if perr := parseDialError(err); perr != nil { + t.Error(perr) + } + if ticks < cancelTick { + // Using strings.Contains is ugly but + // may work on plan9 and windows. + ignorable := []string{ + "connection refused", + "unreachable", + "no route to host", + "invalid argument", + } + e := err.Error() + for _, ignore := range ignorable { + if strings.Contains(e, ignore) { + t.Skipf("connection to %v failed fast with %v", blackholeIPPort, err) + } + } + + t.Fatalf("dial error after %d ticks (%d before cancel sent): %v", + ticks, cancelTick-ticks, err) + } + if oe, ok := err.(*OpError); !ok || oe.Err != errCanceled { + t.Fatalf("dial error = %v (%T); want OpError with Err == errCanceled", err, err) + } + return // success. + } + } +} + +func TestCancelAfterDial(t *testing.T) { + if testing.Short() { + t.Skip("avoiding time.Sleep") + } + + ln := newLocalListener(t, "tcp") + + var wg sync.WaitGroup + wg.Add(1) + defer func() { + ln.Close() + wg.Wait() + }() + + // Echo back the first line of each incoming connection. + go func() { + for { + c, err := ln.Accept() + if err != nil { + break + } + rb := bufio.NewReader(c) + line, err := rb.ReadString('\n') + if err != nil { + t.Error(err) + c.Close() + continue + } + if _, err := c.Write([]byte(line)); err != nil { + t.Error(err) + } + c.Close() + } + wg.Done() + }() + + try := func() { + cancel := make(chan struct{}) + d := &Dialer{Cancel: cancel} + c, err := d.Dial("tcp", ln.Addr().String()) + + // Immediately after dialing, request cancellation and sleep. + // Before Issue 15078 was fixed, this would cause subsequent operations + // to fail with an i/o timeout roughly 50% of the time. + close(cancel) + time.Sleep(10 * time.Millisecond) + + if err != nil { + t.Fatal(err) + } + defer c.Close() + + // Send some data to confirm that the connection is still alive. + const message = "echo!\n" + if _, err := c.Write([]byte(message)); err != nil { + t.Fatal(err) + } + + // The server should echo the line, and close the connection. + rb := bufio.NewReader(c) + line, err := rb.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if line != message { + t.Errorf("got %q; want %q", line, message) + } + if _, err := rb.ReadByte(); err != io.EOF { + t.Errorf("got %v; want %v", err, io.EOF) + } + } + + // This bug manifested about 50% of the time, so try it a few times. + for i := 0; i < 10; i++ { + try() + } +} + +func TestDialClosedPortFailFast(t *testing.T) { + if runtime.GOOS != "windows" { + // Reported by go.dev/issues/23366. + t.Skip("skipping windows only test") + } + for _, network := range []string{"tcp", "tcp4", "tcp6"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("skipping: can't listen on %s", network) + } + // Reserve a local port till the end of the + // test by opening a listener and connecting to + // it using Dial. + ln := newLocalListener(t, network) + addr := ln.Addr().String() + conn1, err := Dial(network, addr) + if err != nil { + ln.Close() + t.Fatal(err) + } + defer conn1.Close() + // Now close the listener so the next Dial fails + // keeping conn1 alive so the port is not made + // available. + ln.Close() + + maxElapsed := time.Second + // The host can be heavy-loaded and take + // longer than configured. Retry until + // Dial takes less than maxElapsed or + // the test times out. + for { + startTime := time.Now() + conn2, err := Dial(network, addr) + if err == nil { + conn2.Close() + t.Fatal("error expected") + } + elapsed := time.Since(startTime) + if elapsed < maxElapsed { + break + } + t.Logf("got %v; want < %v", elapsed, maxElapsed) + } + }) + } +} + +// Issue 18806: it should always be possible to net.Dial a +// net.Listener().Addr().String when the listen address was ":n", even +// if the machine has halfway configured IPv6 such that it can bind on +// "::" not connect back to that same address. +func TestDialListenerAddr(t *testing.T) { + if !testableNetwork("tcp4") { + t.Skipf("skipping: can't listen on tcp4") + } + + // The original issue report was for listening on just ":0" on a system that + // supports both tcp4 and tcp6 for external traffic but only tcp4 for loopback + // traffic. However, the port opened by ":0" is externally-accessible, and may + // trigger firewall alerts or otherwise be mistaken for malicious activity + // (see https://go.dev/issue/59497). Moreover, it often does not reproduce + // the scenario in the issue, in which the port *cannot* be dialed as tcp6. + // + // To address both of those problems, we open a tcp4-only localhost port, but + // then dial the address string that the listener would have reported for a + // dual-stack port. + ln, err := Listen("tcp4", "localhost:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + t.Logf("listening on %q", ln.Addr()) + _, port, err := SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + + // If we had opened a dual-stack port without an explicit "localhost" address, + // the Listener would arbitrarily report an empty tcp6 address in its Addr + // string. + // + // The documentation for Dial says ‘if the host is empty or a literal + // unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for TCP and + // UDP, "", "0.0.0.0" or "::" for IP, the local system is assumed.’ + // In #18806, it was decided that that should include the local tcp4 host + // even if the string is in the tcp6 format. + dialAddr := "[::]:" + port + c, err := Dial("tcp4", dialAddr) + if err != nil { + t.Fatalf(`Dial("tcp4", %q): %v`, dialAddr, err) + } + c.Close() + t.Logf(`Dial("tcp4", %q) succeeded`, dialAddr) +} + +func TestDialerControl(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + case "js", "wasip1": + t.Skipf("skipping: fake net does not support Dialer.Control") + } + + t.Run("StreamDial", func(t *testing.T) { + for _, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} { + if !testableNetwork(network) { + continue + } + ln := newLocalListener(t, network) + defer ln.Close() + d := Dialer{Control: controlOnConnSetup} + c, err := d.Dial(network, ln.Addr().String()) + if err != nil { + t.Error(err) + continue + } + c.Close() + } + }) + t.Run("PacketDial", func(t *testing.T) { + for _, network := range []string{"udp", "udp4", "udp6", "unixgram"} { + if !testableNetwork(network) { + continue + } + c1 := newLocalPacketListener(t, network) + if network == "unixgram" { + defer os.Remove(c1.LocalAddr().String()) + } + defer c1.Close() + d := Dialer{Control: controlOnConnSetup} + c2, err := d.Dial(network, c1.LocalAddr().String()) + if err != nil { + t.Error(err) + continue + } + c2.Close() + } + }) +} + +func TestDialerControlContext(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("%s does not have full support of socktest", runtime.GOOS) + case "js", "wasip1": + t.Skipf("skipping: fake net does not support Dialer.ControlContext") + } + t.Run("StreamDial", func(t *testing.T) { + for i, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("skipping: %s not available", network) + } + + ln := newLocalListener(t, network) + defer ln.Close() + var id int + d := Dialer{ControlContext: func(ctx context.Context, network string, address string, c syscall.RawConn) error { + id = ctx.Value("id").(int) + return controlOnConnSetup(network, address, c) + }} + c, err := d.DialContext(context.WithValue(context.Background(), "id", i+1), network, ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + if id != i+1 { + t.Errorf("got id %d, want %d", id, i+1) + } + c.Close() + }) + } + }) +} + +func TestDialContext(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + case "js", "wasip1": + t.Skipf("skipping: fake net does not support Dialer.ControlContext") + } + + t.Run("StreamDial", func(t *testing.T) { + var err error + for i, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} { + if !testableNetwork(network) { + continue + } + ln := newLocalListener(t, network) + defer ln.Close() + var id int + d := Dialer{ControlContext: func(ctx context.Context, network string, address string, c syscall.RawConn) error { + id = ctx.Value("id").(int) + return controlOnConnSetup(network, address, c) + }} + var c Conn + switch network { + case "tcp", "tcp4", "tcp6": + raddr, err := netip.ParseAddrPort(ln.Addr().String()) + if err != nil { + t.Error(err) + continue + } + c, err = d.DialTCP(context.WithValue(context.Background(), "id", i+1), network, (*TCPAddr)(nil).AddrPort(), raddr) + case "unix", "unixpacket": + raddr, err := ResolveUnixAddr(network, ln.Addr().String()) + if err != nil { + t.Error(err) + continue + } + c, err = d.DialUnix(context.WithValue(context.Background(), "id", i+1), network, nil, raddr) + } + if err != nil { + t.Error(err) + continue + } + if id != i+1 { + t.Errorf("%s: got id %d, want %d", network, id, i+1) + } + c.Close() + } + }) + t.Run("PacketDial", func(t *testing.T) { + var err error + for i, network := range []string{"udp", "udp4", "udp6", "unixgram"} { + if !testableNetwork(network) { + continue + } + c1 := newLocalPacketListener(t, network) + if network == "unixgram" { + defer os.Remove(c1.LocalAddr().String()) + } + defer c1.Close() + var id int + d := Dialer{ControlContext: func(ctx context.Context, network string, address string, c syscall.RawConn) error { + id = ctx.Value("id").(int) + return controlOnConnSetup(network, address, c) + }} + var c2 Conn + switch network { + case "udp", "udp4", "udp6": + raddr, err := netip.ParseAddrPort(c1.LocalAddr().String()) + if err != nil { + t.Error(err) + continue + } + c2, err = d.DialUDP(context.WithValue(context.Background(), "id", i+1), network, (*UDPAddr)(nil).AddrPort(), raddr) + case "unixgram": + raddr, err := ResolveUnixAddr(network, c1.LocalAddr().String()) + if err != nil { + t.Error(err) + continue + } + c2, err = d.DialUnix(context.WithValue(context.Background(), "id", i+1), network, nil, raddr) + } + if err != nil { + t.Error(err) + continue + } + if id != i+1 { + t.Errorf("%s: got id %d, want %d", network, id, i+1) + } + c2.Close() + } + }) +} + +// mustHaveExternalNetwork is like testenv.MustHaveExternalNetwork +// except on non-Linux, non-mobile builders it permits the test to +// run in -short mode. +func mustHaveExternalNetwork(t *testing.T) { + t.Helper() + definitelyHasLongtestBuilder := runtime.GOOS == "linux" + mobile := runtime.GOOS == "android" || runtime.GOOS == "ios" + fake := runtime.GOOS == "js" || runtime.GOOS == "wasip1" + if testenv.Builder() != "" && !definitelyHasLongtestBuilder && !mobile && !fake { + // On a non-Linux, non-mobile builder (e.g., freebsd-amd64-13_0). + // + // Don't skip testing because otherwise the test may never run on + // any builder if this port doesn't also have a -longtest builder. + return + } + testenv.MustHaveExternalNetwork(t) +} + +type contextWithNonZeroDeadline struct { + context.Context +} + +func (contextWithNonZeroDeadline) Deadline() (time.Time, bool) { + // Return non-zero time.Time value with false indicating that no deadline is set. + return time.Unix(0, 0), false +} + +func TestDialWithNonZeroDeadline(t *testing.T) { + ln := newLocalListener(t, "tcp") + defer ln.Close() + _, port, err := SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + + ctx := contextWithNonZeroDeadline{Context: context.Background()} + var dialer Dialer + c, err := dialer.DialContext(ctx, "tcp", JoinHostPort("", port)) + if err != nil { + t.Fatal(err) + } + c.Close() +} diff --git a/go/src/net/dial_unix_test.go b/go/src/net/dial_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d0df0b71eaeea5fb6b624897140c25f20bbc4884 --- /dev/null +++ b/go/src/net/dial_unix_test.go @@ -0,0 +1,113 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "context" + "errors" + "syscall" + "testing" + "time" +) + +func init() { + isEADDRINUSE = func(err error) bool { + return errors.Is(err, syscall.EADDRINUSE) + } +} + +// Issue 16523 +func TestDialContextCancelRace(t *testing.T) { + oldConnectFunc := connectFunc + oldGetsockoptIntFunc := getsockoptIntFunc + oldTestHookCanceledDial := testHookCanceledDial + defer func() { + connectFunc = oldConnectFunc + getsockoptIntFunc = oldGetsockoptIntFunc + testHookCanceledDial = oldTestHookCanceledDial + }() + + ln := newLocalListener(t, "tcp") + listenerDone := make(chan struct{}) + go func() { + defer close(listenerDone) + c, err := ln.Accept() + if err == nil { + c.Close() + } + }() + defer func() { <-listenerDone }() + defer ln.Close() + + sawCancel := make(chan bool, 1) + testHookCanceledDial = func() { + sawCancel <- true + } + + ctx, cancelCtx := context.WithCancel(context.Background()) + + connectFunc = func(fd int, addr syscall.Sockaddr) error { + err := oldConnectFunc(fd, addr) + t.Logf("connect(%d, addr) = %v", fd, err) + if err == nil { + // On some operating systems, localhost + // connects _sometimes_ succeed immediately. + // Prevent that, so we exercise the code path + // we're interested in testing. This seems + // harmless. It makes FreeBSD 10.10 work when + // run with many iterations. It failed about + // half the time previously. + return syscall.EINPROGRESS + } + return err + } + + getsockoptIntFunc = func(fd, level, opt int) (val int, err error) { + val, err = oldGetsockoptIntFunc(fd, level, opt) + t.Logf("getsockoptIntFunc(%d, %d, %d) = (%v, %v)", fd, level, opt, val, err) + if level == syscall.SOL_SOCKET && opt == syscall.SO_ERROR && err == nil && val == 0 { + t.Logf("canceling context") + + // Cancel the context at just the moment which + // caused the race in issue 16523. + cancelCtx() + + // And wait for the "interrupter" goroutine to + // cancel the dial by messing with its write + // timeout before returning. + select { + case <-sawCancel: + t.Logf("saw cancel") + case <-time.After(5 * time.Second): + t.Errorf("didn't see cancel after 5 seconds") + } + } + return + } + + var d Dialer + c, err := d.DialContext(ctx, "tcp", ln.Addr().String()) + if err == nil { + c.Close() + t.Fatal("unexpected successful dial; want context canceled error") + } + + select { + case <-ctx.Done(): + case <-time.After(5 * time.Second): + t.Fatal("expected context to be canceled") + } + + oe, ok := err.(*OpError) + if !ok || oe.Op != "dial" { + t.Fatalf("Dial error = %#v; want dial *OpError", err) + } + + if oe.Err != errCanceled { + t.Errorf("DialContext = (%v, %v); want OpError with error %v", c, err, errCanceled) + } +} diff --git a/go/src/net/dnsclient.go b/go/src/net/dnsclient.go new file mode 100644 index 0000000000000000000000000000000000000000..eb509d175fc1a0a53a0c68162802d688bb25b5ab --- /dev/null +++ b/go/src/net/dnsclient.go @@ -0,0 +1,239 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "cmp" + "internal/bytealg" + "internal/strconv" + "slices" + _ "unsafe" // for go:linkname + + "golang.org/x/net/dns/dnsmessage" +) + +// provided by runtime +// +//go:linkname runtime_rand runtime.rand +func runtime_rand() uint64 + +func randInt() int { + return int(uint(runtime_rand()) >> 1) // clear sign bit +} + +func randIntn(n int) int { + return randInt() % n +} + +// 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 error) { + ip := ParseIP(addr) + if ip == nil { + return "", &DNSError{Err: "unrecognized address", Name: addr} + } + if ip.To4() != nil { + return strconv.Itoa(int(ip[15])) + "." + strconv.Itoa(int(ip[14])) + "." + strconv.Itoa(int(ip[13])) + "." + strconv.Itoa(int(ip[12])) + ".in-addr.arpa.", nil + } + // Must be IPv6 + buf := make([]byte, 0, len(ip)*4+len("ip6.arpa.")) + // Add it, in reverse, to the buffer + for i := len(ip) - 1; i >= 0; i-- { + v := ip[i] + buf = append(buf, hexDigit[v&0xF], + '.', + hexDigit[v>>4], + '.') + } + // Append "ip6.arpa." and return (buf already has the final .) + buf = append(buf, "ip6.arpa."...) + return string(buf), nil +} + +func equalASCIIName(x, y dnsmessage.Name) bool { + if x.Length != y.Length { + return false + } + for i := 0; i < int(x.Length); i++ { + a := x.Data[i] + b := y.Data[i] + if 'A' <= a && a <= 'Z' { + a += 0x20 + } + if 'A' <= b && b <= 'Z' { + b += 0x20 + } + if a != b { + return false + } + } + return true +} + +// isDomainName checks if a string is a presentation-format domain name +// (currently restricted to hostname-compatible "preferred name" LDH labels and +// SRV-like "underscore labels"; see golang.org/issue/12421). +// +// isDomainName should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/sagernet/sing +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname isDomainName +func isDomainName(s string) bool { + // The root domain name is valid. See golang.org/issue/45715. + if s == "." { + return true + } + + // See RFC 1035, RFC 3696. + // Presentation format has dots before every label except the first, and the + // terminal empty label is optional here because we assume fully-qualified + // (absolute) input. We must therefore reserve space for the first and last + // labels' length octets in wire format, where they are necessary and the + // maximum total length is 255. + // So our _effective_ maximum is 253, but 254 is not rejected if the last + // character is a dot. + l := len(s) + if l == 0 || l > 254 || l == 254 && s[l-1] != '.' { + return false + } + + last := byte('.') + nonNumeric := false // true once we've seen a letter or hyphen + partlen := 0 + for i := 0; i < len(s); i++ { + c := s[i] + switch { + default: + return false + case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_': + nonNumeric = true + partlen++ + case '0' <= c && c <= '9': + // fine + partlen++ + case c == '-': + // Byte before dash cannot be dot. + if last == '.' { + return false + } + partlen++ + nonNumeric = true + case c == '.': + // Byte before dot cannot be dot, dash. + if last == '.' || last == '-' { + return false + } + if partlen > 63 || partlen == 0 { + return false + } + partlen = 0 + } + last = c + } + if last == '-' || partlen > 63 { + return false + } + + return nonNumeric +} + +// absDomainName returns an absolute domain name which ends with a +// trailing dot to match pure Go reverse resolver and all other lookup +// routines. +// See golang.org/issue/12189. +// But we don't want to add dots for local names from /etc/hosts. +// It's hard to tell so we settle on the heuristic that names without dots +// (like "localhost" or "myhost") do not get trailing dots, but any other +// names do. +func absDomainName(s string) string { + if bytealg.IndexByteString(s, '.') != -1 && s[len(s)-1] != '.' { + s += "." + } + return s +} + +// An SRV represents a single DNS SRV record. +type SRV struct { + Target string + Port uint16 + Priority uint16 + Weight uint16 +} + +// byPriorityWeight sorts SRV records by ascending priority and weight. +type byPriorityWeight []*SRV + +// shuffleByWeight shuffles SRV records by weight using the algorithm +// described in RFC 2782. +func (addrs byPriorityWeight) shuffleByWeight() { + sum := 0 + for _, addr := range addrs { + sum += int(addr.Weight) + } + for sum > 0 && len(addrs) > 1 { + s := 0 + n := randIntn(sum) + for i := range addrs { + s += int(addrs[i].Weight) + if s > n { + if i > 0 { + addrs[0], addrs[i] = addrs[i], addrs[0] + } + break + } + } + sum -= int(addrs[0].Weight) + addrs = addrs[1:] + } +} + +// sort reorders SRV records as specified in RFC 2782. +func (addrs byPriorityWeight) sort() { + slices.SortFunc(addrs, func(a, b *SRV) int { + if r := cmp.Compare(a.Priority, b.Priority); r != 0 { + return r + } + return cmp.Compare(a.Weight, b.Weight) + }) + i := 0 + for j := 1; j < len(addrs); j++ { + if addrs[i].Priority != addrs[j].Priority { + addrs[i:j].shuffleByWeight() + i = j + } + } + addrs[i:].shuffleByWeight() +} + +// An MX represents a single DNS MX record. +type MX struct { + Host string + Pref uint16 +} + +// byPref sorts MX records by preference +type byPref []*MX + +// sort reorders MX records as specified in RFC 5321. +func (s byPref) sort() { + for i := range s { + j := randIntn(i + 1) + s[i], s[j] = s[j], s[i] + } + slices.SortFunc(s, func(a, b *MX) int { + return cmp.Compare(a.Pref, b.Pref) + }) +} + +// An NS represents a single DNS NS record. +type NS struct { + Host string +} diff --git a/go/src/net/dnsclient_test.go b/go/src/net/dnsclient_test.go new file mode 100644 index 0000000000000000000000000000000000000000..24cd69e13be25d932760cdd4e195c46625dd004f --- /dev/null +++ b/go/src/net/dnsclient_test.go @@ -0,0 +1,66 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "testing" +) + +func checkDistribution(t *testing.T, data []*SRV, margin float64) { + sum := 0 + for _, srv := range data { + sum += int(srv.Weight) + } + + results := make(map[string]int) + + count := 10000 + for j := 0; j < count; j++ { + d := make([]*SRV, len(data)) + copy(d, data) + byPriorityWeight(d).shuffleByWeight() + key := d[0].Target + results[key] = results[key] + 1 + } + + actual := results[data[0].Target] + expected := float64(count) * float64(data[0].Weight) / float64(sum) + diff := float64(actual) - expected + t.Logf("actual: %v diff: %v e: %v m: %v", actual, diff, expected, margin) + if diff < 0 { + diff = -diff + } + if diff > (expected * margin) { + t.Errorf("missed target weight: expected %v, %v", expected, actual) + } +} + +func testUniformity(t *testing.T, size int, margin float64) { + data := make([]*SRV, size) + for i := 0; i < size; i++ { + data[i] = &SRV{Target: string('a' + rune(i)), Weight: 1} + } + checkDistribution(t, data, margin) +} + +func TestDNSSRVUniformity(t *testing.T) { + testUniformity(t, 2, 0.05) + testUniformity(t, 3, 0.10) + testUniformity(t, 10, 0.20) + testWeighting(t, 0.05) +} + +func testWeighting(t *testing.T, margin float64) { + data := []*SRV{ + {Target: "a", Weight: 60}, + {Target: "b", Weight: 30}, + {Target: "c", Weight: 10}, + } + checkDistribution(t, data, margin) +} + +func TestWeighting(t *testing.T) { + testWeighting(t, 0.05) +} diff --git a/go/src/net/dnsclient_unix.go b/go/src/net/dnsclient_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..40f76062944f465fc05e7c2d690477565a261e5c --- /dev/null +++ b/go/src/net/dnsclient_unix.go @@ -0,0 +1,892 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// DNS client: see RFC 1035. +// Has to be linked into package net for Dial. + +// TODO(rsc): +// Could potentially handle many outstanding lookups faster. +// Random UDP source port (net.Dial should do that for us). +// Random request IDs. + +package net + +import ( + "context" + "errors" + "internal/bytealg" + "internal/godebug" + "internal/strconv" + "internal/stringslite" + "io" + "os" + "runtime" + "sync" + "sync/atomic" + "time" + + "golang.org/x/net/dns/dnsmessage" +) + +const ( + // to be used as a useTCP parameter to exchange + useTCPOnly = true + useUDPOrTCP = false + + // Maximum DNS packet size. + // Value taken from https://dnsflagday.net/2020/. + maxDNSPacketSize = 1232 +) + +var ( + errLameReferral = errors.New("lame referral") + errCannotUnmarshalDNSMessage = errors.New("cannot unmarshal DNS message") + errCannotMarshalDNSMessage = errors.New("cannot marshal DNS message") + errServerMisbehaving = errors.New("server misbehaving") + errInvalidDNSResponse = errors.New("invalid DNS response") + errNoAnswerFromDNSServer = errors.New("no answer from DNS server") + + // errServerTemporarilyMisbehaving is like errServerMisbehaving, except + // that when it gets translated to a DNSError, the IsTemporary field + // gets set to true. + errServerTemporarilyMisbehaving = &temporaryError{"server misbehaving"} +) + +// netedns0 controls whether we send an EDNS0 additional header. +var netedns0 = godebug.New("netedns0") + +func newRequest(q dnsmessage.Question, ad bool) (id uint16, udpReq, tcpReq []byte, err error) { + id = uint16(randInt()) + b := dnsmessage.NewBuilder(make([]byte, 2, 514), dnsmessage.Header{ID: id, RecursionDesired: true, AuthenticData: ad}) + if err := b.StartQuestions(); err != nil { + return 0, nil, nil, err + } + if err := b.Question(q); err != nil { + return 0, nil, nil, err + } + + if netedns0.Value() == "0" { + netedns0.IncNonDefault() + } else { + // Accept packets up to maxDNSPacketSize. RFC 6891. + if err := b.StartAdditionals(); err != nil { + return 0, nil, nil, err + } + var rh dnsmessage.ResourceHeader + if err := rh.SetEDNS0(maxDNSPacketSize, dnsmessage.RCodeSuccess, false); err != nil { + return 0, nil, nil, err + } + if err := b.OPTResource(rh, dnsmessage.OPTResource{}); err != nil { + return 0, nil, nil, err + } + } + + tcpReq, err = b.Finish() + if err != nil { + return 0, nil, nil, err + } + udpReq = tcpReq[2:] + l := len(tcpReq) - 2 + tcpReq[0] = byte(l >> 8) + tcpReq[1] = byte(l) + return id, udpReq, tcpReq, nil +} + +func checkResponse(reqID uint16, reqQues dnsmessage.Question, respHdr dnsmessage.Header, respQues dnsmessage.Question) bool { + if !respHdr.Response { + return false + } + if reqID != respHdr.ID { + return false + } + if reqQues.Type != respQues.Type || reqQues.Class != respQues.Class || !equalASCIIName(reqQues.Name, respQues.Name) { + return false + } + return true +} + +func dnsPacketRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error) { + if _, err := c.Write(b); err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, err + } + + b = make([]byte, maxDNSPacketSize) + for { + n, err := c.Read(b) + if err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, err + } + var p dnsmessage.Parser + // Ignore invalid responses as they may be malicious + // forgery attempts. Instead continue waiting until + // timeout. See golang.org/issue/13281. + h, err := p.Start(b[:n]) + if err != nil { + continue + } + q, err := p.Question() + if err != nil || !checkResponse(id, query, h, q) { + continue + } + return p, h, nil + } +} + +func dnsStreamRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error) { + if _, err := c.Write(b); err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, err + } + + b = make([]byte, 1280) // 1280 is a reasonable initial size for IP over Ethernet, see RFC 4035 + if _, err := io.ReadFull(c, b[:2]); err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, err + } + l := int(b[0])<<8 | int(b[1]) + if l > len(b) { + b = make([]byte, l) + } + n, err := io.ReadFull(c, b[:l]) + if err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, err + } + var p dnsmessage.Parser + h, err := p.Start(b[:n]) + if err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, errCannotUnmarshalDNSMessage + } + q, err := p.Question() + if err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, errCannotUnmarshalDNSMessage + } + if !checkResponse(id, query, h, q) { + return dnsmessage.Parser{}, dnsmessage.Header{}, errInvalidDNSResponse + } + return p, h, nil +} + +// exchange sends a query on the connection and hopes for a response. +func (r *Resolver) exchange(ctx context.Context, server string, q dnsmessage.Question, timeout time.Duration, useTCP, ad bool) (dnsmessage.Parser, dnsmessage.Header, error) { + q.Class = dnsmessage.ClassINET + id, udpReq, tcpReq, err := newRequest(q, ad) + if err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, errCannotMarshalDNSMessage + } + var networks []string + if useTCP { + networks = []string{"tcp"} + } else { + networks = []string{"udp", "tcp"} + } + for _, network := range networks { + ctx, cancel := context.WithDeadline(ctx, time.Now().Add(timeout)) + defer cancel() + + c, err := r.dial(ctx, network, server) + if err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, err + } + if d, ok := ctx.Deadline(); ok && !d.IsZero() { + c.SetDeadline(d) + } + var p dnsmessage.Parser + var h dnsmessage.Header + if _, ok := c.(PacketConn); ok { + p, h, err = dnsPacketRoundTrip(c, id, q, udpReq) + } else { + p, h, err = dnsStreamRoundTrip(c, id, q, tcpReq) + } + c.Close() + if err != nil { + return dnsmessage.Parser{}, dnsmessage.Header{}, mapErr(err) + } + if err := p.SkipQuestion(); err != dnsmessage.ErrSectionDone { + return dnsmessage.Parser{}, dnsmessage.Header{}, errInvalidDNSResponse + } + // RFC 5966 indicates that when a client receives a UDP response with + // the TC flag set, it should take the TC flag as an indication that it + // should retry over TCP instead. + // The case when the TC flag is set in a TCP response is not well specified, + // so this implements the glibc resolver behavior, returning the existing + // dns response instead of returning a "errNoAnswerFromDNSServer" error. + // See go.dev/issue/64896 + if h.Truncated && network == "udp" { + continue + } + return p, h, nil + } + return dnsmessage.Parser{}, dnsmessage.Header{}, errNoAnswerFromDNSServer +} + +// checkHeader performs basic sanity checks on the header. +func checkHeader(p *dnsmessage.Parser, h dnsmessage.Header) error { + rcode, hasAdd := extractExtendedRCode(*p, h) + + if rcode == dnsmessage.RCodeNameError { + return errNoSuchHost + } + + _, err := p.AnswerHeader() + if err != nil && err != dnsmessage.ErrSectionDone { + return errCannotUnmarshalDNSMessage + } + + // libresolv continues to the next server when it receives + // an invalid referral response. See golang.org/issue/15434. + if rcode == dnsmessage.RCodeSuccess && !h.Authoritative && !h.RecursionAvailable && err == dnsmessage.ErrSectionDone && !hasAdd { + return errLameReferral + } + + if rcode != dnsmessage.RCodeSuccess && rcode != dnsmessage.RCodeNameError { + // 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 or + // having temporary trouble. + if rcode == dnsmessage.RCodeServerFailure { + return errServerTemporarilyMisbehaving + } + return errServerMisbehaving + } + + return nil +} + +func skipToAnswer(p *dnsmessage.Parser, qtype dnsmessage.Type) error { + for { + h, err := p.AnswerHeader() + if err == dnsmessage.ErrSectionDone { + return errNoSuchHost + } + if err != nil { + return errCannotUnmarshalDNSMessage + } + if h.Type == qtype { + return nil + } + if err := p.SkipAnswer(); err != nil { + return errCannotUnmarshalDNSMessage + } + } +} + +// extractExtendedRCode extracts the extended RCode from the OPT resource (EDNS(0)) +// If an OPT record is not found, the RCode from the hdr is returned. +// Another return value indicates whether an additional resource was found. +func extractExtendedRCode(p dnsmessage.Parser, hdr dnsmessage.Header) (dnsmessage.RCode, bool) { + p.SkipAllAnswers() + p.SkipAllAuthorities() + hasAdd := false + for { + ahdr, err := p.AdditionalHeader() + if err != nil { + return hdr.RCode, hasAdd + } + hasAdd = true + if ahdr.Type == dnsmessage.TypeOPT { + return ahdr.ExtendedRCode(hdr.RCode), hasAdd + } + if err := p.SkipAdditional(); err != nil { + return hdr.RCode, hasAdd + } + } +} + +// Do a lookup for a single name, which must be rooted +// (otherwise answer will not find the answers). +func (r *Resolver) tryOneName(ctx context.Context, cfg *dnsConfig, name string, qtype dnsmessage.Type) (dnsmessage.Parser, string, error) { + var lastErr error + serverOffset := cfg.serverOffset() + sLen := uint32(len(cfg.servers)) + + n, err := dnsmessage.NewName(name) + if err != nil { + return dnsmessage.Parser{}, "", &DNSError{Err: errCannotMarshalDNSMessage.Error(), Name: name} + } + q := dnsmessage.Question{ + Name: n, + Type: qtype, + Class: dnsmessage.ClassINET, + } + + for i := 0; i < cfg.attempts; i++ { + for j := uint32(0); j < sLen; j++ { + server := cfg.servers[(serverOffset+j)%sLen] + + p, h, err := r.exchange(ctx, server, q, cfg.timeout, cfg.useTCP, cfg.trustAD) + if err != nil { + dnsErr := newDNSError(err, name, server) + // Set IsTemporary for socket-level errors. Note that this flag + // may also be used to indicate a SERVFAIL response. + if _, ok := err.(*OpError); ok { + dnsErr.IsTemporary = true + } + lastErr = dnsErr + continue + } + + if err := checkHeader(&p, h); err != nil { + if err == errNoSuchHost { + // The name does not exist, so trying + // another server won't help. + return p, server, newDNSError(errNoSuchHost, name, server) + } + lastErr = newDNSError(err, name, server) + continue + } + + if err := skipToAnswer(&p, qtype); err != nil { + if err == errNoSuchHost { + // The name does not exist, so trying + // another server won't help. + return p, server, newDNSError(errNoSuchHost, name, server) + } + lastErr = newDNSError(err, name, server) + continue + } + + return p, server, nil + } + } + return dnsmessage.Parser{}, "", lastErr +} + +// A resolverConfig represents a DNS stub resolver configuration. +type resolverConfig struct { + initOnce sync.Once // guards init of resolverConfig + + // ch is used as a semaphore that only allows one lookup at a + // time to recheck resolv.conf. + ch chan struct{} // guards lastChecked and modTime + lastChecked time.Time // last time resolv.conf was checked + + dnsConfig atomic.Pointer[dnsConfig] // parsed resolv.conf structure used in lookups +} + +var resolvConf resolverConfig + +func getSystemDNSConfig() *dnsConfig { + resolvConf.tryUpdate("/etc/resolv.conf") + return resolvConf.dnsConfig.Load() +} + +// init initializes conf and is only called via conf.initOnce. +func (conf *resolverConfig) init() { + // Set dnsConfig and lastChecked so we don't parse + // resolv.conf twice the first time. + conf.dnsConfig.Store(dnsReadConfig("/etc/resolv.conf")) + conf.lastChecked = time.Now() + + // Prepare ch so that only one update of resolverConfig may + // run at once. + conf.ch = make(chan struct{}, 1) +} + +// tryUpdate tries to update conf with the named resolv.conf file. +// The name variable only exists for testing. It is otherwise always +// "/etc/resolv.conf". +func (conf *resolverConfig) tryUpdate(name string) { + conf.initOnce.Do(conf.init) + + if conf.dnsConfig.Load().noReload { + return + } + + // Ensure only one update at a time checks resolv.conf. + if !conf.tryAcquireSema() { + return + } + defer conf.releaseSema() + + now := time.Now() + if conf.lastChecked.After(now.Add(-5 * time.Second)) { + return + } + conf.lastChecked = now + + switch runtime.GOOS { + case "windows": + // There's no file on disk, so don't bother checking + // and failing. + // + // The Windows implementation of dnsReadConfig (called + // below) ignores the name. + default: + var mtime time.Time + if fi, err := os.Stat(name); err == nil { + mtime = fi.ModTime() + } + if mtime.Equal(conf.dnsConfig.Load().mtime) { + return + } + } + + dnsConf := dnsReadConfig(name) + conf.dnsConfig.Store(dnsConf) +} + +func (conf *resolverConfig) tryAcquireSema() bool { + select { + case conf.ch <- struct{}{}: + return true + default: + return false + } +} + +func (conf *resolverConfig) releaseSema() { + <-conf.ch +} + +func (r *Resolver) lookup(ctx context.Context, name string, qtype dnsmessage.Type, conf *dnsConfig) (dnsmessage.Parser, string, error) { + if !isDomainName(name) { + // We used to use "invalid domain name" as the error, + // but that is a detail of the specific lookup mechanism. + // Other lookups might allow broader name syntax + // (for example Multicast DNS allows UTF-8; see RFC 6762). + // For consistency with libc resolvers, report no such host. + return dnsmessage.Parser{}, "", newDNSError(errNoSuchHost, name, "") + } + + if conf == nil { + conf = getSystemDNSConfig() + } + + var ( + p dnsmessage.Parser + server string + err error + ) + for _, fqdn := range conf.nameList(name) { + p, server, err = r.tryOneName(ctx, conf, fqdn, qtype) + if err == nil { + break + } + if nerr, ok := err.(Error); ok && nerr.Temporary() && r.strictErrors() { + // If we hit a temporary error with StrictErrors enabled, + // stop immediately instead of trying more names. + break + } + } + if err == nil { + return p, server, nil + } + if err, ok := err.(*DNSError); ok { + // Show original name passed to lookup, not suffixed one. + // In general we might have tried many suffixes; showing + // just one is misleading. See also golang.org/issue/6324. + err.Name = name + } + return dnsmessage.Parser{}, "", err +} + +// avoidDNS reports whether this is a hostname for which we should not +// use DNS. Currently this includes only .onion, per RFC 7686. See +// golang.org/issue/13705. Does not cover .local names (RFC 6762), +// see golang.org/issue/16739. +func avoidDNS(name string) bool { + if name == "" { + return true + } + name = stringslite.TrimSuffix(name, ".") + return stringsHasSuffixFold(name, ".onion") +} + +// nameList returns a list of names for sequential DNS queries. +func (conf *dnsConfig) nameList(name string) []string { + // Check name length (see isDomainName). + l := len(name) + rooted := l > 0 && name[l-1] == '.' + if l > 254 || l == 254 && !rooted { + return nil + } + + // If name is rooted (trailing dot), try only that name. + if rooted { + if avoidDNS(name) { + return nil + } + return []string{name} + } + + hasNdots := bytealg.CountString(name, '.') >= conf.ndots + name += "." + l++ + + // Build list of search choices. + names := make([]string, 0, 1+len(conf.search)) + // If name has enough dots, try unsuffixed first. + if hasNdots && !avoidDNS(name) { + names = append(names, name) + } + // Try suffixes that are not too long (see isDomainName). + for _, suffix := range conf.search { + fqdn := name + suffix + if !avoidDNS(fqdn) && len(fqdn) <= 254 { + names = append(names, fqdn) + } + } + // Try unsuffixed, if not tried first above. + if !hasNdots && !avoidDNS(name) { + names = append(names, name) + } + return names +} + +// hostLookupOrder specifies the order of LookupHost lookup strategies. +// It is basically a simplified representation of nsswitch.conf. +// "files" means /etc/hosts. +type hostLookupOrder int + +const ( + // hostLookupCgo means defer to cgo. + hostLookupCgo hostLookupOrder = iota + hostLookupFilesDNS // files first + hostLookupDNSFiles // dns first + hostLookupFiles // only files + hostLookupDNS // only DNS +) + +var lookupOrderName = map[hostLookupOrder]string{ + hostLookupCgo: "cgo", + hostLookupFilesDNS: "files,dns", + hostLookupDNSFiles: "dns,files", + hostLookupFiles: "files", + hostLookupDNS: "dns", +} + +func (o hostLookupOrder) String() string { + if s, ok := lookupOrderName[o]; ok { + return s + } + return "hostLookupOrder=" + strconv.Itoa(int(o)) + "??" +} + +func (r *Resolver) goLookupHostOrder(ctx context.Context, name string, order hostLookupOrder, conf *dnsConfig) (addrs []string, err error) { + if order == hostLookupFilesDNS || order == hostLookupFiles { + // Use entries from /etc/hosts if they match. + addrs, _ = lookupStaticHost(name) + if len(addrs) > 0 { + return + } + + if order == hostLookupFiles { + return nil, newDNSError(errNoSuchHost, name, "") + } + } + ips, _, err := r.goLookupIPCNAMEOrder(ctx, "ip", name, order, conf) + if err != nil { + return + } + addrs = make([]string, 0, len(ips)) + for _, ip := range ips { + addrs = append(addrs, ip.String()) + } + return +} + +// lookup entries from /etc/hosts +func goLookupIPFiles(name string) (addrs []IPAddr, canonical string) { + addr, canonical := lookupStaticHost(name) + for _, haddr := range addr { + haddr, zone := splitHostZone(haddr) + if ip := ParseIP(haddr); ip != nil { + addr := IPAddr{IP: ip, Zone: zone} + addrs = append(addrs, addr) + } + } + sortByRFC6724(addrs) + return addrs, canonical +} + +// goLookupIP is the native Go implementation of LookupIP. +// The libc versions are in cgo_*.go. +func (r *Resolver) goLookupIP(ctx context.Context, network, host string, order hostLookupOrder, conf *dnsConfig) (addrs []IPAddr, err error) { + addrs, _, err = r.goLookupIPCNAMEOrder(ctx, network, host, order, conf) + return +} + +func (r *Resolver) goLookupIPCNAMEOrder(ctx context.Context, network, name string, order hostLookupOrder, conf *dnsConfig) (addrs []IPAddr, cname dnsmessage.Name, err error) { + if order == hostLookupFilesDNS || order == hostLookupFiles { + var canonical string + addrs, canonical = goLookupIPFiles(name) + + if len(addrs) > 0 { + var err error + cname, err = dnsmessage.NewName(canonical) + if err != nil { + return nil, dnsmessage.Name{}, err + } + return addrs, cname, nil + } + + if order == hostLookupFiles { + return nil, dnsmessage.Name{}, newDNSError(errNoSuchHost, name, "") + } + } + + if !isDomainName(name) { + // See comment in func lookup above about use of errNoSuchHost. + return nil, dnsmessage.Name{}, newDNSError(errNoSuchHost, name, "") + } + type result struct { + p dnsmessage.Parser + server string + error + } + + if conf == nil { + conf = getSystemDNSConfig() + } + + lane := make(chan result, 1) + qtypes := []dnsmessage.Type{dnsmessage.TypeA, dnsmessage.TypeAAAA} + if network == "CNAME" { + qtypes = append(qtypes, dnsmessage.TypeCNAME) + } + switch ipVersion(network) { + case '4': + qtypes = []dnsmessage.Type{dnsmessage.TypeA} + case '6': + qtypes = []dnsmessage.Type{dnsmessage.TypeAAAA} + } + var queryFn func(fqdn string, qtype dnsmessage.Type) + var responseFn func(fqdn string, qtype dnsmessage.Type) result + if conf.singleRequest { + queryFn = func(fqdn string, qtype dnsmessage.Type) {} + responseFn = func(fqdn string, qtype dnsmessage.Type) result { + dnsWaitGroup.Add(1) + defer dnsWaitGroup.Done() + p, server, err := r.tryOneName(ctx, conf, fqdn, qtype) + return result{p, server, err} + } + } else { + queryFn = func(fqdn string, qtype dnsmessage.Type) { + dnsWaitGroup.Add(1) + go func(qtype dnsmessage.Type) { + p, server, err := r.tryOneName(ctx, conf, fqdn, qtype) + lane <- result{p, server, err} + dnsWaitGroup.Done() + }(qtype) + } + responseFn = func(fqdn string, qtype dnsmessage.Type) result { + return <-lane + } + } + var lastErr error + for _, fqdn := range conf.nameList(name) { + for _, qtype := range qtypes { + queryFn(fqdn, qtype) + } + hitStrictError := false + for _, qtype := range qtypes { + result := responseFn(fqdn, qtype) + if result.error != nil { + if nerr, ok := result.error.(Error); ok && nerr.Temporary() && r.strictErrors() { + // This error will abort the nameList loop. + hitStrictError = true + lastErr = result.error + } else if lastErr == nil || fqdn == name+"." { + // Prefer error for original name. + lastErr = result.error + } + continue + } + + // Presotto says it's okay to assume that servers listed in + // /etc/resolv.conf are recursive resolvers. + // + // We asked for recursion, so it should have included all the + // answers we need in this one packet. + // + // Further, RFC 1034 section 4.3.1 says that "the recursive + // response to a query will be... The answer to the query, + // possibly preface by one or more CNAME RRs that specify + // aliases encountered on the way to an answer." + // + // Therefore, we should be able to assume that we can ignore + // CNAMEs and that the A and AAAA records we requested are + // for the canonical name. + + loop: + for { + h, err := result.p.AnswerHeader() + if err != nil && err != dnsmessage.ErrSectionDone { + lastErr = &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: name, + Server: result.server, + } + } + if err != nil { + break + } + switch h.Type { + case dnsmessage.TypeA: + a, err := result.p.AResource() + if err != nil { + lastErr = &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: name, + Server: result.server, + } + break loop + } + addrs = append(addrs, IPAddr{IP: IP(a.A[:])}) + if cname.Length == 0 && h.Name.Length != 0 { + cname = h.Name + } + + case dnsmessage.TypeAAAA: + aaaa, err := result.p.AAAAResource() + if err != nil { + lastErr = &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: name, + Server: result.server, + } + break loop + } + addrs = append(addrs, IPAddr{IP: IP(aaaa.AAAA[:])}) + if cname.Length == 0 && h.Name.Length != 0 { + cname = h.Name + } + + case dnsmessage.TypeCNAME: + c, err := result.p.CNAMEResource() + if err != nil { + lastErr = &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: name, + Server: result.server, + } + break loop + } + if cname.Length == 0 && c.CNAME.Length > 0 { + cname = c.CNAME + } + + default: + if err := result.p.SkipAnswer(); err != nil { + lastErr = &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: name, + Server: result.server, + } + break loop + } + continue + } + } + } + if hitStrictError { + // If either family hit an error with StrictErrors enabled, + // discard all addresses. This ensures that network flakiness + // cannot turn a dualstack hostname IPv4/IPv6-only. + addrs = nil + break + } + if len(addrs) > 0 || network == "CNAME" && cname.Length > 0 { + break + } + } + if lastErr, ok := lastErr.(*DNSError); ok { + // Show original name passed to lookup, not suffixed one. + // In general we might have tried many suffixes; showing + // just one is misleading. See also golang.org/issue/6324. + lastErr.Name = name + } + sortByRFC6724(addrs) + if len(addrs) == 0 && !(network == "CNAME" && cname.Length > 0) { + if order == hostLookupDNSFiles { + var canonical string + addrs, canonical = goLookupIPFiles(name) + if len(addrs) > 0 { + var err error + cname, err = dnsmessage.NewName(canonical) + if err != nil { + return nil, dnsmessage.Name{}, err + } + return addrs, cname, nil + } + } + if lastErr != nil { + return nil, dnsmessage.Name{}, lastErr + } + } + return addrs, cname, nil +} + +// goLookupCNAME is the native Go (non-cgo) implementation of LookupCNAME. +func (r *Resolver) goLookupCNAME(ctx context.Context, host string, order hostLookupOrder, conf *dnsConfig) (string, error) { + _, cname, err := r.goLookupIPCNAMEOrder(ctx, "CNAME", host, order, conf) + return cname.String(), err +} + +// goLookupPTR is the native Go implementation of LookupAddr. +func (r *Resolver) goLookupPTR(ctx context.Context, addr string, order hostLookupOrder, conf *dnsConfig) ([]string, error) { + if order == hostLookupFiles || order == hostLookupFilesDNS { + names := lookupStaticAddr(addr) + if len(names) > 0 { + return names, nil + } + + if order == hostLookupFiles { + return nil, newDNSError(errNoSuchHost, addr, "") + } + } + + arpa, err := reverseaddr(addr) + if err != nil { + return nil, err + } + p, server, err := r.lookup(ctx, arpa, dnsmessage.TypePTR, conf) + if err != nil { + if dnsErr, ok := errors.AsType[*DNSError](err); ok && dnsErr.IsNotFound { + if order == hostLookupDNSFiles { + names := lookupStaticAddr(addr) + if len(names) > 0 { + return names, nil + } + } + } + return nil, err + } + var ptrs []string + for { + h, err := p.AnswerHeader() + if err == dnsmessage.ErrSectionDone { + break + } + if err != nil { + return nil, &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: addr, + Server: server, + } + } + if h.Type != dnsmessage.TypePTR { + err := p.SkipAnswer() + if err != nil { + return nil, &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: addr, + Server: server, + } + } + continue + } + ptr, err := p.PTRResource() + if err != nil { + return nil, &DNSError{ + Err: errCannotUnmarshalDNSMessage.Error(), + Name: addr, + Server: server, + } + } + ptrs = append(ptrs, ptr.PTR.String()) + + } + + return ptrs, nil +} diff --git a/go/src/net/dnsclient_unix_test.go b/go/src/net/dnsclient_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..fc1d40f18b6f9a75c9e5daf506991bd8bf6340b9 --- /dev/null +++ b/go/src/net/dnsclient_unix_test.go @@ -0,0 +1,2857 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "context" + "errors" + "fmt" + "maps" + "os" + "path" + "path/filepath" + "reflect" + "runtime" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "golang.org/x/net/dns/dnsmessage" +) + +// Test address from 192.0.2.0/24 block, reserved by RFC 5737 for documentation. +var TestAddr = [4]byte{0xc0, 0x00, 0x02, 0x01} + +// Test address from 2001:db8::/32 block, reserved by RFC 3849 for documentation. +var TestAddr6 = [16]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} + +func mustNewName(name string) dnsmessage.Name { + nn, err := dnsmessage.NewName(name) + if err != nil { + panic(fmt.Sprint("creating name: ", err)) + } + return nn +} + +func mustQuestion(name string, qtype dnsmessage.Type, class dnsmessage.Class) dnsmessage.Question { + return dnsmessage.Question{ + Name: mustNewName(name), + Type: qtype, + Class: class, + } +} + +var dnsTransportFallbackTests = []struct { + server string + question dnsmessage.Question + timeout int + rcode dnsmessage.RCode +}{ + // Querying "com." with qtype=255 usually makes an answer + // which requires more than 512 bytes. + {"8.8.8.8:53", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), 2, dnsmessage.RCodeSuccess}, + {"8.8.4.4:53", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), 4, dnsmessage.RCodeSuccess}, +} + +func TestDNSTransportFallback(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + } + if n == "udp" { + r.Header.Truncated = true + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + for _, tt := range dnsTransportFallbackTests { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + _, h, err := r.exchange(ctx, tt.server, tt.question, time.Second, useUDPOrTCP, false) + if err != nil { + t.Error(err) + continue + } + if h.RCode != tt.rcode { + t.Errorf("got %v from %v; want %v", h.RCode, tt.server, tt.rcode) + continue + } + } +} + +func TestDNSTransportNoFallbackOnTCP(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + Truncated: true, + }, + Questions: q.Questions, + } + if n == "tcp" { + r.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + } + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + for _, tt := range dnsTransportFallbackTests { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + p, h, err := r.exchange(ctx, tt.server, tt.question, time.Second, useUDPOrTCP, false) + if err != nil { + t.Error(err) + continue + } + if h.RCode != tt.rcode { + t.Errorf("got %v from %v; want %v", h.RCode, tt.server, tt.rcode) + continue + } + a, err := p.AllAnswers() + if err != nil { + t.Errorf("unexpected error %v getting all answers from %v", err, tt.server) + continue + } + if len(a) != 1 { + t.Errorf("got %d answers from %v; want 1", len(a), tt.server) + continue + } + } +} + +// See RFC 6761 for further information about the reserved, pseudo +// domain names. +var specialDomainNameTests = []struct { + question dnsmessage.Question + rcode dnsmessage.RCode +}{ + // Name resolution APIs and libraries should not recognize the + // followings as special. + {mustQuestion("1.0.168.192.in-addr.arpa.", dnsmessage.TypePTR, dnsmessage.ClassINET), dnsmessage.RCodeNameError}, + {mustQuestion("test.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeNameError}, + {mustQuestion("example.com.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeSuccess}, + + // Name resolution APIs and libraries should recognize the + // followings as special and should not send any queries. + // Though, we test those names here for verifying negative + // answers at DNS query-response interaction level. + {mustQuestion("localhost.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeNameError}, + {mustQuestion("invalid.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeNameError}, +} + +func TestSpecialDomainName(t *testing.T) { + fake := fakeDNSServer{rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + + switch q.Questions[0].Name.String() { + case "example.com.": + r.Header.RCode = dnsmessage.RCodeSuccess + default: + r.Header.RCode = dnsmessage.RCodeNameError + } + + return r, nil + }} + r := Resolver{PreferGo: true, Dial: fake.DialContext} + server := "8.8.8.8:53" + for _, tt := range specialDomainNameTests { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + _, h, err := r.exchange(ctx, server, tt.question, 3*time.Second, useUDPOrTCP, false) + if err != nil { + t.Error(err) + continue + } + if h.RCode != tt.rcode { + t.Errorf("got %v from %v; want %v", h.RCode, server, tt.rcode) + continue + } + } +} + +// Issue 13705: don't try to resolve onion addresses, etc +func TestAvoidDNSName(t *testing.T) { + tests := []struct { + name string + avoid bool + }{ + {"foo.com", false}, + {"foo.com.", false}, + + {"foo.onion.", true}, + {"foo.onion", true}, + {"foo.ONION", true}, + {"foo.ONION.", true}, + + // But do resolve *.local address; Issue 16739 + {"foo.local.", false}, + {"foo.local", false}, + {"foo.LOCAL", false}, + {"foo.LOCAL.", false}, + + {"", true}, // will be rejected earlier too + + // Without stuff before onion/local, they're fine to + // use DNS. With a search path, + // "onion.vegetables.com" can use DNS. Without a + // search path (or with a trailing dot), the queries + // are just kinda useless, but don't reveal anything + // private. + {"local", false}, + {"onion", false}, + {"local.", false}, + {"onion.", false}, + } + for _, tt := range tests { + got := avoidDNS(tt.name) + if got != tt.avoid { + t.Errorf("avoidDNS(%q) = %v; want %v", tt.name, got, tt.avoid) + } + } +} + +func TestNameListAvoidDNS(t *testing.T) { + c := &dnsConfig{search: []string{"go.dev.", "onion."}} + got := c.nameList("www") + if !slices.Equal(got, []string{"www.", "www.go.dev."}) { + t.Fatalf(`nameList("www") = %v, want "www.", "www.go.dev."`, got) + } + + got = c.nameList("www.onion") + if !slices.Equal(got, []string{"www.onion.go.dev."}) { + t.Fatalf(`nameList("www.onion") = %v, want "www.onion.go.dev."`, got) + } +} + +var fakeDNSServerSuccessful = fakeDNSServer{rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + if len(q.Questions) == 1 && q.Questions[0].Type == dnsmessage.TypeA { + r.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + } + } + return r, nil +}} + +// Issue 13705: don't try to resolve onion addresses, etc +func TestLookupTorOnion(t *testing.T) { + defer dnsWaitGroup.Wait() + r := Resolver{PreferGo: true, Dial: fakeDNSServerSuccessful.DialContext} + addrs, err := r.LookupIPAddr(context.Background(), "foo.onion.") + if err != nil { + t.Fatalf("lookup = %v; want nil", err) + } + if len(addrs) > 0 { + t.Errorf("unexpected addresses: %v", addrs) + } +} + +type resolvConfTest struct { + dir string + path string + *resolverConfig +} + +func newResolvConfTest() (*resolvConfTest, error) { + dir, err := os.MkdirTemp("", "go-resolvconftest") + if err != nil { + return nil, err + } + conf := &resolvConfTest{ + dir: dir, + path: path.Join(dir, "resolv.conf"), + resolverConfig: &resolvConf, + } + conf.initOnce.Do(conf.init) + return conf, nil +} + +func (conf *resolvConfTest) write(lines []string) error { + f, err := os.OpenFile(conf.path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) + if err != nil { + return err + } + if _, err := f.WriteString(strings.Join(lines, "\n")); err != nil { + f.Close() + return err + } + f.Close() + return nil +} + +func (conf *resolvConfTest) writeAndUpdate(lines []string) error { + return conf.writeAndUpdateWithLastCheckedTime(lines, time.Now().Add(time.Hour)) +} + +func (conf *resolvConfTest) writeAndUpdateWithLastCheckedTime(lines []string, lastChecked time.Time) error { + if err := conf.write(lines); err != nil { + return err + } + return conf.forceUpdate(conf.path, lastChecked) +} + +func (conf *resolvConfTest) forceUpdate(name string, lastChecked time.Time) error { + dnsConf := dnsReadConfig(name) + if !conf.forceUpdateConf(dnsConf, lastChecked) { + return fmt.Errorf("tryAcquireSema for %s failed", name) + } + return nil +} + +func (conf *resolvConfTest) forceUpdateConf(c *dnsConfig, lastChecked time.Time) bool { + conf.dnsConfig.Store(c) + for i := 0; i < 5; i++ { + if conf.tryAcquireSema() { + conf.lastChecked = lastChecked + conf.releaseSema() + return true + } + } + return false +} + +func (conf *resolvConfTest) servers() []string { + return conf.dnsConfig.Load().servers +} + +func (conf *resolvConfTest) teardown() error { + err := conf.forceUpdate("/etc/resolv.conf", time.Time{}) + os.RemoveAll(conf.dir) + return err +} + +var updateResolvConfTests = []struct { + name string // query name + lines []string // resolver configuration lines + servers []string // expected name servers +}{ + { + name: "golang.org", + lines: []string{"nameserver 8.8.8.8"}, + servers: []string{"8.8.8.8:53"}, + }, + { + name: "", + lines: nil, // an empty resolv.conf should use defaultNS as name servers + servers: defaultNS, + }, + { + name: "www.example.com", + lines: []string{"nameserver 8.8.4.4"}, + servers: []string{"8.8.4.4:53"}, + }, +} + +func TestUpdateResolvConf(t *testing.T) { + defer dnsWaitGroup.Wait() + + r := Resolver{PreferGo: true, Dial: fakeDNSServerSuccessful.DialContext} + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + for i, tt := range updateResolvConfTests { + if err := conf.writeAndUpdate(tt.lines); err != nil { + t.Error(err) + continue + } + if tt.name != "" { + var wg sync.WaitGroup + const N = 10 + wg.Add(N) + for j := 0; j < N; j++ { + go func(name string) { + defer wg.Done() + ips, err := r.LookupIPAddr(context.Background(), name) + if err != nil { + t.Error(err) + return + } + if len(ips) == 0 { + t.Errorf("no records for %s", name) + return + } + }(tt.name) + } + wg.Wait() + } + servers := conf.servers() + if !slices.Equal(servers, tt.servers) { + t.Errorf("#%d: got %v; want %v", i, servers, tt.servers) + continue + } + } +} + +var goLookupIPWithResolverConfigTests = []struct { + name string + lines []string // resolver configuration lines + error + a, aaaa bool // whether response contains A, AAAA-record +}{ + // no records, transport timeout + { + "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j", + []string{ + "options timeout:1 attempts:1", + "nameserver 255.255.255.255", // please forgive us for abuse of limited broadcast address + }, + &DNSError{Name: "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j", Server: "255.255.255.255:53", IsTimeout: true}, + false, false, + }, + + // no records, non-existent domain + { + "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j", + []string{ + "options timeout:3 attempts:1", + "nameserver 8.8.8.8", + }, + &DNSError{Name: "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j", Server: "8.8.8.8:53", IsTimeout: false}, + false, false, + }, + + // a few A records, no AAAA records + { + "ipv4.google.com.", + []string{ + "nameserver 8.8.8.8", + "nameserver 2001:4860:4860::8888", + }, + nil, + true, false, + }, + { + "ipv4.google.com", + []string{ + "domain golang.org", + "nameserver 2001:4860:4860::8888", + "nameserver 8.8.8.8", + }, + nil, + true, false, + }, + { + "ipv4.google.com", + []string{ + "search x.golang.org y.golang.org", + "nameserver 2001:4860:4860::8888", + "nameserver 8.8.8.8", + }, + nil, + true, false, + }, + + // no A records, a few AAAA records + { + "ipv6.google.com.", + []string{ + "nameserver 2001:4860:4860::8888", + "nameserver 8.8.8.8", + }, + nil, + false, true, + }, + { + "ipv6.google.com", + []string{ + "domain golang.org", + "nameserver 8.8.8.8", + "nameserver 2001:4860:4860::8888", + }, + nil, + false, true, + }, + { + "ipv6.google.com", + []string{ + "search x.golang.org y.golang.org", + "nameserver 8.8.8.8", + "nameserver 2001:4860:4860::8888", + }, + nil, + false, true, + }, + + // both A and AAAA records + { + "hostname.as112.net", // see RFC 7534 + []string{ + "domain golang.org", + "nameserver 2001:4860:4860::8888", + "nameserver 8.8.8.8", + }, + nil, + true, true, + }, + { + "hostname.as112.net", // see RFC 7534 + []string{ + "search x.golang.org y.golang.org", + "nameserver 2001:4860:4860::8888", + "nameserver 8.8.8.8", + }, + nil, + true, true, + }, +} + +func TestGoLookupIPWithResolverConfig(t *testing.T) { + defer dnsWaitGroup.Wait() + fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + switch s { + case "[2001:4860:4860::8888]:53", "8.8.8.8:53": + break + default: + time.Sleep(10 * time.Millisecond) + return dnsmessage.Message{}, os.ErrDeadlineExceeded + } + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + for _, question := range q.Questions { + switch question.Type { + case dnsmessage.TypeA: + switch question.Name.String() { + case "hostname.as112.net.": + break + case "ipv4.google.com.": + r.Answers = append(r.Answers, dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }) + default: + + } + case dnsmessage.TypeAAAA: + switch question.Name.String() { + case "hostname.as112.net.": + break + case "ipv6.google.com.": + r.Answers = append(r.Answers, dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeAAAA, + Class: dnsmessage.ClassINET, + Length: 16, + }, + Body: &dnsmessage.AAAAResource{ + AAAA: TestAddr6, + }, + }) + } + } + } + return r, nil + }} + r := Resolver{PreferGo: true, Dial: fake.DialContext} + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + for _, tt := range goLookupIPWithResolverConfigTests { + if err := conf.writeAndUpdate(tt.lines); err != nil { + t.Error(err) + continue + } + addrs, err := r.LookupIPAddr(context.Background(), tt.name) + if err != nil { + if err, ok := err.(*DNSError); !ok || tt.error != nil && (err.Name != tt.error.(*DNSError).Name || err.Server != tt.error.(*DNSError).Server || err.IsTimeout != tt.error.(*DNSError).IsTimeout) { + t.Errorf("got %v; want %v", err, tt.error) + } + continue + } + if len(addrs) == 0 { + t.Errorf("no records for %s", tt.name) + } + if !tt.a && !tt.aaaa && len(addrs) > 0 { + t.Errorf("unexpected %v for %s", addrs, tt.name) + } + for _, addr := range addrs { + if !tt.a && addr.IP.To4() != nil { + t.Errorf("got %v; must not be IPv4 address", addr) + } + if !tt.aaaa && addr.IP.To16() != nil && addr.IP.To4() == nil { + t.Errorf("got %v; must not be IPv6 address", addr) + } + } + } +} + +// Test that goLookupIPOrder falls back to the host file when no DNS servers are available. +func TestGoLookupIPOrderFallbackToFile(t *testing.T) { + defer dnsWaitGroup.Wait() + + fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, tm time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + return r, nil + }} + r := Resolver{PreferGo: true, Dial: fake.DialContext} + + // Add a config that simulates no dns servers being available. + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + if err := conf.writeAndUpdate([]string{}); err != nil { + t.Fatal(err) + } + // Redirect host file lookups. + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + hostsFilePath = "testdata/hosts" + + for _, order := range []hostLookupOrder{hostLookupFilesDNS, hostLookupDNSFiles} { + name := fmt.Sprintf("order %v", order) + // First ensure that we get an error when contacting a non-existent host. + _, _, err := r.goLookupIPCNAMEOrder(context.Background(), "ip", "notarealhost", order, nil) + if err == nil { + t.Errorf("%s: expected error while looking up name not in hosts file", name) + continue + } + + // Now check that we get an address when the name appears in the hosts file. + addrs, _, err := r.goLookupIPCNAMEOrder(context.Background(), "ip", "thor", order, nil) // entry is in "testdata/hosts" + if err != nil { + t.Errorf("%s: expected to successfully lookup host entry", name) + continue + } + if len(addrs) != 1 { + t.Errorf("%s: expected exactly one result, but got %v", name, addrs) + continue + } + if got, want := addrs[0].String(), "127.1.1.1"; got != want { + t.Errorf("%s: address doesn't match expectation. got %v, want %v", name, got, want) + } + } +} + +// Issue 12712. +// When using search domains, return the error encountered +// querying the original name instead of an error encountered +// querying a generated name. +func TestErrorForOriginalNameWhenSearching(t *testing.T) { + defer dnsWaitGroup.Wait() + + const fqdn = "doesnotexist.domain" + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + if err := conf.writeAndUpdate([]string{"search servfail"}); err != nil { + t.Fatal(err) + } + + fake := fakeDNSServer{rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + + switch q.Questions[0].Name.String() { + case fqdn + ".servfail.": + r.Header.RCode = dnsmessage.RCodeServerFailure + default: + r.Header.RCode = dnsmessage.RCodeNameError + } + + return r, nil + }} + + cases := []struct { + strictErrors bool + wantErr *DNSError + }{ + {true, &DNSError{Name: fqdn, Err: "server misbehaving", IsTemporary: true}}, + {false, &DNSError{Name: fqdn, Err: errNoSuchHost.Error(), IsNotFound: true}}, + } + for _, tt := range cases { + r := Resolver{PreferGo: true, StrictErrors: tt.strictErrors, Dial: fake.DialContext} + _, err = r.LookupIPAddr(context.Background(), fqdn) + if err == nil { + t.Fatal("expected an error") + } + + want := tt.wantErr + if err, ok := err.(*DNSError); !ok || err.Name != want.Name || err.Err != want.Err || err.IsTemporary != want.IsTemporary { + t.Errorf("got %v; want %v", err, want) + } + } +} + +// Issue 15434. If a name server gives a lame referral, continue to the next. +func TestIgnoreLameReferrals(t *testing.T) { + defer dnsWaitGroup.Wait() + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + if err := conf.writeAndUpdate([]string{"nameserver 192.0.2.1", // the one that will give a lame referral + "nameserver 192.0.2.2"}); err != nil { + t.Fatal(err) + } + + fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + t.Log(s, q) + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + + if s == "192.0.2.2:53" { + r.Header.RecursionAvailable = true + if q.Questions[0].Type == dnsmessage.TypeA { + r.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + } + } + } else if s == "192.0.2.1:53" { + if q.Questions[0].Type == dnsmessage.TypeA && strings.HasPrefix(q.Questions[0].Name.String(), "empty.com.") { + var edns0Hdr dnsmessage.ResourceHeader + edns0Hdr.SetEDNS0(maxDNSPacketSize, dnsmessage.RCodeSuccess, false) + + r.Additionals = []dnsmessage.Resource{ + { + Header: edns0Hdr, + Body: &dnsmessage.OPTResource{}, + }, + } + } + } + + return r, nil + }} + r := Resolver{PreferGo: true, Dial: fake.DialContext} + + addrs, err := r.LookupIP(context.Background(), "ip4", "www.golang.org") + if err != nil { + t.Fatal(err) + } + + if got := len(addrs); got != 1 { + t.Fatalf("got %d addresses, want 1", got) + } + + if got, want := addrs[0].String(), "192.0.2.1"; got != want { + t.Fatalf("got address %v, want %v", got, want) + } + + _, err = r.LookupIP(context.Background(), "ip4", "empty.com") + de, ok := err.(*DNSError) + if !ok { + t.Fatalf("err = %#v; wanted a *net.DNSError", err) + } + if de.Err != errNoSuchHost.Error() { + t.Fatalf("Err = %#v; wanted %q", de.Err, errNoSuchHost.Error()) + } +} + +func BenchmarkGoLookupIP(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + ctx := context.Background() + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + goResolver.LookupIPAddr(ctx, "www.example.com") + } +} + +func BenchmarkGoLookupIPNoSuchHost(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + ctx := context.Background() + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + goResolver.LookupIPAddr(ctx, "some.nonexistent") + } +} + +func BenchmarkGoLookupIPWithBrokenNameServer(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + + conf, err := newResolvConfTest() + if err != nil { + b.Fatal(err) + } + defer conf.teardown() + + lines := []string{ + "nameserver 203.0.113.254", // use TEST-NET-3 block, see RFC 5737 + "nameserver 8.8.8.8", + } + if err := conf.writeAndUpdate(lines); err != nil { + b.Fatal(err) + } + ctx := context.Background() + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + goResolver.LookupIPAddr(ctx, "www.example.com") + } +} + +type fakeDNSServer struct { + rh func(n, s string, q dnsmessage.Message, t time.Time) (dnsmessage.Message, error) + alwaysTCP bool +} + +func (server *fakeDNSServer) DialContext(_ context.Context, n, s string) (Conn, error) { + if server.alwaysTCP || n == "tcp" || n == "tcp4" || n == "tcp6" { + return &fakeDNSConn{tcp: true, server: server, n: n, s: s}, nil + } + return &fakeDNSPacketConn{fakeDNSConn: fakeDNSConn{tcp: false, server: server, n: n, s: s}}, nil +} + +type fakeDNSConn struct { + Conn + tcp bool + server *fakeDNSServer + n string + s string + q dnsmessage.Message + t time.Time + buf []byte +} + +func (f *fakeDNSConn) Close() error { + return nil +} + +func (f *fakeDNSConn) Read(b []byte) (int, error) { + if len(f.buf) > 0 { + n := copy(b, f.buf) + f.buf = f.buf[n:] + return n, nil + } + + resp, err := f.server.rh(f.n, f.s, f.q, f.t) + if err != nil { + return 0, err + } + + bb := make([]byte, 2, 514) + bb, err = resp.AppendPack(bb) + if err != nil { + return 0, fmt.Errorf("cannot marshal DNS message: %v", err) + } + + if f.tcp { + l := len(bb) - 2 + bb[0] = byte(l >> 8) + bb[1] = byte(l) + f.buf = bb + return f.Read(b) + } + + bb = bb[2:] + if len(b) < len(bb) { + return 0, errors.New("read would fragment DNS message") + } + + copy(b, bb) + return len(bb), nil +} + +func (f *fakeDNSConn) Write(b []byte) (int, error) { + if f.tcp && len(b) >= 2 { + b = b[2:] + } + if f.q.Unpack(b) != nil { + return 0, fmt.Errorf("cannot unmarshal DNS message fake %s (%d)", f.n, len(b)) + } + return len(b), nil +} + +func (f *fakeDNSConn) SetDeadline(t time.Time) error { + f.t = t + return nil +} + +type fakeDNSPacketConn struct { + PacketConn + fakeDNSConn +} + +func (f *fakeDNSPacketConn) SetDeadline(t time.Time) error { + return f.fakeDNSConn.SetDeadline(t) +} + +func (f *fakeDNSPacketConn) Close() error { + return f.fakeDNSConn.Close() +} + +// UDP round-tripper algorithm should ignore invalid DNS responses (issue 13281). +func TestIgnoreDNSForgeries(t *testing.T) { + c, s := Pipe() + go func() { + b := make([]byte, maxDNSPacketSize) + n, err := s.Read(b) + if err != nil { + t.Error(err) + return + } + + var msg dnsmessage.Message + if msg.Unpack(b[:n]) != nil { + t.Error("invalid DNS query:", err) + return + } + + s.Write([]byte("garbage DNS response packet")) + + msg.Header.Response = true + msg.Header.ID++ // make invalid ID + + if b, err = msg.Pack(); err != nil { + t.Error("failed to pack DNS response:", err) + return + } + s.Write(b) + + msg.Header.ID-- // restore original ID + msg.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: mustNewName("www.example.com."), + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + } + + b, err = msg.Pack() + if err != nil { + t.Error("failed to pack DNS response:", err) + return + } + s.Write(b) + }() + + msg := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: 42, + }, + Questions: []dnsmessage.Question{ + { + Name: mustNewName("www.example.com."), + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + }, + }, + } + + b, err := msg.Pack() + if err != nil { + t.Fatal("Pack failed:", err) + } + + p, _, err := dnsPacketRoundTrip(c, 42, msg.Questions[0], b) + if err != nil { + t.Fatalf("dnsPacketRoundTrip failed: %v", err) + } + + p.SkipAllQuestions() + as, err := p.AllAnswers() + if err != nil { + t.Fatal("AllAnswers failed:", err) + } + if got := as[0].Body.(*dnsmessage.AResource).A; got != TestAddr { + t.Errorf("got address %v, want %v", got, TestAddr) + } +} + +// Issue 16865. If a name server times out, continue to the next. +func TestRetryTimeout(t *testing.T) { + defer dnsWaitGroup.Wait() + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + testConf := []string{ + "nameserver 192.0.2.1", // the one that will timeout + "nameserver 192.0.2.2", + } + if err := conf.writeAndUpdate(testConf); err != nil { + t.Fatal(err) + } + + var deadline0 time.Time + + fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) { + t.Log(s, q, deadline) + + if deadline.IsZero() { + t.Error("zero deadline") + } + + if s == "192.0.2.1:53" { + deadline0 = deadline + time.Sleep(10 * time.Millisecond) + return dnsmessage.Message{}, os.ErrDeadlineExceeded + } + + if deadline.Equal(deadline0) { + t.Error("deadline didn't change") + } + + return mockTXTResponse(q), nil + }} + r := &Resolver{PreferGo: true, Dial: fake.DialContext} + + _, err = r.LookupTXT(context.Background(), "www.golang.org") + if err != nil { + t.Fatal(err) + } + + if deadline0.IsZero() { + t.Error("deadline0 still zero", deadline0) + } +} + +func TestRotate(t *testing.T) { + // without rotation, always uses the first server + testRotate(t, false, []string{"192.0.2.1", "192.0.2.2"}, []string{"192.0.2.1:53", "192.0.2.1:53", "192.0.2.1:53"}) + + // with rotation, rotates through back to first + testRotate(t, true, []string{"192.0.2.1", "192.0.2.2"}, []string{"192.0.2.1:53", "192.0.2.2:53", "192.0.2.1:53"}) +} + +func testRotate(t *testing.T, rotate bool, nameservers, wantServers []string) { + defer dnsWaitGroup.Wait() + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + var confLines []string + for _, ns := range nameservers { + confLines = append(confLines, "nameserver "+ns) + } + if rotate { + confLines = append(confLines, "options rotate") + } + + if err := conf.writeAndUpdate(confLines); err != nil { + t.Fatal(err) + } + + var usedServers []string + fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) { + usedServers = append(usedServers, s) + return mockTXTResponse(q), nil + }} + r := Resolver{PreferGo: true, Dial: fake.DialContext} + + // len(nameservers) + 1 to allow rotation to get back to start + for i := 0; i < len(nameservers)+1; i++ { + if _, err := r.LookupTXT(context.Background(), "www.golang.org"); err != nil { + t.Fatal(err) + } + } + + if !slices.Equal(usedServers, wantServers) { + t.Errorf("rotate=%t got used servers:\n%v\nwant:\n%v", rotate, usedServers, wantServers) + } +} + +func mockTXTResponse(q dnsmessage.Message) dnsmessage.Message { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + RecursionAvailable: true, + }, + Questions: q.Questions, + Answers: []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeTXT, + Class: dnsmessage.ClassINET, + }, + Body: &dnsmessage.TXTResource{ + TXT: []string{"ok"}, + }, + }, + }, + } + + return r +} + +// Issue 17448. With StrictErrors enabled, temporary errors should make +// LookupIP fail rather than return a partial result. +func TestStrictErrorsLookupIP(t *testing.T) { + defer dnsWaitGroup.Wait() + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + confData := []string{ + "nameserver 192.0.2.53", + "search x.golang.org y.golang.org", + } + if err := conf.writeAndUpdate(confData); err != nil { + t.Fatal(err) + } + + const name = "test-issue19592" + const server = "192.0.2.53:53" + const searchX = "test-issue19592.x.golang.org." + const searchY = "test-issue19592.y.golang.org." + const ip4 = "192.0.2.1" + const ip6 = "2001:db8::1" + + type resolveWhichEnum int + const ( + resolveOK resolveWhichEnum = iota + resolveOpError + resolveServfail + resolveTimeout + ) + + makeTempError := func(err string) error { + return &DNSError{ + Err: err, + Name: name, + Server: server, + IsTemporary: true, + } + } + makeTimeout := func() error { + return &DNSError{ + Err: os.ErrDeadlineExceeded.Error(), + Name: name, + Server: server, + IsTimeout: true, + IsTemporary: true, + } + } + makeNxDomain := func() error { + return &DNSError{ + Err: errNoSuchHost.Error(), + Name: name, + Server: server, + IsNotFound: true, + } + } + + cases := []struct { + desc string + resolveWhich func(quest dnsmessage.Question) resolveWhichEnum + wantStrictErr error + wantLaxErr error + wantIPs []string + }{ + { + desc: "No errors", + resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum { + return resolveOK + }, + wantIPs: []string{ip4, ip6}, + }, + { + desc: "searchX error fails in strict mode", + resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum { + if quest.Name.String() == searchX { + return resolveTimeout + } + return resolveOK + }, + wantStrictErr: makeTimeout(), + wantIPs: []string{ip4, ip6}, + }, + { + desc: "searchX IPv4-only timeout fails in strict mode", + resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum { + if quest.Name.String() == searchX && quest.Type == dnsmessage.TypeA { + return resolveTimeout + } + return resolveOK + }, + wantStrictErr: makeTimeout(), + wantIPs: []string{ip4, ip6}, + }, + { + desc: "searchX IPv6-only servfail fails in strict mode", + resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum { + if quest.Name.String() == searchX && quest.Type == dnsmessage.TypeAAAA { + return resolveServfail + } + return resolveOK + }, + wantStrictErr: makeTempError("server misbehaving"), + wantIPs: []string{ip4, ip6}, + }, + { + desc: "searchY error always fails", + resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum { + if quest.Name.String() == searchY { + return resolveTimeout + } + return resolveOK + }, + wantStrictErr: makeTimeout(), + wantLaxErr: makeNxDomain(), // This one reaches the "test." FQDN. + }, + { + desc: "searchY IPv4-only socket error fails in strict mode", + resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum { + if quest.Name.String() == searchY && quest.Type == dnsmessage.TypeA { + return resolveOpError + } + return resolveOK + }, + wantStrictErr: makeTempError("write: socket on fire"), + wantIPs: []string{ip6}, + }, + { + desc: "searchY IPv6-only timeout fails in strict mode", + resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum { + if quest.Name.String() == searchY && quest.Type == dnsmessage.TypeAAAA { + return resolveTimeout + } + return resolveOK + }, + wantStrictErr: makeTimeout(), + wantIPs: []string{ip4}, + }, + } + + for i, tt := range cases { + fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) { + t.Log(s, q) + + switch tt.resolveWhich(q.Questions[0]) { + case resolveOK: + // Handle below. + case resolveOpError: + return dnsmessage.Message{}, &OpError{Op: "write", Err: fmt.Errorf("socket on fire")} + case resolveServfail: + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + RCode: dnsmessage.RCodeServerFailure, + }, + Questions: q.Questions, + }, nil + case resolveTimeout: + return dnsmessage.Message{}, os.ErrDeadlineExceeded + default: + t.Fatal("Impossible resolveWhich") + } + + switch q.Questions[0].Name.String() { + case searchX, name + ".": + // Return NXDOMAIN to utilize the search list. + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + RCode: dnsmessage.RCodeNameError, + }, + Questions: q.Questions, + }, nil + case searchY: + // Return records below. + default: + return dnsmessage.Message{}, fmt.Errorf("Unexpected Name: %v", q.Questions[0].Name) + } + + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + switch q.Questions[0].Type { + case dnsmessage.TypeA: + r.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + } + case dnsmessage.TypeAAAA: + r.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeAAAA, + Class: dnsmessage.ClassINET, + Length: 16, + }, + Body: &dnsmessage.AAAAResource{ + AAAA: TestAddr6, + }, + }, + } + default: + return dnsmessage.Message{}, fmt.Errorf("Unexpected Type: %v", q.Questions[0].Type) + } + return r, nil + }} + + for _, strict := range []bool{true, false} { + r := Resolver{PreferGo: true, StrictErrors: strict, Dial: fake.DialContext} + ips, err := r.LookupIPAddr(context.Background(), name) + + var wantErr error + if strict { + wantErr = tt.wantStrictErr + } else { + wantErr = tt.wantLaxErr + } + if !reflect.DeepEqual(err, wantErr) { + t.Errorf("#%d (%s) strict=%v: got err %#v; want %#v", i, tt.desc, strict, err, wantErr) + } + + gotIPs := map[string]struct{}{} + for _, ip := range ips { + gotIPs[ip.String()] = struct{}{} + } + wantIPs := map[string]struct{}{} + if wantErr == nil { + for _, ip := range tt.wantIPs { + wantIPs[ip] = struct{}{} + } + } + if !maps.Equal(gotIPs, wantIPs) { + t.Errorf("#%d (%s) strict=%v: got ips %v; want %v", i, tt.desc, strict, gotIPs, wantIPs) + } + } + } +} + +// Issue 17448. With StrictErrors enabled, temporary errors should make +// LookupTXT stop walking the search list. +func TestStrictErrorsLookupTXT(t *testing.T) { + defer dnsWaitGroup.Wait() + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + confData := []string{ + "nameserver 192.0.2.53", + "search x.golang.org y.golang.org", + } + if err := conf.writeAndUpdate(confData); err != nil { + t.Fatal(err) + } + + const name = "test" + const server = "192.0.2.53:53" + const searchX = "test.x.golang.org." + const searchY = "test.y.golang.org." + const txt = "Hello World" + + fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) { + t.Log(s, q) + + switch q.Questions[0].Name.String() { + case searchX: + return dnsmessage.Message{}, os.ErrDeadlineExceeded + case searchY: + return mockTXTResponse(q), nil + default: + return dnsmessage.Message{}, fmt.Errorf("Unexpected Name: %v", q.Questions[0].Name) + } + }} + + for _, strict := range []bool{true, false} { + r := Resolver{StrictErrors: strict, Dial: fake.DialContext} + p, _, err := r.lookup(context.Background(), name, dnsmessage.TypeTXT, nil) + var wantErr error + var wantRRs int + if strict { + wantErr = &DNSError{ + Err: os.ErrDeadlineExceeded.Error(), + Name: name, + Server: server, + IsTimeout: true, + IsTemporary: true, + } + } else { + wantRRs = 1 + } + if !reflect.DeepEqual(err, wantErr) { + t.Errorf("strict=%v: got err %#v; want %#v", strict, err, wantErr) + } + a, err := p.AllAnswers() + if err != nil { + a = nil + } + if len(a) != wantRRs { + t.Errorf("strict=%v: got %v; want %v", strict, len(a), wantRRs) + } + } +} + +// Test for a race between uninstalling the test hooks and closing a +// socket connection. This used to fail when testing with -race. +func TestDNSGoroutineRace(t *testing.T) { + defer dnsWaitGroup.Wait() + + fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, t time.Time) (dnsmessage.Message, error) { + time.Sleep(10 * time.Microsecond) + return dnsmessage.Message{}, os.ErrDeadlineExceeded + }} + r := Resolver{PreferGo: true, Dial: fake.DialContext} + + // The timeout here is less than the timeout used by the server, + // so the goroutine started to query the (fake) server will hang + // around after this test is done if we don't call dnsWaitGroup.Wait. + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Microsecond) + defer cancel() + _, err := r.LookupIPAddr(ctx, "where.are.they.now") + if err == nil { + t.Fatal("fake DNS lookup unexpectedly succeeded") + } +} + +func lookupWithFake(fake fakeDNSServer, name string, typ dnsmessage.Type) error { + r := Resolver{PreferGo: true, Dial: fake.DialContext} + + conf := getSystemDNSConfig() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + _, _, err := r.tryOneName(ctx, conf, name, typ) + return err +} + +// Issue 8434: verify that Temporary returns true on an error when rcode +// is SERVFAIL +func TestIssue8434(t *testing.T) { + err := lookupWithFake(fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + RCode: dnsmessage.RCodeServerFailure, + }, + Questions: q.Questions, + }, nil + }, + }, "golang.org.", dnsmessage.TypeALL) + if err == nil { + t.Fatal("expected an error") + } + if ne, ok := err.(Error); !ok { + t.Fatalf("err = %#v; wanted something supporting net.Error", err) + } else if !ne.Temporary() { + t.Fatalf("Temporary = false for err = %#v; want Temporary == true", err) + } + if de, ok := err.(*DNSError); !ok { + t.Fatalf("err = %#v; wanted a *net.DNSError", err) + } else if !de.IsTemporary { + t.Fatalf("IsTemporary = false for err = %#v; want IsTemporary == true", err) + } +} + +func TestIssueNoSuchHostExists(t *testing.T) { + err := lookupWithFake(fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + RCode: dnsmessage.RCodeNameError, + }, + Questions: q.Questions, + }, nil + }, + }, "golang.org.", dnsmessage.TypeALL) + if err == nil { + t.Fatal("expected an error") + } + if _, ok := err.(Error); !ok { + t.Fatalf("err = %#v; wanted something supporting net.Error", err) + } + if de, ok := err.(*DNSError); !ok { + t.Fatalf("err = %#v; wanted a *net.DNSError", err) + } else if !de.IsNotFound { + t.Fatalf("IsNotFound = false for err = %#v; want IsNotFound == true", err) + } +} + +// TestNoSuchHost verifies that tryOneName works correctly when the domain does +// not exist. +// +// Issue 12778: verify that NXDOMAIN without RA bit errors as "no such host" +// and not "server misbehaving" +// +// Issue 25336: verify that NXDOMAIN errors fail fast. +// +// Issue 27525: verify that empty answers fail fast. +func TestNoSuchHost(t *testing.T) { + tests := []struct { + name string + f func(string, string, dnsmessage.Message, time.Time) (dnsmessage.Message, error) + }{ + { + "NXDOMAIN", + func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + RCode: dnsmessage.RCodeNameError, + RecursionAvailable: false, + }, + Questions: q.Questions, + }, nil + }, + }, + { + "no answers", + func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + RecursionAvailable: false, + Authoritative: true, + }, + Questions: q.Questions, + }, nil + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + lookups := 0 + err := lookupWithFake(fakeDNSServer{ + rh: func(n, s string, q dnsmessage.Message, d time.Time) (dnsmessage.Message, error) { + lookups++ + return test.f(n, s, q, d) + }, + }, ".", dnsmessage.TypeALL) + + if lookups != 1 { + t.Errorf("got %d lookups, wanted 1", lookups) + } + + if err == nil { + t.Fatal("expected an error") + } + de, ok := err.(*DNSError) + if !ok { + t.Fatalf("err = %#v; wanted a *net.DNSError", err) + } + if de.Err != errNoSuchHost.Error() { + t.Fatalf("Err = %#v; wanted %q", de.Err, errNoSuchHost.Error()) + } + if !de.IsNotFound { + t.Fatalf("IsNotFound = %v wanted true", de.IsNotFound) + } + }) + } +} + +// Issue 26573: verify that Conns that don't implement PacketConn are treated +// as streams even when udp was requested. +func TestDNSDialTCP(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + } + return r, nil + }, + alwaysTCP: true, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + ctx := context.Background() + _, _, err := r.exchange(ctx, "0.0.0.0", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), time.Second, useUDPOrTCP, false) + if err != nil { + t.Fatal("exchange failed:", err) + } +} + +// Issue 27763: verify that two strings in one TXT record are concatenated. +func TestTXTRecordTwoStrings(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + Answers: []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + }, + Body: &dnsmessage.TXTResource{ + TXT: []string{"string1 ", "string2"}, + }, + }, + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + }, + Body: &dnsmessage.TXTResource{ + TXT: []string{"onestring"}, + }, + }, + }, + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + txt, err := r.lookupTXT(context.Background(), "golang.org") + if err != nil { + t.Fatal("LookupTXT failed:", err) + } + if want := 2; len(txt) != want { + t.Fatalf("len(txt), got %d, want %d", len(txt), want) + } + if want := "string1 string2"; txt[0] != want { + t.Errorf("txt[0], got %q, want %q", txt[0], want) + } + if want := "onestring"; txt[1] != want { + t.Errorf("txt[1], got %q, want %q", txt[1], want) + } +} + +// Issue 29644: support single-request resolv.conf option in pure Go resolver. +// The A and AAAA queries will be sent sequentially, not in parallel. +func TestSingleRequestLookup(t *testing.T) { + defer dnsWaitGroup.Wait() + var ( + firstcalled int32 + ipv4 int32 = 1 + ipv6 int32 = 2 + ) + fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.ID, + Response: true, + }, + Questions: q.Questions, + } + for _, question := range q.Questions { + switch question.Type { + case dnsmessage.TypeA: + if question.Name.String() == "slowipv4.example.net." { + time.Sleep(10 * time.Millisecond) + } + if !atomic.CompareAndSwapInt32(&firstcalled, 0, ipv4) { + t.Errorf("the A query was received after the AAAA query !") + } + r.Answers = append(r.Answers, dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }) + case dnsmessage.TypeAAAA: + atomic.CompareAndSwapInt32(&firstcalled, 0, ipv6) + r.Answers = append(r.Answers, dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeAAAA, + Class: dnsmessage.ClassINET, + Length: 16, + }, + Body: &dnsmessage.AAAAResource{ + AAAA: TestAddr6, + }, + }) + } + } + return r, nil + }} + r := Resolver{PreferGo: true, Dial: fake.DialContext} + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + if err := conf.writeAndUpdate([]string{"options single-request"}); err != nil { + t.Fatal(err) + } + for _, name := range []string{"hostname.example.net", "slowipv4.example.net"} { + firstcalled = 0 + _, err := r.LookupIPAddr(context.Background(), name) + if err != nil { + t.Error(err) + } + } +} + +// Issue 29358. Add configuration knob to force TCP-only DNS requests in the pure Go resolver. +func TestDNSUseTCP(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + } + if n == "udp" { + t.Fatal("udp protocol was used instead of tcp") + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + _, _, err := r.exchange(ctx, "0.0.0.0", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), time.Second, useTCPOnly, false) + if err != nil { + t.Fatal("exchange failed:", err) + } +} + +func TestDNSUseTCPTruncated(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + Truncated: true, + }, + Questions: q.Questions, + Answers: []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + }, + } + if n == "udp" { + t.Fatal("udp protocol was used instead of tcp") + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + p, _, err := r.exchange(ctx, "0.0.0.0", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), time.Second, useTCPOnly, false) + if err != nil { + t.Fatal("exchange failed:", err) + } + a, err := p.AllAnswers() + if err != nil { + t.Fatalf("unexpected error %v getting all answers", err) + } + if len(a) != 1 { + t.Fatalf("got %d answers; want 1", len(a)) + } +} + +// Issue 34660: PTR response with non-PTR answers should ignore non-PTR +func TestPTRandNonPTR(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + Answers: []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypePTR, + Class: dnsmessage.ClassINET, + }, + Body: &dnsmessage.PTRResource{ + PTR: dnsmessage.MustNewName("golang.org."), + }, + }, + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeTXT, + Class: dnsmessage.ClassINET, + }, + Body: &dnsmessage.TXTResource{ + TXT: []string{"PTR 8 6 60 ..."}, // fake RRSIG + }, + }, + }, + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + names, err := r.lookupAddr(context.Background(), "192.0.2.123") + if err != nil { + t.Fatalf("LookupAddr: %v", err) + } + if want := []string{"golang.org."}; !slices.Equal(names, want) { + t.Errorf("names = %q; want %q", names, want) + } +} + +func TestCVE202133195(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + RecursionAvailable: true, + }, + Questions: q.Questions, + } + switch q.Questions[0].Type { + case dnsmessage.TypeCNAME: + r.Answers = []dnsmessage.Resource{} + case dnsmessage.TypeA: // CNAME lookup uses a A/AAAA as a proxy + r.Answers = append(r.Answers, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName(".golang.org."), + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + ) + case dnsmessage.TypeSRV: + n := q.Questions[0].Name + if n.String() == "_hdr._tcp.golang.org." { + n = dnsmessage.MustNewName(".golang.org.") + } + r.Answers = append(r.Answers, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: n, + Type: dnsmessage.TypeSRV, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.SRVResource{ + Target: dnsmessage.MustNewName(".golang.org."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: n, + Type: dnsmessage.TypeSRV, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.SRVResource{ + Target: dnsmessage.MustNewName("good.golang.org."), + }, + }, + ) + case dnsmessage.TypeMX: + r.Answers = append(r.Answers, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName(".golang.org."), + Type: dnsmessage.TypeMX, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName(".golang.org."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName("good.golang.org."), + Type: dnsmessage.TypeMX, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName("good.golang.org."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName("127.0.0.1."), + Type: dnsmessage.TypeMX, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName("127.0.0.1."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName("1.2.3.4.5."), + Type: dnsmessage.TypeMX, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName("1.2.3.4.5."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName("2001:4860:0:2001::68."), + Type: dnsmessage.TypeMX, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName("2001:4860:0:2001::68."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName("2001:4860:0:2001::68%zone."), + Type: dnsmessage.TypeMX, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName("2001:4860:0:2001::68%zone."), + }, + }, + ) + case dnsmessage.TypeNS: + r.Answers = append(r.Answers, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName(".golang.org."), + Type: dnsmessage.TypeNS, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.NSResource{ + NS: dnsmessage.MustNewName(".golang.org."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName("good.golang.org."), + Type: dnsmessage.TypeNS, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.NSResource{ + NS: dnsmessage.MustNewName("good.golang.org."), + }, + }, + ) + case dnsmessage.TypePTR: + r.Answers = append(r.Answers, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName(".golang.org."), + Type: dnsmessage.TypePTR, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.PTRResource{ + PTR: dnsmessage.MustNewName(".golang.org."), + }, + }, + dnsmessage.Resource{ + Header: dnsmessage.ResourceHeader{ + Name: dnsmessage.MustNewName("good.golang.org."), + Type: dnsmessage.TypePTR, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.PTRResource{ + PTR: dnsmessage.MustNewName("good.golang.org."), + }, + }, + ) + } + return r, nil + }, + } + + r := Resolver{PreferGo: true, Dial: fake.DialContext} + // Change the default resolver to match our manipulated resolver + originalDefault := DefaultResolver + DefaultResolver = &r + defer func() { DefaultResolver = originalDefault }() + // Redirect host file lookups. + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + hostsFilePath = "testdata/hosts" + + tests := []struct { + name string + f func(*testing.T) + }{ + { + name: "CNAME", + f: func(t *testing.T) { + expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"} + _, err := r.LookupCNAME(context.Background(), "golang.org") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + _, err = LookupCNAME("golang.org") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + }, + }, + { + name: "SRV (bad record)", + f: func(t *testing.T) { + expected := []*SRV{ + { + Target: "good.golang.org.", + }, + } + expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"} + _, records, err := r.LookupSRV(context.Background(), "target", "tcp", "golang.org") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + if !reflect.DeepEqual(records, expected) { + t.Error("Unexpected record set") + } + _, records, err = LookupSRV("target", "tcp", "golang.org") + if err.Error() != expectedErr.Error() { + t.Errorf("unexpected error: %s", err) + } + if !reflect.DeepEqual(records, expected) { + t.Error("Unexpected record set") + } + }, + }, + { + name: "SRV (bad header)", + f: func(t *testing.T) { + _, _, err := r.LookupSRV(context.Background(), "hdr", "tcp", "golang.org.") + if expected := "lookup golang.org.: SRV header name is invalid"; err == nil || err.Error() != expected { + t.Errorf("Resolver.LookupSRV returned unexpected error, got %q, want %q", err, expected) + } + _, _, err = LookupSRV("hdr", "tcp", "golang.org.") + if expected := "lookup golang.org.: SRV header name is invalid"; err == nil || err.Error() != expected { + t.Errorf("LookupSRV returned unexpected error, got %q, want %q", err, expected) + } + }, + }, + { + name: "MX", + f: func(t *testing.T) { + expected := []string{ + "127.0.0.1.", + "2001:4860:0:2001::68.", + "good.golang.org.", + } + expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"} + records, err := r.LookupMX(context.Background(), "golang.org") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + + hosts := func(records []*MX) []string { + var got []string + for _, mx := range records { + got = append(got, mx.Host) + } + slices.Sort(got) + return got + } + + got := hosts(records) + if !slices.Equal(got, expected) { + t.Errorf("Unexpected record set: got %v, want %v", got, expected) + } + records, err = LookupMX("golang.org") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + got = hosts(records) + if !slices.Equal(got, expected) { + t.Errorf("Unexpected record set: got %v, want %v", got, expected) + } + }, + }, + { + name: "NS", + f: func(t *testing.T) { + expected := []*NS{ + { + Host: "good.golang.org.", + }, + } + expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"} + records, err := r.LookupNS(context.Background(), "golang.org") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + if !reflect.DeepEqual(records, expected) { + t.Error("Unexpected record set") + } + records, err = LookupNS("golang.org") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + if !reflect.DeepEqual(records, expected) { + t.Error("Unexpected record set") + } + }, + }, + { + name: "Addr", + f: func(t *testing.T) { + expected := []string{"good.golang.org."} + expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "192.0.2.42"} + records, err := r.LookupAddr(context.Background(), "192.0.2.42") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + if !slices.Equal(records, expected) { + t.Error("Unexpected record set") + } + records, err = LookupAddr("192.0.2.42") + if err.Error() != expectedErr.Error() { + t.Fatalf("unexpected error: %s", err) + } + if !slices.Equal(records, expected) { + t.Error("Unexpected record set") + } + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, tc.f) + } + +} + +func TestNullMX(t *testing.T) { + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + Answers: []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeMX, + Class: dnsmessage.ClassINET, + }, + Body: &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName("."), + }, + }, + }, + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + rrset, err := r.LookupMX(context.Background(), "golang.org") + if err != nil { + t.Fatalf("LookupMX: %v", err) + } + if want := []*MX{&MX{Host: "."}}; !reflect.DeepEqual(rrset, want) { + records := []string{} + for _, rr := range rrset { + records = append(records, fmt.Sprintf("%v", rr)) + } + t.Errorf("records = [%v]; want [%v]", strings.Join(records, " "), want[0]) + } +} + +func TestRootNS(t *testing.T) { + // See https://golang.org/issue/45715. + fake := fakeDNSServer{ + rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + Answers: []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeNS, + Class: dnsmessage.ClassINET, + }, + Body: &dnsmessage.NSResource{ + NS: dnsmessage.MustNewName("i.root-servers.net."), + }, + }, + }, + } + return r, nil + }, + } + r := Resolver{PreferGo: true, Dial: fake.DialContext} + rrset, err := r.LookupNS(context.Background(), ".") + if err != nil { + t.Fatalf("LookupNS: %v", err) + } + if want := []*NS{&NS{Host: "i.root-servers.net."}}; !reflect.DeepEqual(rrset, want) { + records := []string{} + for _, rr := range rrset { + records = append(records, fmt.Sprintf("%v", rr)) + } + t.Errorf("records = [%v]; want [%v]", strings.Join(records, " "), want[0]) + } +} + +func TestGoLookupIPCNAMEOrderHostsAliasesFilesOnlyMode(t *testing.T) { + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + hostsFilePath = "testdata/aliases" + mode := hostLookupFiles + + for _, v := range lookupStaticHostAliasesTest { + testGoLookupIPCNAMEOrderHostsAliases(t, mode, v.lookup, absDomainName(v.res)) + } +} + +func TestGoLookupIPCNAMEOrderHostsAliasesFilesDNSMode(t *testing.T) { + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + hostsFilePath = "testdata/aliases" + mode := hostLookupFilesDNS + + for _, v := range lookupStaticHostAliasesTest { + testGoLookupIPCNAMEOrderHostsAliases(t, mode, v.lookup, absDomainName(v.res)) + } +} + +var goLookupIPCNAMEOrderDNSFilesModeTests = []struct { + lookup, res string +}{ + // 127.0.1.1 + {"invalid.invalid", "invalid.test"}, +} + +func TestGoLookupIPCNAMEOrderHostsAliasesDNSFilesMode(t *testing.T) { + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + hostsFilePath = "testdata/aliases" + mode := hostLookupDNSFiles + + for _, v := range goLookupIPCNAMEOrderDNSFilesModeTests { + testGoLookupIPCNAMEOrderHostsAliases(t, mode, v.lookup, absDomainName(v.res)) + } +} + +func testGoLookupIPCNAMEOrderHostsAliases(t *testing.T, mode hostLookupOrder, lookup, lookupRes string) { + fake := fakeDNSServer{ + rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + var answers []dnsmessage.Resource + + if mode != hostLookupDNSFiles { + t.Fatal("received unexpected DNS query") + } + + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + }, + Questions: []dnsmessage.Question{q.Questions[0]}, + Answers: answers, + }, nil + }, + } + + r := Resolver{PreferGo: true, Dial: fake.DialContext} + ins := []string{lookup, absDomainName(lookup), strings.ToLower(lookup), strings.ToUpper(lookup)} + for _, in := range ins { + _, res, err := r.goLookupIPCNAMEOrder(context.Background(), "ip", in, mode, nil) + if err != nil { + t.Errorf("expected err == nil, but got error: %v", err) + } + if res.String() != lookupRes { + t.Errorf("goLookupIPCNAMEOrder(%v): got %v, want %v", in, res, lookupRes) + } + } +} + +// Test that we advertise support for a larger DNS packet size. +// This isn't a great test as it just tests the dnsmessage package +// against itself. +func TestDNSPacketSize(t *testing.T) { + t.Run("enabled", func(t *testing.T) { + testDNSPacketSize(t, false) + }) + t.Run("disabled", func(t *testing.T) { + testDNSPacketSize(t, true) + }) +} + +func testDNSPacketSize(t *testing.T, disable bool) { + fake := fakeDNSServer{ + rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + if disable { + if len(q.Additionals) > 0 { + t.Error("unexpected additional record") + } + } else { + if len(q.Additionals) == 0 { + t.Error("missing EDNS record") + } else if opt, ok := q.Additionals[0].Body.(*dnsmessage.OPTResource); !ok { + t.Errorf("additional record type %T, expected OPTResource", q.Additionals[0]) + } else if len(opt.Options) != 0 { + t.Errorf("found %d Options, expected none", len(opt.Options)) + } else { + got := int(q.Additionals[0].Header.Class) + t.Logf("EDNS packet size == %d", got) + if got != maxDNSPacketSize { + t.Errorf("EDNS packet size == %d, want %d", got, maxDNSPacketSize) + } + } + } + + // Hand back a dummy answer to verify that + // LookupIPAddr completes. + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + } + if q.Questions[0].Type == dnsmessage.TypeA { + r.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + } + } + return r, nil + }, + } + + if disable { + t.Setenv("GODEBUG", "netedns0=0") + } + + r := &Resolver{PreferGo: true, Dial: fake.DialContext} + if _, err := r.LookupIPAddr(context.Background(), "go.dev"); err != nil { + t.Errorf("lookup failed: %v", err) + } +} + +func TestLongDNSNames(t *testing.T) { + const longDNSsuffix = ".go.dev." + const longDNSsuffixNoEndingDot = ".go.dev" + + var longDNSPrefix = strings.Repeat("verylongdomainlabel.", 20) + + var longDNSNamesTests = []struct { + req string + fail bool + }{ + {req: longDNSPrefix[:255-len(longDNSsuffix)] + longDNSsuffix, fail: true}, + {req: longDNSPrefix[:254-len(longDNSsuffix)] + longDNSsuffix}, + {req: longDNSPrefix[:253-len(longDNSsuffix)] + longDNSsuffix}, + + {req: longDNSPrefix[:253-len(longDNSsuffixNoEndingDot)] + longDNSsuffixNoEndingDot}, + {req: longDNSPrefix[:254-len(longDNSsuffixNoEndingDot)] + longDNSsuffixNoEndingDot, fail: true}, + } + + fake := fakeDNSServer{ + rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + Answers: []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: q.Questions[0].Type, + Class: dnsmessage.ClassINET, + }, + }, + }, + } + + switch q.Questions[0].Type { + case dnsmessage.TypeA: + r.Answers[0].Body = &dnsmessage.AResource{A: TestAddr} + case dnsmessage.TypeAAAA: + r.Answers[0].Body = &dnsmessage.AAAAResource{AAAA: TestAddr6} + case dnsmessage.TypeTXT: + r.Answers[0].Body = &dnsmessage.TXTResource{TXT: []string{"."}} + case dnsmessage.TypeMX: + r.Answers[0].Body = &dnsmessage.MXResource{ + MX: dnsmessage.MustNewName("go.dev."), + } + case dnsmessage.TypeNS: + r.Answers[0].Body = &dnsmessage.NSResource{ + NS: dnsmessage.MustNewName("go.dev."), + } + case dnsmessage.TypeSRV: + r.Answers[0].Body = &dnsmessage.SRVResource{ + Target: dnsmessage.MustNewName("go.dev."), + } + case dnsmessage.TypeCNAME: + r.Answers[0].Body = &dnsmessage.CNAMEResource{ + CNAME: dnsmessage.MustNewName("fake.cname."), + } + default: + panic("unknown dnsmessage type") + } + + return r, nil + }, + } + + r := &Resolver{PreferGo: true, Dial: fake.DialContext} + + methodTests := []string{"CNAME", "Host", "IP", "IPAddr", "MX", "NS", "NetIP", "SRV", "TXT"} + query := func(t string, req string) error { + switch t { + case "CNAME": + _, err := r.LookupCNAME(context.Background(), req) + return err + case "Host": + _, err := r.LookupHost(context.Background(), req) + return err + case "IP": + _, err := r.LookupIP(context.Background(), "ip", req) + return err + case "IPAddr": + _, err := r.LookupIPAddr(context.Background(), req) + return err + case "MX": + _, err := r.LookupMX(context.Background(), req) + return err + case "NS": + _, err := r.LookupNS(context.Background(), req) + return err + case "NetIP": + _, err := r.LookupNetIP(context.Background(), "ip", req) + return err + case "SRV": + const service = "service" + const proto = "proto" + req = req[len(service)+len(proto)+4:] + _, _, err := r.LookupSRV(context.Background(), service, proto, req) + return err + case "TXT": + _, err := r.LookupTXT(context.Background(), req) + return err + } + panic("unknown query method") + } + + for i, v := range longDNSNamesTests { + for _, testName := range methodTests { + err := query(testName, v.req) + if v.fail { + if err == nil { + t.Errorf("%v: Lookup%v: unexpected success", i, testName) + break + } + + expectedErr := DNSError{Err: errNoSuchHost.Error(), Name: v.req, IsNotFound: true} + dnsErr, _ := errors.AsType[*DNSError](err) + if dnsErr == nil || *dnsErr != expectedErr { + t.Errorf("%v: Lookup%v: unexpected error: %v", i, testName, err) + } + break + } + if err != nil { + t.Errorf("%v: Lookup%v: unexpected error: %v", i, testName, err) + } + } + } +} + +func TestDNSTrustAD(t *testing.T) { + fake := fakeDNSServer{ + rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + if q.Questions[0].Name.String() == "notrustad.go.dev." && q.Header.AuthenticData { + t.Error("unexpected AD bit") + } + + if q.Questions[0].Name.String() == "trustad.go.dev." && !q.Header.AuthenticData { + t.Error("expected AD bit") + } + + r := dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: dnsmessage.RCodeSuccess, + }, + Questions: q.Questions, + } + if q.Questions[0].Type == dnsmessage.TypeA { + r.Answers = []dnsmessage.Resource{ + { + Header: dnsmessage.ResourceHeader{ + Name: q.Questions[0].Name, + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + Length: 4, + }, + Body: &dnsmessage.AResource{ + A: TestAddr, + }, + }, + } + } + + return r, nil + }} + + r := &Resolver{PreferGo: true, Dial: fake.DialContext} + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + err = conf.writeAndUpdate([]string{"nameserver 127.0.0.1"}) + if err != nil { + t.Fatal(err) + } + + if _, err := r.LookupIPAddr(context.Background(), "notrustad.go.dev"); err != nil { + t.Errorf("lookup failed: %v", err) + } + + err = conf.writeAndUpdate([]string{"nameserver 127.0.0.1", "options trust-ad"}) + if err != nil { + t.Fatal(err) + } + + if _, err := r.LookupIPAddr(context.Background(), "trustad.go.dev"); err != nil { + t.Errorf("lookup failed: %v", err) + } +} + +func TestDNSConfigNoReload(t *testing.T) { + r := &Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (Conn, error) { + if address != "192.0.2.1:53" { + return nil, errors.New("configuration unexpectedly changed") + } + return fakeDNSServerSuccessful.DialContext(ctx, network, address) + }} + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + err = conf.writeAndUpdateWithLastCheckedTime([]string{"nameserver 192.0.2.1", "options no-reload"}, time.Now().Add(-time.Hour)) + if err != nil { + t.Fatal(err) + } + + if _, err = r.LookupHost(context.Background(), "go.dev"); err != nil { + t.Fatal(err) + } + + err = conf.write([]string{"nameserver 192.0.2.200"}) + if err != nil { + t.Fatal(err) + } + + if _, err = r.LookupHost(context.Background(), "go.dev"); err != nil { + t.Fatal(err) + } +} + +func TestLookupOrderFilesNoSuchHost(t *testing.T) { + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + if runtime.GOOS != "openbsd" { + defer setSystemNSS(getSystemNSS(), 0) + setSystemNSS(nssStr(t, "hosts: files"), time.Hour) + } + + conf, err := newResolvConfTest() + if err != nil { + t.Fatal(err) + } + defer conf.teardown() + + resolvConf := dnsConfig{servers: defaultNS} + if runtime.GOOS == "openbsd" { + // Set error to ErrNotExist, so that the hostLookupOrder + // returns hostLookupFiles for openbsd. + resolvConf.err = os.ErrNotExist + } + + if !conf.forceUpdateConf(&resolvConf, time.Now().Add(time.Hour)) { + t.Fatal("failed to update resolv config") + } + + tmpFile := filepath.Join(t.TempDir(), "hosts") + if err := os.WriteFile(tmpFile, []byte{}, 0660); err != nil { + t.Fatal(err) + } + hostsFilePath = tmpFile + + const testName = "test.invalid" + + order, _ := systemConf().hostLookupOrder(DefaultResolver, testName) + if order != hostLookupFiles { + // skip test for systems which do not return hostLookupFiles + t.Skipf("hostLookupOrder did not return hostLookupFiles") + } + + var lookupTests = []struct { + name string + lookup func(name string) error + }{ + { + name: "Host", + lookup: func(name string) error { + _, err = DefaultResolver.LookupHost(context.Background(), name) + return err + }, + }, + { + name: "IP", + lookup: func(name string) error { + _, err = DefaultResolver.LookupIP(context.Background(), "ip", name) + return err + }, + }, + { + name: "IPAddr", + lookup: func(name string) error { + _, err = DefaultResolver.LookupIPAddr(context.Background(), name) + return err + }, + }, + { + name: "NetIP", + lookup: func(name string) error { + _, err = DefaultResolver.LookupNetIP(context.Background(), "ip", name) + return err + }, + }, + } + + for _, v := range lookupTests { + err := v.lookup(testName) + + if err == nil { + t.Errorf("Lookup%v: unexpected success", v.name) + continue + } + + expectedErr := DNSError{Err: errNoSuchHost.Error(), Name: testName, IsNotFound: true} + dnsErr, _ := errors.AsType[*DNSError](err) + if dnsErr == nil || *dnsErr != expectedErr { + t.Errorf("Lookup%v: unexpected error: %v", v.name, err) + } + } +} + +func TestExtendedRCode(t *testing.T) { + fake := fakeDNSServer{ + rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) { + fraudSuccessCode := dnsmessage.RCodeSuccess | 1<<10 + + var edns0Hdr dnsmessage.ResourceHeader + edns0Hdr.SetEDNS0(maxDNSPacketSize, fraudSuccessCode, false) + + return dnsmessage.Message{ + Header: dnsmessage.Header{ + ID: q.Header.ID, + Response: true, + RCode: fraudSuccessCode, + }, + Questions: []dnsmessage.Question{q.Questions[0]}, + Additionals: []dnsmessage.Resource{{ + Header: edns0Hdr, + Body: &dnsmessage.OPTResource{}, + }}, + }, nil + }, + } + + r := &Resolver{PreferGo: true, Dial: fake.DialContext} + _, _, err := r.tryOneName(context.Background(), getSystemDNSConfig(), "go.dev.", dnsmessage.TypeA) + if dnsErr, ok := errors.AsType[*DNSError](err); !ok || dnsErr.Err != errServerMisbehaving.Error() { + t.Fatalf("r.tryOneName(): unexpected error: %v", err) + } +} diff --git a/go/src/net/dnsconfig.go b/go/src/net/dnsconfig.go new file mode 100644 index 0000000000000000000000000000000000000000..5a156ea0e4b6a7c7c9e009fe60a6dd8d621cb74b --- /dev/null +++ b/go/src/net/dnsconfig.go @@ -0,0 +1,57 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "os" + "sync/atomic" + "time" + _ "unsafe" +) + +// defaultNS is the default name servers to use in the absence of DNS configuration. +// +// defaultNS should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/pojntfx/hydrapp/hydrapp +// - github.com/mtibben/androiddnsfix +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname defaultNS +var defaultNS = []string{"127.0.0.1:53", "[::1]:53"} + +var getHostname = os.Hostname // variable for testing + +type dnsConfig struct { + servers []string // server addresses (in host:port form) to use + search []string // rooted suffixes to append to local name + ndots int // number of dots in name to trigger absolute lookup + timeout time.Duration // wait before giving up on a query, including retries + attempts int // lost packets before giving up on server + rotate bool // round robin among servers + unknownOpt bool // anything unknown was encountered + lookup []string // OpenBSD top-level database "lookup" order + err error // any error that occurs during open of resolv.conf + mtime time.Time // time of resolv.conf modification + soffset uint32 // used by serverOffset + singleRequest bool // use sequential A and AAAA queries instead of parallel queries + useTCP bool // force usage of TCP for DNS resolutions + trustAD bool // add AD flag to queries + noReload bool // do not check for config file updates +} + +// serverOffset returns an offset that can be used to determine +// indices of servers in c.servers when making queries. +// When the rotate option is enabled, this offset increases. +// Otherwise it is always 0. +func (c *dnsConfig) serverOffset() uint32 { + if c.rotate { + return atomic.AddUint32(&c.soffset, 1) - 1 // return 0 to start + } + return 0 +} diff --git a/go/src/net/dnsconfig_unix.go b/go/src/net/dnsconfig_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..0fcf2c6cc38426c735f5ca0404c39218a5f8f1eb --- /dev/null +++ b/go/src/net/dnsconfig_unix.go @@ -0,0 +1,164 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !windows + +// Read system DNS config from /etc/resolv.conf + +package net + +import ( + "internal/bytealg" + "internal/stringslite" + "net/netip" + "time" +) + +// See resolv.conf(5) on a Linux machine. +func dnsReadConfig(filename string) *dnsConfig { + conf := &dnsConfig{ + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + } + file, err := open(filename) + if err != nil { + conf.servers = defaultNS + conf.search = dnsDefaultSearch() + conf.err = err + return conf + } + defer file.close() + if fi, err := file.file.Stat(); err == nil { + conf.mtime = fi.ModTime() + } else { + conf.servers = defaultNS + conf.search = dnsDefaultSearch() + conf.err = err + return conf + } + for line, ok := file.readLine(); ok; line, ok = file.readLine() { + if len(line) > 0 && (line[0] == ';' || line[0] == '#') { + // comment. + continue + } + f := getFields(line) + if len(f) < 1 { + continue + } + switch f[0] { + case "nameserver": // add one name server + if len(f) > 1 && len(conf.servers) < 3 { // small, but the standard limit + // One more check: make sure server name is + // just an IP address. Otherwise we need DNS + // to look it up. + if _, err := netip.ParseAddr(f[1]); err == nil { + conf.servers = append(conf.servers, JoinHostPort(f[1], "53")) + } + } + + case "domain": // set search path to just this domain + if len(f) > 1 { + conf.search = []string{ensureRooted(f[1])} + } + + case "search": // set search path to given servers + conf.search = make([]string, 0, len(f)-1) + for i := 1; i < len(f); i++ { + name := ensureRooted(f[i]) + if name == "." { + continue + } + conf.search = append(conf.search, name) + } + + case "options": // magic options + for _, s := range f[1:] { + switch { + case stringslite.HasPrefix(s, "ndots:"): + n, _, _ := dtoi(s[6:]) + if n < 0 { + n = 0 + } else if n > 15 { + n = 15 + } + conf.ndots = n + case stringslite.HasPrefix(s, "timeout:"): + n, _, _ := dtoi(s[8:]) + if n < 1 { + n = 1 + } + conf.timeout = time.Duration(n) * time.Second + case stringslite.HasPrefix(s, "attempts:"): + n, _, _ := dtoi(s[9:]) + if n < 1 { + n = 1 + } + conf.attempts = n + case s == "rotate": + conf.rotate = true + case s == "single-request" || s == "single-request-reopen": + // Linux option: + // http://man7.org/linux/man-pages/man5/resolv.conf.5.html + // "By default, glibc performs IPv4 and IPv6 lookups in parallel [...] + // This option disables the behavior and makes glibc + // perform the IPv6 and IPv4 requests sequentially." + conf.singleRequest = true + case s == "use-vc" || s == "usevc" || s == "tcp": + // Linux (use-vc), FreeBSD (usevc) and OpenBSD (tcp) option: + // http://man7.org/linux/man-pages/man5/resolv.conf.5.html + // "Sets RES_USEVC in _res.options. + // This option forces the use of TCP for DNS resolutions." + // https://www.freebsd.org/cgi/man.cgi?query=resolv.conf&sektion=5&manpath=freebsd-release-ports + // https://man.openbsd.org/resolv.conf.5 + conf.useTCP = true + case s == "trust-ad": + conf.trustAD = true + case s == "edns0": + // We use EDNS by default. + // Ignore this option. + case s == "no-reload": + conf.noReload = true + default: + conf.unknownOpt = true + } + } + + case "lookup": + // OpenBSD option: + // https://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/resolv.conf.5 + // "the legal space-separated values are: bind, file, yp" + conf.lookup = f[1:] + + default: + conf.unknownOpt = true + } + } + if len(conf.servers) == 0 { + conf.servers = defaultNS + } + if len(conf.search) == 0 { + conf.search = dnsDefaultSearch() + } + return conf +} + +func dnsDefaultSearch() []string { + hn, err := getHostname() + if err != nil { + // best effort + return nil + } + if i := bytealg.IndexByteString(hn, '.'); i >= 0 && i < len(hn)-1 { + return []string{ensureRooted(hn[i+1:])} + } + return nil +} + +func ensureRooted(s string) string { + if len(s) > 0 && s[len(s)-1] == '.' { + return s + } + return s + "." +} diff --git a/go/src/net/dnsconfig_unix_test.go b/go/src/net/dnsconfig_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4db1c5a4af9e5336fb41ae254550b1dff520732a --- /dev/null +++ b/go/src/net/dnsconfig_unix_test.go @@ -0,0 +1,315 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "errors" + "io/fs" + "os" + "reflect" + "slices" + "strings" + "testing" + "time" +) + +var dnsReadConfigTests = []struct { + name string + want *dnsConfig +}{ + { + name: "testdata/resolv.conf", + want: &dnsConfig{ + servers: []string{"8.8.8.8:53", "[2001:4860:4860::8888]:53", "[fe80::1%lo0]:53"}, + search: []string{"localdomain."}, + ndots: 5, + timeout: 10 * time.Second, + attempts: 3, + rotate: true, + unknownOpt: true, // the "options attempts 3" line + }, + }, + { + name: "testdata/domain-resolv.conf", + want: &dnsConfig{ + servers: []string{"8.8.8.8:53"}, + search: []string{"localdomain."}, + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + }, + }, + { + name: "testdata/search-resolv.conf", + want: &dnsConfig{ + servers: []string{"8.8.8.8:53"}, + search: []string{"test.", "invalid."}, + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + }, + }, + { + name: "testdata/search-single-dot-resolv.conf", + want: &dnsConfig{ + servers: []string{"8.8.8.8:53"}, + search: []string{}, + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + }, + }, + { + name: "testdata/empty-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/invalid-ndots-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 0, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/large-ndots-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 15, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/negative-ndots-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 0, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/openbsd-resolv.conf", + want: &dnsConfig{ + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + lookup: []string{"file", "bind"}, + servers: []string{"169.254.169.254:53", "10.240.0.1:53"}, + search: []string{"c.symbolic-datum-552.internal."}, + }, + }, + { + name: "testdata/single-request-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 1, + singleRequest: true, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/single-request-reopen-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 1, + singleRequest: true, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/linux-use-vc-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 1, + useTCP: true, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/freebsd-usevc-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 1, + useTCP: true, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, + { + name: "testdata/openbsd-tcp-resolv.conf", + want: &dnsConfig{ + servers: defaultNS, + ndots: 1, + useTCP: true, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + }, + }, +} + +func TestDNSReadConfig(t *testing.T) { + origGetHostname := getHostname + defer func() { getHostname = origGetHostname }() + getHostname = func() (string, error) { return "host.domain.local", nil } + + for _, tt := range dnsReadConfigTests { + want := *tt.want + if len(want.search) == 0 { + want.search = dnsDefaultSearch() + } + conf := dnsReadConfig(tt.name) + if conf.err != nil { + t.Fatal(conf.err) + } + conf.mtime = time.Time{} + if !reflect.DeepEqual(conf, &want) { + t.Errorf("%s:\ngot: %+v\nwant: %+v", tt.name, conf, want) + } + } +} + +func TestDNSReadMissingFile(t *testing.T) { + origGetHostname := getHostname + defer func() { getHostname = origGetHostname }() + getHostname = func() (string, error) { return "host.domain.local", nil } + + conf := dnsReadConfig("a-nonexistent-file") + if !os.IsNotExist(conf.err) { + t.Errorf("missing resolv.conf:\ngot: %v\nwant: %v", conf.err, fs.ErrNotExist) + } + conf.err = nil + want := &dnsConfig{ + servers: defaultNS, + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + search: []string{"domain.local."}, + } + if !reflect.DeepEqual(conf, want) { + t.Errorf("missing resolv.conf:\ngot: %+v\nwant: %+v", conf, want) + } +} + +var dnsDefaultSearchTests = []struct { + name string + err error + want []string +}{ + { + name: "host.long.domain.local", + want: []string{"long.domain.local."}, + }, + { + name: "host.local", + want: []string{"local."}, + }, + { + name: "host", + want: nil, + }, + { + name: "host.domain.local", + err: errors.New("errored"), + want: nil, + }, + { + // ensures we don't return []string{""} + // which causes duplicate lookups + name: "foo.", + want: nil, + }, +} + +func TestDNSDefaultSearch(t *testing.T) { + origGetHostname := getHostname + defer func() { getHostname = origGetHostname }() + + for _, tt := range dnsDefaultSearchTests { + getHostname = func() (string, error) { return tt.name, tt.err } + got := dnsDefaultSearch() + if !slices.Equal(got, tt.want) { + t.Errorf("dnsDefaultSearch with hostname %q and error %+v = %q, wanted %q", tt.name, tt.err, got, tt.want) + } + } +} + +func TestDNSNameLength(t *testing.T) { + origGetHostname := getHostname + defer func() { getHostname = origGetHostname }() + getHostname = func() (string, error) { return "host.domain.local", nil } + + var char63 = "" + for i := 0; i < 63; i++ { + char63 += "a" + } + longDomain := strings.Repeat(char63+".", 5) + "example" + + for _, tt := range dnsReadConfigTests { + conf := dnsReadConfig(tt.name) + if conf.err != nil { + t.Fatal(conf.err) + } + + suffixList := tt.want.search + if len(suffixList) == 0 { + suffixList = dnsDefaultSearch() + } + + var shortestSuffix int + for _, suffix := range suffixList { + if shortestSuffix == 0 || len(suffix) < shortestSuffix { + shortestSuffix = len(suffix) + } + } + + // Test a name that will be maximally long when prefixing the shortest + // suffix (accounting for the intervening dot). + longName := longDomain[len(longDomain)-254+1+shortestSuffix:] + if longName[0] == '.' || longName[1] == '.' { + longName = "aa." + longName[3:] + } + for _, fqdn := range conf.nameList(longName) { + if len(fqdn) > 254 { + t.Errorf("got %d; want less than or equal to 254", len(fqdn)) + } + } + + // Now test a name that's too long for suffixing. + unsuffixable := "a." + longName[1:] + unsuffixableResults := conf.nameList(unsuffixable) + if len(unsuffixableResults) != 1 { + t.Errorf("suffixed names %v; want []", unsuffixableResults[1:]) + } + + // Now test a name that's too long for DNS. + tooLong := "a." + longDomain + tooLongResults := conf.nameList(tooLong) + if tooLongResults != nil { + t.Errorf("suffixed names %v; want nil", tooLongResults) + } + } +} diff --git a/go/src/net/dnsconfig_windows.go b/go/src/net/dnsconfig_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..34455309dbb297b513ed84b5eaa1540b4b0142a1 --- /dev/null +++ b/go/src/net/dnsconfig_windows.go @@ -0,0 +1,68 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/syscall/windows" + "syscall" + "time" +) + +func dnsReadConfig(ignoredFilename string) (conf *dnsConfig) { + conf = &dnsConfig{ + ndots: 1, + timeout: 5 * time.Second, + attempts: 2, + } + defer func() { + if len(conf.servers) == 0 { + conf.servers = defaultNS + } + }() + aas, err := adapterAddresses() + if err != nil { + return + } + + for _, aa := range aas { + // Only take interfaces whose OperStatus is IfOperStatusUp(0x01) into DNS configs. + if aa.OperStatus != windows.IfOperStatusUp { + continue + } + + // Only take interfaces which have at least one gateway + if aa.FirstGatewayAddress == nil { + continue + } + + for dns := aa.FirstDnsServerAddress; dns != nil; dns = dns.Next { + sa, err := dns.Address.Sockaddr.Sockaddr() + if err != nil { + continue + } + var ip IP + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + ip = IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3]) + case *syscall.SockaddrInet6: + ip = make(IP, IPv6len) + copy(ip, sa.Addr[:]) + if ip[0] == 0xfe && ip[1] == 0xc0 { + // fec0/10 IPv6 addresses are site local anycast DNS + // addresses Microsoft sets by default if no other + // IPv6 DNS address is set. Site local anycast is + // deprecated since 2004, see + // https://datatracker.ietf.org/doc/html/rfc3879 + continue + } + default: + // Unexpected type. + continue + } + conf.servers = append(conf.servers, JoinHostPort(ip.String(), "53")) + } + } + return conf +} diff --git a/go/src/net/dnsname_test.go b/go/src/net/dnsname_test.go new file mode 100644 index 0000000000000000000000000000000000000000..601a33af9f4c0af4ea06c7d780064ed69a60112e --- /dev/null +++ b/go/src/net/dnsname_test.go @@ -0,0 +1,84 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "strings" + "testing" +) + +type dnsNameTest struct { + name string + result bool +} + +var dnsNameTests = []dnsNameTest{ + // RFC 2181, section 11. + {"_xmpp-server._tcp.google.com", true}, + {"foo.com", true}, + {"1foo.com", true}, + {"26.0.0.73.com", true}, + {"10-0-0-1", true}, + {"fo-o.com", true}, + {"fo1o.com", true}, + {"foo1.com", true}, + {"a.b..com", false}, + {"a.b-.com", false}, + {"a.b.com-", false}, + {"a.b..", false}, + {"b.com.", true}, +} + +func emitDNSNameTest(ch chan<- dnsNameTest) { + defer close(ch) + var char63 = "" + for i := 0; i < 63; i++ { + char63 += "a" + } + char64 := char63 + "a" + longDomain := strings.Repeat(char63+".", 5) + "example" + + for _, tc := range dnsNameTests { + ch <- tc + } + + ch <- dnsNameTest{char63 + ".com", true} + ch <- dnsNameTest{char64 + ".com", false} + + // Remember: wire format is two octets longer than presentation + // (length octets for the first and [root] last labels). + // 253 is fine: + ch <- dnsNameTest{longDomain[len(longDomain)-253:], true} + // A terminal dot doesn't contribute to length: + ch <- dnsNameTest{longDomain[len(longDomain)-253:] + ".", true} + // 254 is bad: + ch <- dnsNameTest{longDomain[len(longDomain)-254:], false} +} + +func TestDNSName(t *testing.T) { + ch := make(chan dnsNameTest) + go emitDNSNameTest(ch) + for tc := range ch { + if isDomainName(tc.name) != tc.result { + t.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result) + } + } +} + +func BenchmarkDNSName(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + + benchmarks := append(dnsNameTests, []dnsNameTest{ + {strings.Repeat("a", 63), true}, + {strings.Repeat("a", 64), false}, + }...) + for n := 0; n < b.N; n++ { + for _, tc := range benchmarks { + if isDomainName(tc.name) != tc.result { + b.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result) + } + } + } +} diff --git a/go/src/net/error_plan9.go b/go/src/net/error_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..caad133b774dc5c43e60a06fedb0502ea3948d9a --- /dev/null +++ b/go/src/net/error_plan9.go @@ -0,0 +1,9 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +func isConnError(err error) bool { + return false +} diff --git a/go/src/net/error_plan9_test.go b/go/src/net/error_plan9_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f86c96c0d2fbac145fa22f8f4983373e171e222f --- /dev/null +++ b/go/src/net/error_plan9_test.go @@ -0,0 +1,22 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "syscall" + +var ( + errOpNotSupported = syscall.EPLAN9 + + abortedConnRequestErrors []error +) + +func isPlatformError(err error) bool { + _, ok := err.(syscall.ErrorString) + return ok +} + +func isENOBUFS(err error) bool { + return false // ENOBUFS is Unix-specific +} diff --git a/go/src/net/error_posix.go b/go/src/net/error_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..84f80440454b37dd01d6e01f56c7422d2f63e15c --- /dev/null +++ b/go/src/net/error_posix.go @@ -0,0 +1,21 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 || windows + +package net + +import ( + "os" + "syscall" +) + +// wrapSyscallError takes an error and a syscall name. If the error is +// a syscall.Errno, it wraps it in an os.SyscallError using the syscall name. +func wrapSyscallError(name string, err error) error { + if _, ok := err.(syscall.Errno); ok { + err = os.NewSyscallError(name, err) + } + return err +} diff --git a/go/src/net/error_posix_test.go b/go/src/net/error_posix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..081176f771aebf72fa02563e862e82da678dc3f8 --- /dev/null +++ b/go/src/net/error_posix_test.go @@ -0,0 +1,34 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !plan9 + +package net + +import ( + "os" + "syscall" + "testing" +) + +func TestSpuriousENOTAVAIL(t *testing.T) { + for _, tt := range []struct { + error + ok bool + }{ + {syscall.EADDRNOTAVAIL, true}, + {&os.SyscallError{Syscall: "syscall", Err: syscall.EADDRNOTAVAIL}, true}, + {&OpError{Op: "op", Err: syscall.EADDRNOTAVAIL}, true}, + {&OpError{Op: "op", Err: &os.SyscallError{Syscall: "syscall", Err: syscall.EADDRNOTAVAIL}}, true}, + + {syscall.EINVAL, false}, + {&os.SyscallError{Syscall: "syscall", Err: syscall.EINVAL}, false}, + {&OpError{Op: "op", Err: syscall.EINVAL}, false}, + {&OpError{Op: "op", Err: &os.SyscallError{Syscall: "syscall", Err: syscall.EINVAL}}, false}, + } { + if ok := spuriousENOTAVAIL(tt.error); ok != tt.ok { + t.Errorf("spuriousENOTAVAIL(%v) = %v; want %v", tt.error, ok, tt.ok) + } + } +} diff --git a/go/src/net/error_test.go b/go/src/net/error_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8026144c3da7f523090f52c7829e956877b93baa --- /dev/null +++ b/go/src/net/error_test.go @@ -0,0 +1,818 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "errors" + "fmt" + "internal/poll" + "io" + "io/fs" + "net/internal/socktest" + "os" + "runtime" + "strings" + "testing" + "time" +) + +func (e *OpError) isValid() error { + if e.Op == "" { + return fmt.Errorf("OpError.Op is empty: %v", e) + } + if e.Net == "" { + return fmt.Errorf("OpError.Net is empty: %v", e) + } + for _, addr := range []Addr{e.Source, e.Addr} { + switch addr := addr.(type) { + case nil: + case *TCPAddr: + if addr == nil { + return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e) + } + case *UDPAddr: + if addr == nil { + return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e) + } + case *IPAddr: + if addr == nil { + return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e) + } + case *IPNet: + if addr == nil { + return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e) + } + case *UnixAddr: + if addr == nil { + return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e) + } + case *pipeAddr: + if addr == nil { + return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e) + } + case fileAddr: + if addr == "" { + return fmt.Errorf("OpError.Source or Addr is empty: %#v, %v", addr, e) + } + default: + return fmt.Errorf("OpError.Source or Addr is unknown type: %T, %v", addr, e) + } + } + if e.Err == nil { + return fmt.Errorf("OpError.Err is empty: %v", e) + } + return nil +} + +// parseDialError parses nestedErr and reports whether it is a valid +// error value from Dial, Listen functions. +// It returns nil when nestedErr is valid. +func parseDialError(nestedErr error) error { + if nestedErr == nil { + return nil + } + + switch err := nestedErr.(type) { + case *OpError: + if err := err.isValid(); err != nil { + return err + } + nestedErr = err.Err + goto second + } + return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) + +second: + if isPlatformError(nestedErr) { + return nil + } + switch err := nestedErr.(type) { + case *AddrError, *timeoutError, *DNSError, InvalidAddrError, *ParseError, *poll.DeadlineExceededError, UnknownNetworkError: + return nil + case interface{ isAddrinfoErrno() }: + return nil + case *os.SyscallError: + nestedErr = err.Err + goto third + case *fs.PathError: // for Plan 9 + nestedErr = err.Err + goto third + } + switch nestedErr { + case errCanceled, ErrClosed, errMissingAddress, errNoSuitableAddress, + context.DeadlineExceeded, context.Canceled: + return nil + } + return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr) + +third: + if isPlatformError(nestedErr) { + return nil + } + return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr) +} + +var dialErrorTests = []struct { + network, address string +}{ + {"foo", ""}, + {"bar", "baz"}, + {"datakit", "mh/astro/r70"}, + {"tcp", ""}, + {"tcp", "127.0.0.1:☺"}, + {"tcp", "no-such-name:80"}, + {"tcp", "mh/astro/r70:http"}, + + {"tcp", JoinHostPort("127.0.0.1", "-1")}, + {"tcp", JoinHostPort("127.0.0.1", "123456789")}, + {"udp", JoinHostPort("127.0.0.1", "-1")}, + {"udp", JoinHostPort("127.0.0.1", "123456789")}, + {"ip:icmp", "127.0.0.1"}, + + {"unix", "/path/to/somewhere"}, + {"unixgram", "/path/to/somewhere"}, + {"unixpacket", "/path/to/somewhere"}, +} + +func TestDialError(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("%s does not have full support of socktest", runtime.GOOS) + } + + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + return nil, &DNSError{Err: "dial error test", Name: "name", Server: "server", IsTimeout: true} + } + sw.Set(socktest.FilterConnect, func(so *socktest.Status) (socktest.AfterFilter, error) { + return nil, errOpNotSupported + }) + defer sw.Set(socktest.FilterConnect, nil) + + d := Dialer{Timeout: someTimeout} + for i, tt := range dialErrorTests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + c, err := d.Dial(tt.network, tt.address) + if err == nil { + t.Errorf("should fail; %s:%s->%s", c.LocalAddr().Network(), c.LocalAddr(), c.RemoteAddr()) + c.Close() + return + } + if tt.network == "tcp" || tt.network == "udp" { + nerr := err + if op, ok := nerr.(*OpError); ok { + nerr = op.Err + } + if sys, ok := nerr.(*os.SyscallError); ok { + nerr = sys.Err + } + if nerr == errOpNotSupported { + t.Fatalf("should fail without %v; %s:%s->", nerr, tt.network, tt.address) + } + } + if c != nil { + t.Errorf("Dial returned non-nil interface %T(%v) with err != nil", c, c) + } + if err = parseDialError(err); err != nil { + t.Error(err) + } + }) + } +} + +func TestProtocolDialError(t *testing.T) { + switch runtime.GOOS { + case "solaris", "illumos": + t.Skipf("not supported on %s", runtime.GOOS) + } + + for _, network := range []string{"tcp", "udp", "ip:4294967296", "unix", "unixpacket", "unixgram"} { + var err error + switch network { + case "tcp": + _, err = DialTCP(network, nil, &TCPAddr{Port: 1 << 16}) + case "udp": + _, err = DialUDP(network, nil, &UDPAddr{Port: 1 << 16}) + case "ip:4294967296": + _, err = DialIP(network, nil, nil) + case "unix", "unixpacket", "unixgram": + _, err = DialUnix(network, nil, &UnixAddr{Name: "//"}) + } + if err == nil { + t.Errorf("%s: should fail", network) + continue + } + if err := parseDialError(err); err != nil { + t.Errorf("%s: %v", network, err) + continue + } + t.Logf("%s: error as expected: %v", network, err) + } +} + +func TestDialAddrError(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + for _, tt := range []struct { + network string + lit string + addr *TCPAddr + }{ + {"tcp4", "::1", nil}, + {"tcp4", "", &TCPAddr{IP: IPv6loopback}}, + // We don't test the {"tcp6", "byte sequence", nil} + // case for now because there is no easy way to + // control name resolution. + {"tcp6", "", &TCPAddr{IP: IP{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}}}, + } { + desc := tt.lit + if desc == "" { + desc = tt.addr.String() + } + t.Run(fmt.Sprintf("%s/%s", tt.network, desc), func(t *testing.T) { + var err error + var c Conn + var op string + if tt.lit != "" { + c, err = Dial(tt.network, JoinHostPort(tt.lit, "0")) + op = fmt.Sprintf("Dial(%q, %q)", tt.network, JoinHostPort(tt.lit, "0")) + } else { + c, err = DialTCP(tt.network, nil, tt.addr) + op = fmt.Sprintf("DialTCP(%q, %q)", tt.network, tt.addr) + } + t.Logf("%s: %v", op, err) + if err == nil { + c.Close() + t.Fatalf("%s succeeded, want error", op) + } + if perr := parseDialError(err); perr != nil { + t.Fatal(perr) + } + operr := err.(*OpError).Err + aerr, ok := operr.(*AddrError) + if !ok { + t.Fatalf("OpError.Err is %T, want *AddrError", operr) + } + want := tt.lit + if tt.lit == "" { + want = tt.addr.IP.String() + } + if aerr.Addr != want { + t.Errorf("error Addr=%q, want %q", aerr.Addr, want) + } + }) + } +} + +var listenErrorTests = []struct { + network, address string +}{ + {"foo", ""}, + {"bar", "baz"}, + {"datakit", "mh/astro/r70"}, + {"tcp", "127.0.0.1:☺"}, + {"tcp", "no-such-name:80"}, + {"tcp", "mh/astro/r70:http"}, + + {"tcp", JoinHostPort("127.0.0.1", "-1")}, + {"tcp", JoinHostPort("127.0.0.1", "123456789")}, + + {"unix", "/path/to/somewhere"}, + {"unixpacket", "/path/to/somewhere"}, +} + +func TestListenError(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("%s does not have full support of socktest", runtime.GOOS) + } + + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = func(_ context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + return nil, &DNSError{Err: "listen error test", Name: "name", Server: "server", IsTimeout: true} + } + sw.Set(socktest.FilterListen, func(so *socktest.Status) (socktest.AfterFilter, error) { + return nil, errOpNotSupported + }) + defer sw.Set(socktest.FilterListen, nil) + + for i, tt := range listenErrorTests { + t.Run(fmt.Sprintf("%s_%s", tt.network, tt.address), func(t *testing.T) { + ln, err := Listen(tt.network, tt.address) + if err == nil { + t.Errorf("#%d: should fail; %s:%s->", i, ln.Addr().Network(), ln.Addr()) + ln.Close() + return + } + if tt.network == "tcp" { + nerr := err + if op, ok := nerr.(*OpError); ok { + nerr = op.Err + } + if sys, ok := nerr.(*os.SyscallError); ok { + nerr = sys.Err + } + if nerr == errOpNotSupported { + t.Fatalf("#%d: should fail without %v; %s:%s->", i, nerr, tt.network, tt.address) + } + } + if ln != nil { + t.Errorf("Listen returned non-nil interface %T(%v) with err != nil", ln, ln) + } + if err = parseDialError(err); err != nil { + t.Errorf("#%d: %v", i, err) + } + }) + } +} + +var listenPacketErrorTests = []struct { + network, address string +}{ + {"foo", ""}, + {"bar", "baz"}, + {"datakit", "mh/astro/r70"}, + {"udp", "127.0.0.1:☺"}, + {"udp", "no-such-name:80"}, + {"udp", "mh/astro/r70:http"}, + + {"udp", JoinHostPort("127.0.0.1", "-1")}, + {"udp", JoinHostPort("127.0.0.1", "123456789")}, +} + +func TestListenPacketError(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("%s does not have full support of socktest", runtime.GOOS) + } + + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = func(_ context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + return nil, &DNSError{Err: "listen error test", Name: "name", Server: "server", IsTimeout: true} + } + + for i, tt := range listenPacketErrorTests { + t.Run(fmt.Sprintf("%s_%s", tt.network, tt.address), func(t *testing.T) { + c, err := ListenPacket(tt.network, tt.address) + if err == nil { + t.Errorf("#%d: should fail; %s:%s->", i, c.LocalAddr().Network(), c.LocalAddr()) + c.Close() + return + } + if c != nil { + t.Errorf("ListenPacket returned non-nil interface %T(%v) with err != nil", c, c) + } + if err = parseDialError(err); err != nil { + t.Errorf("#%d: %v", i, err) + } + }) + } +} + +func TestProtocolListenError(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + for _, network := range []string{"tcp", "udp", "ip:4294967296", "unix", "unixpacket", "unixgram"} { + var err error + switch network { + case "tcp": + _, err = ListenTCP(network, &TCPAddr{Port: 1 << 16}) + case "udp": + _, err = ListenUDP(network, &UDPAddr{Port: 1 << 16}) + case "ip:4294967296": + _, err = ListenIP(network, nil) + case "unix", "unixpacket": + _, err = ListenUnix(network, &UnixAddr{Name: "//"}) + case "unixgram": + _, err = ListenUnixgram(network, &UnixAddr{Name: "//"}) + } + if err == nil { + t.Errorf("%s: should fail", network) + continue + } + if err = parseDialError(err); err != nil { + t.Errorf("%s: %v", network, err) + continue + } + } +} + +// parseReadError parses nestedErr and reports whether it is a valid +// error value from Read functions. +// It returns nil when nestedErr is valid. +func parseReadError(nestedErr error) error { + if nestedErr == nil { + return nil + } + + switch err := nestedErr.(type) { + case *OpError: + if err := err.isValid(); err != nil { + return err + } + nestedErr = err.Err + goto second + } + if nestedErr == io.EOF { + return nil + } + return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) + +second: + if isPlatformError(nestedErr) { + return nil + } + switch err := nestedErr.(type) { + case *os.SyscallError: + nestedErr = err.Err + goto third + } + switch nestedErr { + case ErrClosed, errTimeout, poll.ErrNotPollable, os.ErrDeadlineExceeded: + return nil + } + return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr) + +third: + if isPlatformError(nestedErr) { + return nil + } + return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr) +} + +// parseWriteError parses nestedErr and reports whether it is a valid +// error value from Write functions. +// It returns nil when nestedErr is valid. +func parseWriteError(nestedErr error) error { + if nestedErr == nil { + return nil + } + + switch err := nestedErr.(type) { + case *OpError: + if err := err.isValid(); err != nil { + return err + } + nestedErr = err.Err + goto second + } + return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) + +second: + if isPlatformError(nestedErr) { + return nil + } + switch err := nestedErr.(type) { + case *AddrError, *timeoutError, *DNSError, InvalidAddrError, *ParseError, *poll.DeadlineExceededError, UnknownNetworkError: + return nil + case interface{ isAddrinfoErrno() }: + return nil + case *os.SyscallError: + nestedErr = err.Err + goto third + } + switch nestedErr { + case errCanceled, ErrClosed, errMissingAddress, errTimeout, os.ErrDeadlineExceeded, ErrWriteToConnected, io.ErrUnexpectedEOF: + return nil + } + return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr) + +third: + if isPlatformError(nestedErr) { + return nil + } + return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr) +} + +// parseCloseError parses nestedErr and reports whether it is a valid +// error value from Close functions. +// It returns nil when nestedErr is valid. +func parseCloseError(nestedErr error, isShutdown bool) error { + if nestedErr == nil { + return nil + } + + // Because historically we have not exported the error that we + // return for an operation on a closed network connection, + // there are programs that test for the exact error string. + // Verify that string here so that we don't break those + // programs unexpectedly. See issues #4373 and #19252. + want := "use of closed network connection" + if !isShutdown && !strings.Contains(nestedErr.Error(), want) { + return fmt.Errorf("error string %q does not contain expected string %q", nestedErr, want) + } + + if !isShutdown && !errors.Is(nestedErr, ErrClosed) { + return fmt.Errorf("errors.Is(%v, errClosed) returns false, want true", nestedErr) + } + + switch err := nestedErr.(type) { + case *OpError: + if err := err.isValid(); err != nil { + return err + } + nestedErr = err.Err + goto second + } + return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) + +second: + if isPlatformError(nestedErr) { + return nil + } + switch err := nestedErr.(type) { + case *os.SyscallError: + nestedErr = err.Err + goto third + case *fs.PathError: // for Plan 9 + nestedErr = err.Err + goto third + } + switch nestedErr { + case ErrClosed: + return nil + } + return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr) + +third: + if isPlatformError(nestedErr) { + return nil + } + switch nestedErr { + case fs.ErrClosed: // for Plan 9 + return nil + } + return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr) +} + +func TestCloseError(t *testing.T) { + t.Run("tcp", func(t *testing.T) { + ln := newLocalListener(t, "tcp") + defer ln.Close() + c, err := Dial(ln.Addr().Network(), ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + + for i := 0; i < 3; i++ { + err = c.(*TCPConn).CloseRead() + if perr := parseCloseError(err, true); perr != nil { + t.Errorf("#%d: %v", i, perr) + } + } + for i := 0; i < 3; i++ { + err = c.(*TCPConn).CloseWrite() + if perr := parseCloseError(err, true); perr != nil { + t.Errorf("#%d: %v", i, perr) + } + } + for i := 0; i < 3; i++ { + err = c.Close() + if perr := parseCloseError(err, false); perr != nil { + t.Errorf("#%d: %v", i, perr) + } + err = ln.Close() + if perr := parseCloseError(err, false); perr != nil { + t.Errorf("#%d: %v", i, perr) + } + } + }) + + t.Run("udp", func(t *testing.T) { + if !testableNetwork("udp") { + t.Skipf("skipping: udp not available") + } + + pc, err := ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer pc.Close() + + for i := 0; i < 3; i++ { + err = pc.Close() + if perr := parseCloseError(err, false); perr != nil { + t.Errorf("#%d: %v", i, perr) + } + } + }) +} + +// parseAcceptError parses nestedErr and reports whether it is a valid +// error value from Accept functions. +// It returns nil when nestedErr is valid. +func parseAcceptError(nestedErr error) error { + if nestedErr == nil { + return nil + } + + switch err := nestedErr.(type) { + case *OpError: + if err := err.isValid(); err != nil { + return err + } + nestedErr = err.Err + goto second + } + return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) + +second: + if isPlatformError(nestedErr) { + return nil + } + switch err := nestedErr.(type) { + case *os.SyscallError: + nestedErr = err.Err + goto third + case *fs.PathError: // for Plan 9 + nestedErr = err.Err + goto third + } + switch nestedErr { + case ErrClosed, errTimeout, poll.ErrNotPollable, os.ErrDeadlineExceeded: + return nil + } + return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr) + +third: + if isPlatformError(nestedErr) { + return nil + } + return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr) +} + +func TestAcceptError(t *testing.T) { + handler := func(ls *localServer, ln Listener) { + for { + ln.(*TCPListener).SetDeadline(time.Now().Add(5 * time.Millisecond)) + c, err := ln.Accept() + if perr := parseAcceptError(err); perr != nil { + t.Error(perr) + } + if err != nil { + if c != nil { + t.Errorf("Accept returned non-nil interface %T(%v) with err != nil", c, c) + } + if nerr, ok := err.(Error); !ok || (!nerr.Timeout() && !nerr.Temporary()) { + return + } + continue + } + c.Close() + } + } + ls := newLocalServer(t, "tcp") + if err := ls.buildup(handler); err != nil { + ls.teardown() + t.Fatal(err) + } + + time.Sleep(100 * time.Millisecond) + ls.teardown() +} + +// parseCommonError parses nestedErr and reports whether it is a valid +// error value from miscellaneous functions. +// It returns nil when nestedErr is valid. +func parseCommonError(nestedErr error) error { + if nestedErr == nil { + return nil + } + + switch err := nestedErr.(type) { + case *OpError: + if err := err.isValid(); err != nil { + return err + } + nestedErr = err.Err + goto second + } + return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) + +second: + if isPlatformError(nestedErr) { + return nil + } + switch err := nestedErr.(type) { + case *os.SyscallError: + nestedErr = err.Err + goto third + case *os.LinkError: + nestedErr = err.Err + goto third + case *fs.PathError: + nestedErr = err.Err + goto third + } + switch nestedErr { + case ErrClosed: + return nil + } + return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr) + +third: + if isPlatformError(nestedErr) { + return nil + } + return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr) +} + +func TestFileError(t *testing.T) { + f, err := os.CreateTemp("", "go-nettest") + if err != nil { + t.Fatal(err) + } + defer os.Remove(f.Name()) + defer f.Close() + + c, err := FileConn(f) + if err != nil { + if c != nil { + t.Errorf("FileConn returned non-nil interface %T(%v) with err != nil", c, c) + } + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + } else { + c.Close() + t.Error("should fail") + } + ln, err := FileListener(f) + if err != nil { + if ln != nil { + t.Errorf("FileListener returned non-nil interface %T(%v) with err != nil", ln, ln) + } + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + } else { + ln.Close() + t.Error("should fail") + } + pc, err := FilePacketConn(f) + if err != nil { + if pc != nil { + t.Errorf("FilePacketConn returned non-nil interface %T(%v) with err != nil", pc, pc) + } + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + } else { + pc.Close() + t.Error("should fail") + } + + ln = newLocalListener(t, "tcp") + + for i := 0; i < 3; i++ { + f, err := ln.(*TCPListener).File() + if err != nil { + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + } else { + f.Close() + } + ln.Close() + } +} + +func parseLookupPortError(nestedErr error) error { + if nestedErr == nil { + return nil + } + + switch nestedErr.(type) { + case *AddrError, *DNSError: + return nil + case *fs.PathError: // for Plan 9 + return nil + } + return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) +} + +func TestContextError(t *testing.T) { + if !errors.Is(errCanceled, context.Canceled) { + t.Error("errCanceled is not context.Canceled") + } + if !errors.Is(errTimeout, context.DeadlineExceeded) { + t.Error("errTimeout is not context.DeadlineExceeded") + } +} diff --git a/go/src/net/error_unix.go b/go/src/net/error_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..d6948670b6a305606753214e3f0398b5f4b6df9a --- /dev/null +++ b/go/src/net/error_unix.go @@ -0,0 +1,16 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 + +package net + +import "syscall" + +func isConnError(err error) bool { + if se, ok := err.(syscall.Errno); ok { + return se == syscall.ECONNRESET || se == syscall.ECONNABORTED + } + return false +} diff --git a/go/src/net/error_unix_test.go b/go/src/net/error_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..963ba21f1a0ac1dd6ba05fe8886a258bdda6ee8d --- /dev/null +++ b/go/src/net/error_unix_test.go @@ -0,0 +1,38 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !plan9 && !windows + +package net + +import ( + "errors" + "os" + "syscall" +) + +var ( + errOpNotSupported = syscall.EOPNOTSUPP + + abortedConnRequestErrors = []error{syscall.ECONNABORTED} // see accept in fd_unix.go +) + +func isPlatformError(err error) bool { + _, ok := err.(syscall.Errno) + return ok +} + +func samePlatformError(err, want error) bool { + if op, ok := err.(*OpError); ok { + err = op.Err + } + if sys, ok := err.(*os.SyscallError); ok { + err = sys.Err + } + return err == want +} + +func isENOBUFS(err error) bool { + return errors.Is(err, syscall.ENOBUFS) +} diff --git a/go/src/net/error_windows.go b/go/src/net/error_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..570b97b278b7f90a46cdaadb74d73de3a1f45def --- /dev/null +++ b/go/src/net/error_windows.go @@ -0,0 +1,14 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "syscall" + +func isConnError(err error) bool { + if se, ok := err.(syscall.Errno); ok { + return se == syscall.WSAECONNRESET || se == syscall.WSAECONNABORTED + } + return false +} diff --git a/go/src/net/error_windows_test.go b/go/src/net/error_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7847af055160f332b06062dc7a6eb921efeb0b34 --- /dev/null +++ b/go/src/net/error_windows_test.go @@ -0,0 +1,28 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "syscall" +) + +var ( + errOpNotSupported = syscall.EOPNOTSUPP + + abortedConnRequestErrors = []error{syscall.ERROR_NETNAME_DELETED, syscall.WSAECONNRESET} // see accept in fd_windows.go +) + +func isPlatformError(err error) bool { + _, ok := err.(syscall.Errno) + return ok +} + +func isENOBUFS(err error) bool { + // syscall.ENOBUFS is a completely made-up value on Windows: we don't expect + // a real system call to ever actually return it. However, since it is already + // defined in the syscall package we may as well check for it. + return errors.Is(err, syscall.ENOBUFS) +} diff --git a/go/src/net/example_test.go b/go/src/net/example_test.go new file mode 100644 index 0000000000000000000000000000000000000000..12c83970940ab0647faa03d67592a61c9afbb275 --- /dev/null +++ b/go/src/net/example_test.go @@ -0,0 +1,387 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net_test + +import ( + "context" + "fmt" + "io" + "log" + "net" + "time" +) + +func ExampleListener() { + // Listen on TCP port 2000 on all available unicast and + // anycast IP addresses of the local system. + l, err := net.Listen("tcp", ":2000") + if err != nil { + log.Fatal(err) + } + defer l.Close() + for { + // Wait for a connection. + conn, err := l.Accept() + if err != nil { + log.Fatal(err) + } + // Handle the connection in a new goroutine. + // The loop then returns to accepting, so that + // multiple connections may be served concurrently. + go func(c net.Conn) { + // Echo all incoming data. + io.Copy(c, c) + // Shut down the connection. + c.Close() + }(conn) + } +} + +func ExampleDialer() { + var d net.Dialer + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + + conn, err := d.DialContext(ctx, "tcp", "localhost:12345") + if err != nil { + log.Fatalf("Failed to dial: %v", err) + } + defer conn.Close() + + if _, err := conn.Write([]byte("Hello, World!")); err != nil { + log.Fatal(err) + } +} + +func ExampleDialer_unix() { + // DialUnix does not take a context.Context parameter. This example shows + // how to dial a Unix socket with a Context. Note that the Context only + // applies to the dial operation; it does not apply to the connection once + // it has been established. + var d net.Dialer + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + + d.LocalAddr = nil // if you have a local addr, add it here + raddr := net.UnixAddr{Name: "/path/to/unix.sock", Net: "unix"} + conn, err := d.DialContext(ctx, "unix", raddr.String()) + if err != nil { + log.Fatalf("Failed to dial: %v", err) + } + defer conn.Close() + if _, err := conn.Write([]byte("Hello, socket!")); err != nil { + log.Fatal(err) + } +} + +func ExampleIPv4() { + fmt.Println(net.IPv4(8, 8, 8, 8)) + + // Output: + // 8.8.8.8 +} + +func ExampleParseCIDR() { + ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24") + if err != nil { + log.Fatal(err) + } + fmt.Println(ipv4Addr) + fmt.Println(ipv4Net) + + ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32") + if err != nil { + log.Fatal(err) + } + fmt.Println(ipv6Addr) + fmt.Println(ipv6Net) + + // Output: + // 192.0.2.1 + // 192.0.2.0/24 + // 2001:db8:a0b:12f0::1 + // 2001:db8::/32 +} + +func ExampleParseIP() { + fmt.Println(net.ParseIP("192.0.2.1")) + fmt.Println(net.ParseIP("2001:db8::68")) + fmt.Println(net.ParseIP("192.0.2")) + + // Output: + // 192.0.2.1 + // 2001:db8::68 + // +} + +func ExampleIP_DefaultMask() { + ip := net.ParseIP("192.0.2.1") + fmt.Println(ip.DefaultMask()) + + // Output: + // ffffff00 +} + +func ExampleIP_Equal() { + ipv4DNS := net.ParseIP("8.8.8.8") + ipv4Lo := net.ParseIP("127.0.0.1") + ipv6DNS := net.ParseIP("0:0:0:0:0:FFFF:0808:0808") + + fmt.Println(ipv4DNS.Equal(ipv4DNS)) + fmt.Println(ipv4DNS.Equal(ipv4Lo)) + fmt.Println(ipv4DNS.Equal(ipv6DNS)) + + // Output: + // true + // false + // true +} + +func ExampleIP_IsGlobalUnicast() { + ipv6Global := net.ParseIP("2000::") + ipv6UniqLocal := net.ParseIP("2000::") + ipv6Multi := net.ParseIP("FF00::") + + ipv4Private := net.ParseIP("10.255.0.0") + ipv4Public := net.ParseIP("8.8.8.8") + ipv4Broadcast := net.ParseIP("255.255.255.255") + + fmt.Println(ipv6Global.IsGlobalUnicast()) + fmt.Println(ipv6UniqLocal.IsGlobalUnicast()) + fmt.Println(ipv6Multi.IsGlobalUnicast()) + + fmt.Println(ipv4Private.IsGlobalUnicast()) + fmt.Println(ipv4Public.IsGlobalUnicast()) + fmt.Println(ipv4Broadcast.IsGlobalUnicast()) + + // Output: + // true + // true + // false + // true + // true + // false +} + +func ExampleIP_IsInterfaceLocalMulticast() { + ipv6InterfaceLocalMulti := net.ParseIP("ff01::1") + ipv6Global := net.ParseIP("2000::") + ipv4 := net.ParseIP("255.0.0.0") + + fmt.Println(ipv6InterfaceLocalMulti.IsInterfaceLocalMulticast()) + fmt.Println(ipv6Global.IsInterfaceLocalMulticast()) + fmt.Println(ipv4.IsInterfaceLocalMulticast()) + + // Output: + // true + // false + // false +} + +func ExampleIP_IsLinkLocalMulticast() { + ipv6LinkLocalMulti := net.ParseIP("ff02::2") + ipv6LinkLocalUni := net.ParseIP("fe80::") + ipv4LinkLocalMulti := net.ParseIP("224.0.0.0") + ipv4LinkLocalUni := net.ParseIP("169.254.0.0") + + fmt.Println(ipv6LinkLocalMulti.IsLinkLocalMulticast()) + fmt.Println(ipv6LinkLocalUni.IsLinkLocalMulticast()) + fmt.Println(ipv4LinkLocalMulti.IsLinkLocalMulticast()) + fmt.Println(ipv4LinkLocalUni.IsLinkLocalMulticast()) + + // Output: + // true + // false + // true + // false +} + +func ExampleIP_IsLinkLocalUnicast() { + ipv6LinkLocalUni := net.ParseIP("fe80::") + ipv6Global := net.ParseIP("2000::") + ipv4LinkLocalUni := net.ParseIP("169.254.0.0") + ipv4LinkLocalMulti := net.ParseIP("224.0.0.0") + + fmt.Println(ipv6LinkLocalUni.IsLinkLocalUnicast()) + fmt.Println(ipv6Global.IsLinkLocalUnicast()) + fmt.Println(ipv4LinkLocalUni.IsLinkLocalUnicast()) + fmt.Println(ipv4LinkLocalMulti.IsLinkLocalUnicast()) + + // Output: + // true + // false + // true + // false +} + +func ExampleIP_IsLoopback() { + ipv6Lo := net.ParseIP("::1") + ipv6 := net.ParseIP("ff02::1") + ipv4Lo := net.ParseIP("127.0.0.0") + ipv4 := net.ParseIP("128.0.0.0") + + fmt.Println(ipv6Lo.IsLoopback()) + fmt.Println(ipv6.IsLoopback()) + fmt.Println(ipv4Lo.IsLoopback()) + fmt.Println(ipv4.IsLoopback()) + + // Output: + // true + // false + // true + // false +} + +func ExampleIP_IsMulticast() { + ipv6Multi := net.ParseIP("FF00::") + ipv6LinkLocalMulti := net.ParseIP("ff02::1") + ipv6Lo := net.ParseIP("::1") + ipv4Multi := net.ParseIP("239.0.0.0") + ipv4LinkLocalMulti := net.ParseIP("224.0.0.0") + ipv4Lo := net.ParseIP("127.0.0.0") + + fmt.Println(ipv6Multi.IsMulticast()) + fmt.Println(ipv6LinkLocalMulti.IsMulticast()) + fmt.Println(ipv6Lo.IsMulticast()) + fmt.Println(ipv4Multi.IsMulticast()) + fmt.Println(ipv4LinkLocalMulti.IsMulticast()) + fmt.Println(ipv4Lo.IsMulticast()) + + // Output: + // true + // true + // false + // true + // true + // false +} + +func ExampleIP_IsPrivate() { + ipv6Private := net.ParseIP("fc00::") + ipv6Public := net.ParseIP("fe00::") + ipv4Private := net.ParseIP("10.255.0.0") + ipv4Public := net.ParseIP("11.0.0.0") + + fmt.Println(ipv6Private.IsPrivate()) + fmt.Println(ipv6Public.IsPrivate()) + fmt.Println(ipv4Private.IsPrivate()) + fmt.Println(ipv4Public.IsPrivate()) + + // Output: + // true + // false + // true + // false +} + +func ExampleIP_IsUnspecified() { + ipv6Unspecified := net.ParseIP("::") + ipv6Specified := net.ParseIP("fe00::") + ipv4Unspecified := net.ParseIP("0.0.0.0") + ipv4Specified := net.ParseIP("8.8.8.8") + + fmt.Println(ipv6Unspecified.IsUnspecified()) + fmt.Println(ipv6Specified.IsUnspecified()) + fmt.Println(ipv4Unspecified.IsUnspecified()) + fmt.Println(ipv4Specified.IsUnspecified()) + + // Output: + // true + // false + // true + // false +} + +func ExampleIP_Mask() { + ipv4Addr := net.ParseIP("192.0.2.1") + // This mask corresponds to a /24 subnet for IPv4. + ipv4Mask := net.CIDRMask(24, 32) + fmt.Println(ipv4Addr.Mask(ipv4Mask)) + + ipv6Addr := net.ParseIP("2001:db8:a0b:12f0::1") + // This mask corresponds to a /32 subnet for IPv6. + ipv6Mask := net.CIDRMask(32, 128) + fmt.Println(ipv6Addr.Mask(ipv6Mask)) + + // Output: + // 192.0.2.0 + // 2001:db8:: +} + +func ExampleIP_String() { + ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + ipv4 := net.IPv4(10, 255, 0, 0) + + fmt.Println(ipv6.String()) + fmt.Println(ipv4.String()) + + // Output: + // fc00:: + // 10.255.0.0 +} + +func ExampleIP_To16() { + ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + ipv4 := net.IPv4(10, 255, 0, 0) + + fmt.Println(ipv6.To16()) + fmt.Println(ipv4.To16()) + + // Output: + // fc00:: + // 10.255.0.0 +} + +func ExampleIP_To4() { + ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + ipv4 := net.IPv4(10, 255, 0, 0) + + fmt.Println(ipv6.To4()) + fmt.Println(ipv4.To4()) + + // Output: + // + // 10.255.0.0 +} + +func ExampleCIDRMask() { + // This mask corresponds to a /31 subnet for IPv4. + fmt.Println(net.CIDRMask(31, 32)) + + // This mask corresponds to a /64 subnet for IPv6. + fmt.Println(net.CIDRMask(64, 128)) + + // Output: + // fffffffe + // ffffffffffffffff0000000000000000 +} + +func ExampleIPv4Mask() { + fmt.Println(net.IPv4Mask(255, 255, 255, 0)) + + // Output: + // ffffff00 +} + +func ExampleUDPConn_WriteTo() { + // Unlike Dial, ListenPacket creates a connection without any + // association with peers. + conn, err := net.ListenPacket("udp", ":0") + if err != nil { + log.Fatal(err) + } + defer conn.Close() + + dst, err := net.ResolveUDPAddr("udp", "192.0.2.1:2000") + if err != nil { + log.Fatal(err) + } + + // The connection can write data to the desired address. + _, err = conn.WriteTo([]byte("data"), dst) + if err != nil { + log.Fatal(err) + } +} diff --git a/go/src/net/external_test.go b/go/src/net/external_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9b918f8986a1f5ad813629918fbd142c0bb37d3a --- /dev/null +++ b/go/src/net/external_test.go @@ -0,0 +1,165 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "fmt" + "internal/testenv" + "io" + "strings" + "testing" +) + +func TestResolveGoogle(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 { + t.Skip("both IPv4 and IPv6 are required") + } + + for _, network := range []string{"tcp", "tcp4", "tcp6"} { + addr, err := ResolveTCPAddr(network, "www.google.com:http") + if err != nil { + t.Error(err) + continue + } + switch { + case network == "tcp" && addr.IP.To4() == nil: + fallthrough + case network == "tcp4" && addr.IP.To4() == nil: + t.Errorf("got %v; want an IPv4 address on %s", addr, network) + case network == "tcp6" && (addr.IP.To16() == nil || addr.IP.To4() != nil): + t.Errorf("got %v; want an IPv6 address on %s", addr, network) + } + } +} + +var dialGoogleTests = []struct { + dial func(string, string) (Conn, error) + unreachableNetwork string + networks []string + addrs []string +}{ + { + dial: (&Dialer{DualStack: true}).Dial, + networks: []string{"tcp", "tcp4", "tcp6"}, + addrs: []string{"www.google.com:http"}, + }, + { + dial: Dial, + unreachableNetwork: "tcp6", + networks: []string{"tcp", "tcp4"}, + }, + { + dial: Dial, + unreachableNetwork: "tcp4", + networks: []string{"tcp", "tcp6"}, + }, +} + +func TestDialGoogle(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 { + t.Skip("both IPv4 and IPv6 are required") + } + + var err error + dialGoogleTests[1].addrs, dialGoogleTests[2].addrs, err = googleLiteralAddrs() + if err != nil { + t.Error(err) + } + for _, tt := range dialGoogleTests { + for _, network := range tt.networks { + disableSocketConnect(tt.unreachableNetwork) + for _, addr := range tt.addrs { + if err := fetchGoogle(tt.dial, network, addr); err != nil { + t.Error(err) + } + } + enableSocketConnect() + } + } +} + +var ( + literalAddrs4 = [...]string{ + "%d.%d.%d.%d:80", + "www.google.com:80", + "%d.%d.%d.%d:http", + "www.google.com:http", + "[::ffff:%d.%d.%d.%d]:80", + "[::ffff:%02x%02x:%02x%02x]:80", + "[0:0:0:0:0000:ffff:%d.%d.%d.%d]:80", + "[0:0:0:0:000000:ffff:%d.%d.%d.%d]:80", + "[0:0:0:0::ffff:%d.%d.%d.%d]:80", + } + literalAddrs6 = [...]string{ + "[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]:80", + "ipv6.google.com:80", + "[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]:http", + "ipv6.google.com:http", + } +) + +func googleLiteralAddrs() (lits4, lits6 []string, err error) { + ips, err := LookupIP("www.google.com") + if err != nil { + return nil, nil, err + } + if len(ips) == 0 { + return nil, nil, nil + } + var ip4, ip6 IP + for _, ip := range ips { + if ip4 == nil && ip.To4() != nil { + ip4 = ip.To4() + } + if ip6 == nil && ip.To16() != nil && ip.To4() == nil { + ip6 = ip.To16() + } + if ip4 != nil && ip6 != nil { + break + } + } + if ip4 != nil { + for i, lit4 := range literalAddrs4 { + if strings.Contains(lit4, "%") { + literalAddrs4[i] = fmt.Sprintf(lit4, ip4[0], ip4[1], ip4[2], ip4[3]) + } + } + lits4 = literalAddrs4[:] + } + if ip6 != nil { + for i, lit6 := range literalAddrs6 { + if strings.Contains(lit6, "%") { + literalAddrs6[i] = fmt.Sprintf(lit6, ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7], ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15]) + } + } + lits6 = literalAddrs6[:] + } + return +} + +func fetchGoogle(dial func(string, string) (Conn, error), network, address string) error { + c, err := dial(network, address) + if err != nil { + return err + } + defer c.Close() + req := []byte("GET /robots.txt HTTP/1.0\r\nHost: www.google.com\r\n\r\n") + if _, err := c.Write(req); err != nil { + return err + } + b := make([]byte, 1000) + n, err := io.ReadFull(c, b) + if err != nil { + return err + } + if n < 1000 { + return fmt.Errorf("short read from %s:%s->%s", network, c.RemoteAddr(), c.LocalAddr()) + } + return nil +} diff --git a/go/src/net/fd_fake.go b/go/src/net/fd_fake.go new file mode 100644 index 0000000000000000000000000000000000000000..946805ab940b7a2c49f42113759759501dbb70d2 --- /dev/null +++ b/go/src/net/fd_fake.go @@ -0,0 +1,171 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js || wasip1 + +package net + +import ( + "internal/poll" + "runtime" + "time" +) + +const ( + readSyscallName = "fd_read" + writeSyscallName = "fd_write" +) + +// Network file descriptor. +type netFD struct { + pfd poll.FD + + // immutable until Close + family int + sotype int + isConnected bool // handshake completed or use of association with peer + net string + laddr Addr + raddr Addr + + // The only networking available in WASI preview 1 is the ability to + // sock_accept on a pre-opened socket, and then fd_read, fd_write, + // fd_close, and sock_shutdown on the resulting connection. We + // intercept applicable netFD calls on this instance, and then pass + // the remainder of the netFD calls to fakeNetFD. + *fakeNetFD +} + +func newFD(net string, sysfd int) *netFD { + return newPollFD(net, poll.FD{ + Sysfd: sysfd, + IsStream: true, + ZeroReadIsEOF: true, + }) +} + +func newPollFD(net string, pfd poll.FD) *netFD { + var laddr Addr + var raddr Addr + // WASI preview 1 does not have functions like getsockname/getpeername, + // so we cannot get access to the underlying IP address used by connections. + // + // However, listeners created by FileListener are of type *TCPListener, + // which can be asserted by a Go program. The (*TCPListener).Addr method + // documents that the returned value will be of type *TCPAddr, we satisfy + // the documented behavior by creating addresses of the expected type here. + switch net { + case "tcp": + laddr = new(TCPAddr) + raddr = new(TCPAddr) + case "udp": + laddr = new(UDPAddr) + raddr = new(UDPAddr) + default: + laddr = unknownAddr{} + raddr = unknownAddr{} + } + return &netFD{ + pfd: pfd, + net: net, + laddr: laddr, + raddr: raddr, + } +} + +func (fd *netFD) init() error { + return fd.pfd.Init(fd.net, true) +} + +func (fd *netFD) name() string { + return "unknown" +} + +func (fd *netFD) accept() (netfd *netFD, err error) { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.accept(fd.laddr) + } + d, _, errcall, err := fd.pfd.Accept() + if err != nil { + if errcall != "" { + err = wrapSyscallError(errcall, err) + } + return nil, err + } + netfd = newFD("tcp", d) + if err = netfd.init(); err != nil { + netfd.Close() + return nil, err + } + return netfd, nil +} + +func (fd *netFD) setAddr(laddr, raddr Addr) { + fd.laddr = laddr + fd.raddr = raddr + // TODO Replace with runtime.AddCleanup. + runtime.SetFinalizer(fd, (*netFD).Close) +} + +func (fd *netFD) Close() error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.Close() + } + // TODO Replace with runtime.AddCleanup. + runtime.SetFinalizer(fd, nil) + return fd.pfd.Close() +} + +func (fd *netFD) shutdown(how int) error { + if fd.fakeNetFD != nil { + return nil + } + err := fd.pfd.Shutdown(how) + runtime.KeepAlive(fd) + return wrapSyscallError("shutdown", err) +} + +func (fd *netFD) Read(p []byte) (n int, err error) { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.Read(p) + } + n, err = fd.pfd.Read(p) + runtime.KeepAlive(fd) + return n, wrapSyscallError(readSyscallName, err) +} + +func (fd *netFD) Write(p []byte) (nn int, err error) { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.Write(p) + } + nn, err = fd.pfd.Write(p) + runtime.KeepAlive(fd) + return nn, wrapSyscallError(writeSyscallName, err) +} + +func (fd *netFD) SetDeadline(t time.Time) error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.SetDeadline(t) + } + return fd.pfd.SetDeadline(t) +} + +func (fd *netFD) SetReadDeadline(t time.Time) error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.SetReadDeadline(t) + } + return fd.pfd.SetReadDeadline(t) +} + +func (fd *netFD) SetWriteDeadline(t time.Time) error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.SetWriteDeadline(t) + } + return fd.pfd.SetWriteDeadline(t) +} + +type unknownAddr struct{} + +func (unknownAddr) Network() string { return "unknown" } +func (unknownAddr) String() string { return "unknown" } diff --git a/go/src/net/fd_js.go b/go/src/net/fd_js.go new file mode 100644 index 0000000000000000000000000000000000000000..0fce036ef13c1cef33a1d603397801c1c4ec5553 --- /dev/null +++ b/go/src/net/fd_js.go @@ -0,0 +1,28 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Fake networking for js/wasm. It is intended to allow tests of other package to pass. + +//go:build js + +package net + +import ( + "os" + "syscall" +) + +func (fd *netFD) closeRead() error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.closeRead() + } + return os.NewSyscallError("closeRead", syscall.ENOTSUP) +} + +func (fd *netFD) closeWrite() error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.closeWrite() + } + return os.NewSyscallError("closeRead", syscall.ENOTSUP) +} diff --git a/go/src/net/fd_plan9.go b/go/src/net/fd_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..66a12e7d7dabdc2c886925f6b0486f2413d72fa3 --- /dev/null +++ b/go/src/net/fd_plan9.go @@ -0,0 +1,192 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/poll" + "io" + "os" + "syscall" + "time" +) + +// Network file descriptor. +type netFD struct { + pfd poll.FD + + // immutable until Close + net string + n string + dir string + listen, ctl, data *os.File + laddr, raddr Addr + isStream bool +} + +var netdir = "/net" // default network + +func newFD(net, name string, listen, ctl, data *os.File, laddr, raddr Addr) (*netFD, error) { + ret := &netFD{ + net: net, + n: name, + dir: netdir + "/" + net + "/" + name, + listen: listen, + ctl: ctl, data: data, + laddr: laddr, + raddr: raddr, + } + ret.pfd.Destroy = ret.destroy + return ret, nil +} + +func (fd *netFD) init() error { + // stub for future fd.pd.Init(fd) + return nil +} + +func (fd *netFD) name() string { + var ls, rs string + if fd.laddr != nil { + ls = fd.laddr.String() + } + if fd.raddr != nil { + rs = fd.raddr.String() + } + return fd.net + ":" + ls + "->" + rs +} + +func (fd *netFD) ok() bool { return fd != nil && fd.ctl != nil } + +func (fd *netFD) destroy() { + if !fd.ok() { + return + } + err := fd.ctl.Close() + if fd.data != nil { + if err1 := fd.data.Close(); err1 != nil && err == nil { + err = err1 + } + } + if fd.listen != nil { + if err1 := fd.listen.Close(); err1 != nil && err == nil { + err = err1 + } + } + fd.ctl = nil + fd.data = nil + fd.listen = nil +} + +func (fd *netFD) Read(b []byte) (n int, err error) { + if !fd.ok() || fd.data == nil { + return 0, syscall.EINVAL + } + n, err = fd.pfd.Read(fd.data.Read, b) + if fd.net == "udp" && err == io.EOF { + n = 0 + err = nil + } + return +} + +func (fd *netFD) Write(b []byte) (n int, err error) { + if !fd.ok() || fd.data == nil { + return 0, syscall.EINVAL + } + return fd.pfd.Write(fd.data.Write, b) +} + +func (fd *netFD) closeRead() error { + if !fd.ok() { + return syscall.EINVAL + } + return syscall.EPLAN9 +} + +func (fd *netFD) closeWrite() error { + if !fd.ok() { + return syscall.EINVAL + } + return syscall.EPLAN9 +} + +func (fd *netFD) Close() error { + if err := fd.pfd.Close(); err != nil { + return err + } + if !fd.ok() { + return syscall.EINVAL + } + if fd.net == "tcp" { + // The following line is required to unblock Reads. + _, err := fd.ctl.WriteString("close") + if err != nil { + return err + } + } + if fd.net == "udp" { + // The following line is required to unblock Reads. + // See https://go.dev/issue/72770. + fd.SetReadDeadline(time.Now().Add(-time.Hour)) + } + err := fd.ctl.Close() + if fd.data != nil { + if err1 := fd.data.Close(); err1 != nil && err == nil { + err = err1 + } + } + if fd.listen != nil { + if err1 := fd.listen.Close(); err1 != nil && err == nil { + err = err1 + } + } + fd.ctl = nil + fd.data = nil + fd.listen = nil + return err +} + +// This method is only called via Conn. +func (fd *netFD) dup() (*os.File, error) { + if !fd.ok() || fd.data == nil { + return nil, syscall.EINVAL + } + return fd.file(fd.data, fd.dir+"/data") +} + +func (l *TCPListener) dup() (*os.File, error) { + if !l.fd.ok() { + return nil, syscall.EINVAL + } + return l.fd.file(l.fd.ctl, l.fd.dir+"/ctl") +} + +func (fd *netFD) file(f *os.File, s string) (*os.File, error) { + dfd, err := syscall.Dup(int(f.Fd()), -1) + if err != nil { + return nil, os.NewSyscallError("dup", err) + } + return os.NewFile(uintptr(dfd), s), nil +} + +func setReadBuffer(fd *netFD, bytes int) error { + return syscall.EPLAN9 +} + +func setWriteBuffer(fd *netFD, bytes int) error { + return syscall.EPLAN9 +} + +func (fd *netFD) SetDeadline(t time.Time) error { + return fd.pfd.SetDeadline(t) +} + +func (fd *netFD) SetReadDeadline(t time.Time) error { + return fd.pfd.SetReadDeadline(t) +} + +func (fd *netFD) SetWriteDeadline(t time.Time) error { + return fd.pfd.SetWriteDeadline(t) +} diff --git a/go/src/net/fd_posix.go b/go/src/net/fd_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..023cd534e4206fe8a21c6f44dc8f10403b6b4a63 --- /dev/null +++ b/go/src/net/fd_posix.go @@ -0,0 +1,160 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || windows + +package net + +import ( + "internal/poll" + "runtime" + "syscall" + "time" +) + +// Network file descriptor. +type netFD struct { + pfd poll.FD + + // immutable until Close + family int + sotype int + isConnected bool // handshake completed or use of association with peer + net string + laddr Addr + raddr Addr +} + +func (fd *netFD) name() string { + var ls, rs string + if fd.laddr != nil { + ls = fd.laddr.String() + } + if fd.raddr != nil { + rs = fd.raddr.String() + } + return fd.net + ":" + ls + "->" + rs +} + +func (fd *netFD) setAddr(laddr, raddr Addr) { + fd.laddr = laddr + fd.raddr = raddr + // TODO Replace with runtime.AddCleanup. + runtime.SetFinalizer(fd, (*netFD).Close) +} + +func (fd *netFD) Close() error { + // TODO Replace with runtime.AddCleanup. + runtime.SetFinalizer(fd, nil) + return fd.pfd.Close() +} + +func (fd *netFD) shutdown(how int) error { + err := fd.pfd.Shutdown(how) + runtime.KeepAlive(fd) + return wrapSyscallError("shutdown", err) +} + +func (fd *netFD) closeRead() error { + return fd.shutdown(syscall.SHUT_RD) +} + +func (fd *netFD) closeWrite() error { + return fd.shutdown(syscall.SHUT_WR) +} + +func (fd *netFD) Read(p []byte) (n int, err error) { + n, err = fd.pfd.Read(p) + runtime.KeepAlive(fd) + return n, wrapSyscallError(readSyscallName, err) +} + +func (fd *netFD) readFrom(p []byte) (n int, sa syscall.Sockaddr, err error) { + n, sa, err = fd.pfd.ReadFrom(p) + runtime.KeepAlive(fd) + return n, sa, wrapSyscallError(readFromSyscallName, err) +} +func (fd *netFD) readFromInet4(p []byte, from *syscall.SockaddrInet4) (n int, err error) { + n, err = fd.pfd.ReadFromInet4(p, from) + runtime.KeepAlive(fd) + return n, wrapSyscallError(readFromSyscallName, err) +} + +func (fd *netFD) readFromInet6(p []byte, from *syscall.SockaddrInet6) (n int, err error) { + n, err = fd.pfd.ReadFromInet6(p, from) + runtime.KeepAlive(fd) + return n, wrapSyscallError(readFromSyscallName, err) +} + +func (fd *netFD) readMsg(p []byte, oob []byte, flags int) (n, oobn, retflags int, sa syscall.Sockaddr, err error) { + n, oobn, retflags, sa, err = fd.pfd.ReadMsg(p, oob, flags) + runtime.KeepAlive(fd) + return n, oobn, retflags, sa, wrapSyscallError(readMsgSyscallName, err) +} + +func (fd *netFD) readMsgInet4(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet4) (n, oobn, retflags int, err error) { + n, oobn, retflags, err = fd.pfd.ReadMsgInet4(p, oob, flags, sa) + runtime.KeepAlive(fd) + return n, oobn, retflags, wrapSyscallError(readMsgSyscallName, err) +} + +func (fd *netFD) readMsgInet6(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet6) (n, oobn, retflags int, err error) { + n, oobn, retflags, err = fd.pfd.ReadMsgInet6(p, oob, flags, sa) + runtime.KeepAlive(fd) + return n, oobn, retflags, wrapSyscallError(readMsgSyscallName, err) +} + +func (fd *netFD) Write(p []byte) (nn int, err error) { + nn, err = fd.pfd.Write(p) + runtime.KeepAlive(fd) + return nn, wrapSyscallError(writeSyscallName, err) +} + +func (fd *netFD) writeTo(p []byte, sa syscall.Sockaddr) (n int, err error) { + n, err = fd.pfd.WriteTo(p, sa) + runtime.KeepAlive(fd) + return n, wrapSyscallError(writeToSyscallName, err) +} + +func (fd *netFD) writeToInet4(p []byte, sa *syscall.SockaddrInet4) (n int, err error) { + n, err = fd.pfd.WriteToInet4(p, sa) + runtime.KeepAlive(fd) + return n, wrapSyscallError(writeToSyscallName, err) +} + +func (fd *netFD) writeToInet6(p []byte, sa *syscall.SockaddrInet6) (n int, err error) { + n, err = fd.pfd.WriteToInet6(p, sa) + runtime.KeepAlive(fd) + return n, wrapSyscallError(writeToSyscallName, err) +} + +func (fd *netFD) writeMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) { + n, oobn, err = fd.pfd.WriteMsg(p, oob, sa) + runtime.KeepAlive(fd) + return n, oobn, wrapSyscallError(writeMsgSyscallName, err) +} + +func (fd *netFD) writeMsgInet4(p []byte, oob []byte, sa *syscall.SockaddrInet4) (n int, oobn int, err error) { + n, oobn, err = fd.pfd.WriteMsgInet4(p, oob, sa) + runtime.KeepAlive(fd) + return n, oobn, wrapSyscallError(writeMsgSyscallName, err) +} + +func (fd *netFD) writeMsgInet6(p []byte, oob []byte, sa *syscall.SockaddrInet6) (n int, oobn int, err error) { + n, oobn, err = fd.pfd.WriteMsgInet6(p, oob, sa) + runtime.KeepAlive(fd) + return n, oobn, wrapSyscallError(writeMsgSyscallName, err) +} + +func (fd *netFD) SetDeadline(t time.Time) error { + return fd.pfd.SetDeadline(t) +} + +func (fd *netFD) SetReadDeadline(t time.Time) error { + return fd.pfd.SetReadDeadline(t) +} + +func (fd *netFD) SetWriteDeadline(t time.Time) error { + return fd.pfd.SetWriteDeadline(t) +} diff --git a/go/src/net/fd_unix.go b/go/src/net/fd_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..0d4303e2cc0cbee5e64f9bad4c647bc541678c5d --- /dev/null +++ b/go/src/net/fd_unix.go @@ -0,0 +1,184 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "context" + "internal/poll" + "os" + "runtime" + "syscall" +) + +const ( + readSyscallName = "read" + readFromSyscallName = "recvfrom" + readMsgSyscallName = "recvmsg" + writeSyscallName = "write" + writeToSyscallName = "sendto" + writeMsgSyscallName = "sendmsg" +) + +func newFD(sysfd, family, sotype int, net string) (*netFD, error) { + ret := &netFD{ + pfd: poll.FD{ + Sysfd: sysfd, + IsStream: sotype == syscall.SOCK_STREAM, + ZeroReadIsEOF: sotype != syscall.SOCK_DGRAM && sotype != syscall.SOCK_RAW, + }, + family: family, + sotype: sotype, + net: net, + } + return ret, nil +} + +func (fd *netFD) init() error { + return fd.pfd.Init(fd.net, true) +} + +func (fd *netFD) connect(ctx context.Context, la, ra syscall.Sockaddr) (rsa syscall.Sockaddr, ret error) { + // Do not need to call fd.writeLock here, + // because fd is not yet accessible to user, + // so no concurrent operations are possible. + switch err := connectFunc(fd.pfd.Sysfd, ra); err { + case syscall.EINPROGRESS, syscall.EALREADY, syscall.EINTR: + case nil, syscall.EISCONN: + select { + case <-ctx.Done(): + return nil, mapErr(ctx.Err()) + default: + } + if err := fd.pfd.Init(fd.net, true); err != nil { + return nil, err + } + runtime.KeepAlive(fd) + return nil, nil + case syscall.EINVAL: + // On Solaris and illumos we can see EINVAL if the socket has + // already been accepted and closed by the server. Treat this + // as a successful connection--writes to the socket will see + // EOF. For details and a test case in C see + // https://golang.org/issue/6828. + if runtime.GOOS == "solaris" || runtime.GOOS == "illumos" { + return nil, nil + } + fallthrough + default: + return nil, os.NewSyscallError("connect", err) + } + if err := fd.pfd.Init(fd.net, true); err != nil { + return nil, err + } + + ctxDone := ctx.Done() + if ctxDone != nil { + if deadline, hasDeadline := ctx.Deadline(); hasDeadline { + fd.pfd.SetWriteDeadline(deadline) + defer fd.pfd.SetWriteDeadline(noDeadline) + } + + // Load the hook function synchronously to prevent a race + // with test code that restores the old value. + testHookCanceledDial := testHookCanceledDial + stop := context.AfterFunc(ctx, func() { + // Force the runtime's poller to immediately give up + // waiting for writability, unblocking waitWrite + // below. + _ = fd.pfd.SetWriteDeadline(aLongTimeAgo) + testHookCanceledDial() + }) + defer func() { + if !stop() && ret == nil { + // The context.AfterFunc has called or is about to call + // SetWriteDeadline, but the connect code below had + // returned from waitWrite already and did a successful + // connect (ret == nil). Because we've now poisoned the + // connection by making it unwritable, don't return a + // successful dial. This was issue 16523. + ret = mapErr(ctx.Err()) + // The caller closes fd on error, so there's no need to + // wait for the SetWriteDeadline call to return. + } + }() + } + + for { + // Performing multiple connect system calls on a + // non-blocking socket under Unix variants does not + // necessarily result in earlier errors being + // returned. Instead, once runtime-integrated network + // poller tells us that the socket is ready, get the + // SO_ERROR socket option to see if the connection + // succeeded or failed. See issue 7474 for further + // details. + if err := fd.pfd.WaitWrite(); err != nil { + select { + case <-ctxDone: + return nil, mapErr(ctx.Err()) + default: + } + return nil, err + } + nerr, err := getsockoptIntFunc(fd.pfd.Sysfd, syscall.SOL_SOCKET, syscall.SO_ERROR) + if err != nil { + return nil, os.NewSyscallError("getsockopt", err) + } + switch err := syscall.Errno(nerr); err { + case syscall.EINPROGRESS, syscall.EALREADY, syscall.EINTR: + case syscall.EISCONN: + return nil, nil + case syscall.Errno(0): + // The runtime poller can wake us up spuriously; + // see issues 14548 and 19289. Check that we are + // really connected; if not, wait again. + if rsa, err := syscall.Getpeername(fd.pfd.Sysfd); err == nil { + return rsa, nil + } + default: + return nil, os.NewSyscallError("connect", err) + } + runtime.KeepAlive(fd) + } +} + +func (fd *netFD) accept() (netfd *netFD, err error) { + d, rsa, errcall, err := fd.pfd.Accept() + if err != nil { + if errcall != "" { + err = wrapSyscallError(errcall, err) + } + return nil, err + } + + if netfd, err = newFD(d, fd.family, fd.sotype, fd.net); err != nil { + poll.CloseFunc(d) + return nil, err + } + if err = netfd.init(); err != nil { + netfd.Close() + return nil, err + } + lsa, _ := syscall.Getsockname(netfd.pfd.Sysfd) + netfd.setAddr(netfd.addrFunc()(lsa), netfd.addrFunc()(rsa)) + return netfd, nil +} + +// Defined in os package. +func newUnixFile(fd int, name string) *os.File + +func (fd *netFD) dup() (f *os.File, err error) { + ns, call, err := fd.pfd.Dup() + if err != nil { + if call != "" { + err = os.NewSyscallError(call, err) + } + return nil, err + } + + return newUnixFile(ns, fd.name()), nil +} diff --git a/go/src/net/fd_wasip1.go b/go/src/net/fd_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..d50effc05d32bfb4430cadf001b33006f21d8d6f --- /dev/null +++ b/go/src/net/fd_wasip1.go @@ -0,0 +1,25 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build wasip1 + +package net + +import ( + "syscall" +) + +func (fd *netFD) closeRead() error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.closeRead() + } + return fd.shutdown(syscall.SHUT_RD) +} + +func (fd *netFD) closeWrite() error { + if fd.fakeNetFD != nil { + return fd.fakeNetFD.closeWrite() + } + return fd.shutdown(syscall.SHUT_WR) +} diff --git a/go/src/net/fd_windows.go b/go/src/net/fd_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..c28ce045c47811202395fb9477c28325234f8e10 --- /dev/null +++ b/go/src/net/fd_windows.go @@ -0,0 +1,261 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "internal/poll" + "internal/syscall/windows" + "os" + "runtime" + "syscall" + "unsafe" +) + +const ( + readSyscallName = "wsarecv" + readFromSyscallName = "wsarecvfrom" + readMsgSyscallName = "wsarecvmsg" + writeSyscallName = "wsasend" + writeToSyscallName = "wsasendto" + writeMsgSyscallName = "wsasendmsg" +) + +func init() { + poll.InitWSA() +} + +// canUseConnectEx reports whether we can use the ConnectEx Windows API call +// for the given network type. +func canUseConnectEx(net string) bool { + switch net { + case "tcp", "tcp4", "tcp6": + return true + } + // ConnectEx windows API does not support connectionless sockets. + return false +} + +func newFD(sysfd syscall.Handle, family, sotype int, net string) (*netFD, error) { + ret := &netFD{ + pfd: poll.FD{ + Sysfd: sysfd, + IsStream: sotype == syscall.SOCK_STREAM, + ZeroReadIsEOF: sotype != syscall.SOCK_DGRAM && sotype != syscall.SOCK_RAW, + }, + family: family, + sotype: sotype, + net: net, + } + return ret, nil +} + +func (fd *netFD) init() error { + if err := fd.pfd.Init(fd.net, true); err != nil { + return err + } + switch fd.net { + case "udp", "udp4", "udp6": + // Disable reporting of PORT_UNREACHABLE errors. + // See https://go.dev/issue/5834. + ret := uint32(0) + flag := uint32(0) + size := uint32(unsafe.Sizeof(flag)) + err := syscall.WSAIoctl(fd.pfd.Sysfd, syscall.SIO_UDP_CONNRESET, (*byte)(unsafe.Pointer(&flag)), size, nil, 0, &ret, nil, 0) + if err != nil { + return wrapSyscallError("wsaioctl", err) + } + // Disable reporting of NET_UNREACHABLE errors. + // See https://go.dev/issue/68614. + ret = 0 + flag = 0 + size = uint32(unsafe.Sizeof(flag)) + err = syscall.WSAIoctl(fd.pfd.Sysfd, windows.SIO_UDP_NETRESET, (*byte)(unsafe.Pointer(&flag)), size, nil, 0, &ret, nil, 0) + if err != nil { + return wrapSyscallError("wsaioctl", err) + } + } + return nil +} + +// Always returns nil for connected peer address result. +func (fd *netFD) connect(ctx context.Context, la, ra syscall.Sockaddr) (syscall.Sockaddr, error) { + // Do not need to call fd.writeLock here, + // because fd is not yet accessible to user, + // so no concurrent operations are possible. + if err := fd.init(); err != nil { + return nil, err + } + + if ctx.Done() != nil { + // Propagate the Context's deadline and cancellation. + // If the context is already done, or if it has a nonzero deadline, + // ensure that that is applied before the call to ConnectEx begins + // so that we don't return spurious connections. + defer fd.pfd.SetWriteDeadline(noDeadline) + + if ctx.Err() != nil { + fd.pfd.SetWriteDeadline(aLongTimeAgo) + } else { + if deadline, ok := ctx.Deadline(); ok && !deadline.IsZero() { + fd.pfd.SetWriteDeadline(deadline) + } + + done := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + // Force the runtime's poller to immediately give + // up waiting for writability. + fd.pfd.SetWriteDeadline(aLongTimeAgo) + close(done) + }) + defer func() { + if !stop() { + // Wait for the call to SetWriteDeadline to complete so that we can + // reset the deadline if everything else succeeded. + <-done + } + }() + } + } + + if !canUseConnectEx(fd.net) { + err := connectFunc(fd.pfd.Sysfd, ra) + return nil, os.NewSyscallError("connect", err) + } + // ConnectEx windows API requires an unconnected, previously bound socket. + if la == nil { + switch ra.(type) { + case *syscall.SockaddrInet4: + la = &syscall.SockaddrInet4{} + case *syscall.SockaddrInet6: + la = &syscall.SockaddrInet6{} + default: + panic("unexpected type in connect") + } + if err := syscall.Bind(fd.pfd.Sysfd, la); err != nil { + return nil, os.NewSyscallError("bind", err) + } + } + + var isloopback bool + switch ra := ra.(type) { + case *syscall.SockaddrInet4: + isloopback = ra.Addr[0] == 127 + case *syscall.SockaddrInet6: + isloopback = ra.Addr == [16]byte(IPv6loopback) + default: + panic("unexpected type in connect") + } + if isloopback { + // This makes ConnectEx() fails faster if the target port on the localhost + // is not reachable, instead of waiting for 2s. + params := windows.TCP_INITIAL_RTO_PARAMETERS{ + Rtt: windows.TCP_INITIAL_RTO_UNSPECIFIED_RTT, // use the default or overridden by the Administrator + MaxSynRetransmissions: 1, // minimum possible value before Windows 10.0.16299 + } + if windows.SupportTCPInitialRTONoSYNRetransmissions() { + // In Windows 10.0.16299 TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS makes ConnectEx() fails instantly. + params.MaxSynRetransmissions = windows.TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS + } + var out uint32 + // Don't abort the connection if WSAIoctl fails, as it is only an optimization. + // If it fails reliably, we expect TestDialClosedPortFailFast to detect it. + _ = fd.pfd.WSAIoctl(windows.SIO_TCP_INITIAL_RTO, (*byte)(unsafe.Pointer(¶ms)), uint32(unsafe.Sizeof(params)), nil, 0, &out, nil, 0) + } + + // Call ConnectEx API. + if err := fd.pfd.ConnectEx(ra); err != nil { + select { + case <-ctx.Done(): + return nil, mapErr(ctx.Err()) + default: + if _, ok := err.(syscall.Errno); ok { + err = os.NewSyscallError("connectex", err) + } + return nil, err + } + } + // Refresh socket properties. + return nil, os.NewSyscallError("setsockopt", syscall.Setsockopt(fd.pfd.Sysfd, syscall.SOL_SOCKET, syscall.SO_UPDATE_CONNECT_CONTEXT, (*byte)(unsafe.Pointer(&fd.pfd.Sysfd)), int32(unsafe.Sizeof(fd.pfd.Sysfd)))) +} + +func (c *conn) writeBuffers(v *Buffers) (int64, error) { + if !c.ok() { + return 0, syscall.EINVAL + } + n, err := c.fd.writeBuffers(v) + if err != nil { + return n, &OpError{Op: "wsasend", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return n, nil +} + +func (fd *netFD) writeBuffers(buf *Buffers) (int64, error) { + n, err := fd.pfd.Writev((*[][]byte)(buf)) + runtime.KeepAlive(fd) + return n, wrapSyscallError("wsasend", err) +} + +func (fd *netFD) accept() (*netFD, error) { + s, rawsa, rsan, errcall, err := fd.pfd.Accept(func() (syscall.Handle, error) { + return sysSocket(fd.family, fd.sotype, 0) + }) + + if err != nil { + if errcall != "" { + err = wrapSyscallError(errcall, err) + } + return nil, err + } + + // Associate our new socket with IOCP. + netfd, err := newFD(s, fd.family, fd.sotype, fd.net) + if err != nil { + poll.CloseFunc(s) + return nil, err + } + if err := netfd.init(); err != nil { + fd.Close() + return nil, err + } + + // Get local and peer addr out of AcceptEx buffer. + var lrsa, rrsa *syscall.RawSockaddrAny + var llen, rlen int32 + syscall.GetAcceptExSockaddrs((*byte)(unsafe.Pointer(&rawsa[0])), + 0, rsan, rsan, &lrsa, &llen, &rrsa, &rlen) + lsa, _ := lrsa.Sockaddr() + rsa, _ := rrsa.Sockaddr() + + netfd.setAddr(netfd.addrFunc()(lsa), netfd.addrFunc()(rsa)) + return netfd, nil +} + +// Defined in os package. +func newWindowsFile(h syscall.Handle, name string) *os.File + +func (fd *netFD) dup() (*os.File, error) { + // Disassociate the IOCP from the socket, + // it is not safe to share a duplicated handle + // that is associated with IOCP. + if err := fd.pfd.DisassociateIOCP(); err != nil { + return nil, err + } + var h syscall.Handle + var syserr error + err := fd.pfd.RawControl(func(fd uintptr) { + h, syserr = dupSocket(syscall.Handle(fd)) + }) + if err == nil { + err = syserr + } + if err != nil { + return nil, err + } + // All WSASocket calls must be match with a syscall.Closesocket call, + // but os.NewFile calls syscall.CloseHandle instead. We need to use + // a hidden function so that the returned file is aware of this fact. + return newWindowsFile(h, fd.name()), nil +} diff --git a/go/src/net/file.go b/go/src/net/file.go new file mode 100644 index 0000000000000000000000000000000000000000..3e33c9afad65845eeb3a85a378d038d42a230c6b --- /dev/null +++ b/go/src/net/file.go @@ -0,0 +1,51 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "os" + +// BUG(mikio): On JS, the FileConn, FileListener and +// FilePacketConn functions are not implemented. + +type fileAddr string + +func (fileAddr) Network() string { return "file+net" } +func (f fileAddr) String() string { return string(f) } + +// FileConn returns a copy of the network connection 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 FileConn(f *os.File) (c Conn, err error) { + c, err = fileConn(f) + if err != nil { + err = &OpError{Op: "file", Net: "file+net", Source: nil, Addr: fileAddr(f.Name()), Err: err} + } + return +} + +// FileListener returns a copy of the network listener corresponding +// to the open file f. +// It is the caller's responsibility to close ln when finished. +// Closing ln does not affect f, and closing f does not affect ln. +func FileListener(f *os.File) (ln Listener, err error) { + ln, err = fileListener(f) + if err != nil { + err = &OpError{Op: "file", Net: "file+net", Source: nil, Addr: fileAddr(f.Name()), Err: err} + } + return +} + +// FilePacketConn returns a copy of the packet network connection +// 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 error) { + c, err = filePacketConn(f) + if err != nil { + err = &OpError{Op: "file", Net: "file+net", Source: nil, Addr: fileAddr(f.Name()), Err: err} + } + return +} diff --git a/go/src/net/file_plan9.go b/go/src/net/file_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..6c2151c4098a8af643db8a41e6a47e84ad33a691 --- /dev/null +++ b/go/src/net/file_plan9.go @@ -0,0 +1,135 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "io" + "os" + "syscall" +) + +func (fd *netFD) status(ln int) (string, error) { + if !fd.ok() { + return "", syscall.EINVAL + } + + status, err := os.Open(fd.dir + "/status") + if err != nil { + return "", err + } + defer status.Close() + buf := make([]byte, ln) + n, err := io.ReadFull(status, buf[:]) + if err != nil { + return "", err + } + return string(buf[:n]), nil +} + +func newFileFD(f *os.File) (net *netFD, err error) { + var ctl *os.File + close := func(fd int) { + if err != nil { + syscall.Close(fd) + } + } + + path, err := syscall.Fd2path(int(f.Fd())) + if err != nil { + return nil, os.NewSyscallError("fd2path", err) + } + comp := splitAtBytes(path, "/") + n := len(comp) + if n < 3 || comp[0][0:3] != "net" { + return nil, syscall.EPLAN9 + } + + name := comp[2] + switch file := comp[n-1]; file { + case "ctl", "clone": + fd, err := syscall.Dup(int(f.Fd()), -1) + if err != nil { + return nil, os.NewSyscallError("dup", err) + } + defer close(fd) + + dir := netdir + "/" + comp[n-2] + ctl = os.NewFile(uintptr(fd), dir+"/"+file) + ctl.Seek(0, io.SeekStart) + var buf [16]byte + n, err := ctl.Read(buf[:]) + if err != nil { + return nil, err + } + name = string(buf[:n]) + default: + if len(comp) < 4 { + return nil, errors.New("could not find control file for connection") + } + dir := netdir + "/" + comp[1] + "/" + name + ctl, err = os.OpenFile(dir+"/ctl", os.O_RDWR, 0) + if err != nil { + return nil, err + } + defer close(int(ctl.Fd())) + } + dir := netdir + "/" + comp[1] + "/" + name + laddr, err := readPlan9Addr(comp[1], dir+"/local") + if err != nil { + return nil, err + } + return newFD(comp[1], name, nil, ctl, nil, laddr, nil) +} + +func fileConn(f *os.File) (Conn, error) { + fd, err := newFileFD(f) + if err != nil { + return nil, err + } + if !fd.ok() { + return nil, syscall.EINVAL + } + + fd.data, err = os.OpenFile(fd.dir+"/data", os.O_RDWR, 0) + if err != nil { + return nil, err + } + + switch fd.laddr.(type) { + case *TCPAddr: + return newTCPConn(fd, defaultTCPKeepAliveIdle, KeepAliveConfig{}, testPreHookSetKeepAlive, testHookSetKeepAlive), nil + case *UDPAddr: + return newUDPConn(fd), nil + } + return nil, syscall.EPLAN9 +} + +func fileListener(f *os.File) (Listener, error) { + fd, err := newFileFD(f) + if err != nil { + return nil, err + } + switch fd.laddr.(type) { + case *TCPAddr: + default: + return nil, syscall.EPLAN9 + } + + // check that file corresponds to a listener + s, err := fd.status(len("Listen")) + if err != nil { + return nil, err + } + if s != "Listen" { + return nil, errors.New("file does not represent a listener") + } + + return &TCPListener{fd: fd}, nil +} + +func filePacketConn(f *os.File) (PacketConn, error) { + return nil, syscall.EPLAN9 +} diff --git a/go/src/net/file_posix.go b/go/src/net/file_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..b28ff5845d70d1ee1ab0805a880d1bd73d154551 --- /dev/null +++ b/go/src/net/file_posix.go @@ -0,0 +1,108 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || windows + +package net + +import ( + "internal/poll" + "os" + "syscall" +) + +func newFileFD(f *os.File) (*netFD, error) { + s, err := dupFileSocket(f) + if err != nil { + return nil, err + } + family := syscall.AF_UNSPEC + sotype, err := syscall.GetsockoptInt(s, syscall.SOL_SOCKET, _SO_TYPE) + if err != nil { + poll.CloseFunc(s) + return nil, os.NewSyscallError("getsockopt", err) + } + lsa, err := syscall.Getsockname(s) + if err != nil { + poll.CloseFunc(s) + return nil, os.NewSyscallError("getsockname", err) + } + rsa, _ := syscall.Getpeername(s) + switch lsa.(type) { + case *syscall.SockaddrInet4: + family = syscall.AF_INET + case *syscall.SockaddrInet6: + family = syscall.AF_INET6 + case *syscall.SockaddrUnix: + family = syscall.AF_UNIX + default: + poll.CloseFunc(s) + return nil, syscall.EPROTONOSUPPORT + } + fd, err := newFD(s, family, sotype, "") + if err != nil { + poll.CloseFunc(s) + return nil, err + } + laddr := fd.addrFunc()(lsa) + raddr := fd.addrFunc()(rsa) + fd.net = laddr.Network() + if err := fd.init(); err != nil { + fd.Close() + return nil, err + } + fd.setAddr(laddr, raddr) + return fd, nil +} + +func fileConn(f *os.File) (Conn, error) { + fd, err := newFileFD(f) + if err != nil { + return nil, err + } + switch fd.laddr.(type) { + case *TCPAddr: + return newTCPConn(fd, defaultTCPKeepAliveIdle, KeepAliveConfig{}, testPreHookSetKeepAlive, testHookSetKeepAlive), nil + case *UDPAddr: + return newUDPConn(fd), nil + case *IPAddr: + return newIPConn(fd), nil + case *UnixAddr: + return newUnixConn(fd), nil + } + fd.Close() + return nil, syscall.EINVAL +} + +func fileListener(f *os.File) (Listener, error) { + fd, err := newFileFD(f) + if err != nil { + return nil, err + } + switch laddr := fd.laddr.(type) { + case *TCPAddr: + return &TCPListener{fd: fd}, nil + case *UnixAddr: + return &UnixListener{fd: fd, path: laddr.Name, unlink: false}, nil + } + fd.Close() + return nil, syscall.EINVAL +} + +func filePacketConn(f *os.File) (PacketConn, error) { + fd, err := newFileFD(f) + if err != nil { + return nil, err + } + switch fd.laddr.(type) { + case *UDPAddr: + return newUDPConn(fd), nil + case *IPAddr: + return newIPConn(fd), nil + case *UnixAddr: + return newUnixConn(fd), nil + } + fd.Close() + return nil, syscall.EINVAL +} diff --git a/go/src/net/file_stub.go b/go/src/net/file_stub.go new file mode 100644 index 0000000000000000000000000000000000000000..6fd3eec48d9c09f4fe2802bd70cc09b61580de8a --- /dev/null +++ b/go/src/net/file_stub.go @@ -0,0 +1,16 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js + +package net + +import ( + "os" + "syscall" +) + +func fileConn(f *os.File) (Conn, error) { return nil, syscall.ENOPROTOOPT } +func fileListener(f *os.File) (Listener, error) { return nil, syscall.ENOPROTOOPT } +func filePacketConn(f *os.File) (PacketConn, error) { return nil, syscall.ENOPROTOOPT } diff --git a/go/src/net/file_test.go b/go/src/net/file_test.go new file mode 100644 index 0000000000000000000000000000000000000000..51e54ff506bd1f6a9e2f427abfd63e3f19bb6163 --- /dev/null +++ b/go/src/net/file_test.go @@ -0,0 +1,341 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "os" + "reflect" + "runtime" + "sync" + "testing" +) + +// The full stack test cases for IPConn have been moved to the +// following: +// golang.org/x/net/ipv4 +// golang.org/x/net/ipv6 +// golang.org/x/net/icmp + +var fileConnTests = []struct { + network string +}{ + {"tcp"}, + {"udp"}, + {"unix"}, + {"unixpacket"}, +} + +func TestFileConn(t *testing.T) { + switch runtime.GOOS { + case "plan9", "js", "wasip1": + t.Skipf("not supported on %s", runtime.GOOS) + } + + for _, tt := range fileConnTests { + t.Run(tt.network, func(t *testing.T) { + if !testableNetwork(tt.network) { + t.Skipf("skipping %s test", tt.network) + } + + var network, address string + switch tt.network { + case "udp": + c := newLocalPacketListener(t, tt.network) + defer c.Close() + network = c.LocalAddr().Network() + address = c.LocalAddr().String() + default: + handler := func(ls *localServer, ln Listener) { + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + var b [1]byte + c.Read(b[:]) + } + ls := newLocalServer(t, tt.network) + defer ls.teardown() + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + network = ls.Listener.Addr().Network() + address = ls.Listener.Addr().String() + } + + c1, err := Dial(network, address) + if err != nil { + if perr := parseDialError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + addr := c1.LocalAddr() + + var f *os.File + switch c1 := c1.(type) { + case *TCPConn: + f, err = c1.File() + case *UDPConn: + f, err = c1.File() + case *UnixConn: + f, err = c1.File() + } + if err := c1.Close(); err != nil { + if perr := parseCloseError(err, false); perr != nil { + t.Error(perr) + } + t.Error(err) + } + if err != nil { + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + + c2, err := FileConn(f) + if err := f.Close(); err != nil { + t.Error(err) + } + if err != nil { + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + defer c2.Close() + + if _, err := c2.Write([]byte("FILECONN TEST")); err != nil { + if perr := parseWriteError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + if !reflect.DeepEqual(c2.LocalAddr(), addr) { + t.Fatalf("got %#v; want %#v", c2.LocalAddr(), addr) + } + }) + } +} + +var fileListenerTests = []struct { + network string +}{ + {"tcp"}, + {"unix"}, + {"unixpacket"}, +} + +func TestFileListener(t *testing.T) { + switch runtime.GOOS { + case "plan9", "js", "wasip1": + t.Skipf("not supported on %s", runtime.GOOS) + } + + for _, tt := range fileListenerTests { + t.Run(tt.network, func(t *testing.T) { + if !testableNetwork(tt.network) { + t.Skipf("skipping %s test", tt.network) + } + + ln1 := newLocalListener(t, tt.network) + switch tt.network { + case "unix", "unixpacket": + defer os.Remove(ln1.Addr().String()) + } + addr := ln1.Addr() + + var ( + f *os.File + err error + ) + switch ln1 := ln1.(type) { + case *TCPListener: + f, err = ln1.File() + case *UnixListener: + f, err = ln1.File() + } + switch tt.network { + case "unix", "unixpacket": + defer ln1.Close() // UnixListener.Close calls syscall.Unlink internally + default: + if err := ln1.Close(); err != nil { + t.Error(err) + } + } + if err != nil { + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + + ln2, err := FileListener(f) + if err := f.Close(); err != nil { + t.Error(err) + } + if err != nil { + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + defer ln2.Close() + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + c, err := Dial(ln2.Addr().Network(), ln2.Addr().String()) + if err != nil { + if perr := parseDialError(err); perr != nil { + t.Error(perr) + } + t.Error(err) + return + } + c.Close() + }() + c, err := ln2.Accept() + if err != nil { + if perr := parseAcceptError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + c.Close() + wg.Wait() + if !reflect.DeepEqual(ln2.Addr(), addr) { + t.Fatalf("got %#v; want %#v", ln2.Addr(), addr) + } + }) + } +} + +var filePacketConnTests = []struct { + network string +}{ + {"udp"}, + {"unixgram"}, +} + +func TestFilePacketConn(t *testing.T) { + switch runtime.GOOS { + case "plan9", "js", "wasip1": + t.Skipf("not supported on %s", runtime.GOOS) + } + + for _, tt := range filePacketConnTests { + t.Run(tt.network, func(t *testing.T) { + if !testableNetwork(tt.network) { + t.Skipf("skipping %s test", tt.network) + } + + c1 := newLocalPacketListener(t, tt.network) + switch tt.network { + case "unixgram": + defer os.Remove(c1.LocalAddr().String()) + } + addr := c1.LocalAddr() + + var ( + f *os.File + err error + ) + switch c1 := c1.(type) { + case *UDPConn: + f, err = c1.File() + case *UnixConn: + f, err = c1.File() + } + if err := c1.Close(); err != nil { + if perr := parseCloseError(err, false); perr != nil { + t.Error(perr) + } + t.Error(err) + } + if err != nil { + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + + c2, err := FilePacketConn(f) + if err := f.Close(); err != nil { + t.Error(err) + } + if err != nil { + if perr := parseCommonError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + defer c2.Close() + + if _, err := c2.WriteTo([]byte("FILEPACKETCONN TEST"), addr); err != nil { + if perr := parseWriteError(err); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + if !reflect.DeepEqual(c2.LocalAddr(), addr) { + t.Fatalf("got %#v; want %#v", c2.LocalAddr(), addr) + } + }) + } +} + +// Issue 24483. +func TestFileCloseRace(t *testing.T) { + switch runtime.GOOS { + case "plan9", "js", "wasip1": + t.Skipf("not supported on %s", runtime.GOOS) + } + if !testableNetwork("tcp") { + t.Skip("tcp not supported") + } + + handler := func(ls *localServer, ln Listener) { + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + var b [1]byte + c.Read(b[:]) + } + + ls := newLocalServer(t, "tcp") + defer ls.teardown() + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + + const tries = 100 + for i := 0; i < tries; i++ { + c1, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + tc := c1.(*TCPConn) + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + f, err := tc.File() + if err == nil { + f.Close() + } + }() + go func() { + defer wg.Done() + c1.Close() + }() + wg.Wait() + } +} diff --git a/go/src/net/file_unix.go b/go/src/net/file_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..d56da9003747ab0f94b10b175ec5719a7d5fe8df --- /dev/null +++ b/go/src/net/file_unix.go @@ -0,0 +1,30 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "internal/poll" + "os" + "syscall" +) + +const _SO_TYPE = syscall.SO_TYPE + +func dupFileSocket(f *os.File) (int, error) { + s, call, err := poll.DupCloseOnExec(int(f.Fd())) + if err != nil { + if call != "" { + err = os.NewSyscallError(call, err) + } + return -1, err + } + if err := syscall.SetNonblock(s, true); err != nil { + poll.CloseFunc(s) + return -1, os.NewSyscallError("setnonblock", err) + } + return s, nil +} diff --git a/go/src/net/file_unix_test.go b/go/src/net/file_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0499a02404a3ac7cd2fd1521dd04e29d6a4cc068 --- /dev/null +++ b/go/src/net/file_unix_test.go @@ -0,0 +1,101 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "internal/syscall/unix" + "testing" +) + +// For backward compatibility, opening a net.Conn, turning it into an os.File, +// and calling the Fd method should return a blocking descriptor. +func TestFileFdBlocks(t *testing.T) { + if !testableNetwork("unix") { + t.Skipf("skipping: unix sockets not supported") + } + + ls := newLocalServer(t, "unix") + defer ls.teardown() + + errc := make(chan error, 1) + done := make(chan bool) + handler := func(ls *localServer, ln Listener) { + server, err := ln.Accept() + errc <- err + if err != nil { + return + } + defer server.Close() + <-done + } + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + defer close(done) + + client, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer client.Close() + + if err := <-errc; err != nil { + t.Fatalf("server error: %v", err) + } + + // The socket should be non-blocking. + rawconn, err := client.(*UnixConn).SyscallConn() + if err != nil { + t.Fatal(err) + } + err = rawconn.Control(func(fd uintptr) { + nonblock, err := unix.IsNonblock(int(fd)) + if err != nil { + t.Fatal(err) + } + if !nonblock { + t.Fatal("unix socket is in blocking mode") + } + }) + if err != nil { + t.Fatal(err) + } + + file, err := client.(*UnixConn).File() + if err != nil { + t.Fatal(err) + } + + // At this point the descriptor should still be non-blocking. + rawconn, err = file.SyscallConn() + if err != nil { + t.Fatal(err) + } + err = rawconn.Control(func(fd uintptr) { + nonblock, err := unix.IsNonblock(int(fd)) + if err != nil { + t.Fatal(err) + } + if !nonblock { + t.Fatal("unix socket as os.File is in blocking mode") + } + }) + if err != nil { + t.Fatal(err) + } + + fd := file.Fd() + + // Calling Fd should have put the descriptor into blocking mode. + nonblock, err := unix.IsNonblock(int(fd)) + if err != nil { + t.Fatal(err) + } + if nonblock { + t.Error("unix socket through os.File.Fd is non-blocking") + } +} diff --git a/go/src/net/file_wasip1.go b/go/src/net/file_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..a3624efb55e4ba904ee1806c7092957fa96beb2d --- /dev/null +++ b/go/src/net/file_wasip1.go @@ -0,0 +1,102 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build wasip1 + +package net + +import ( + "os" + "syscall" + _ "unsafe" // for go:linkname +) + +func fileListener(f *os.File) (Listener, error) { + filetype, err := fd_fdstat_get_type(f.PollFD().Sysfd) + if err != nil { + return nil, err + } + net, err := fileListenNet(filetype) + if err != nil { + return nil, err + } + pfd := f.PollFD().Copy() + fd := newPollFD(net, pfd) + if err := fd.init(); err != nil { + pfd.Close() + return nil, err + } + return newFileListener(fd), nil +} + +func fileConn(f *os.File) (Conn, error) { + filetype, err := fd_fdstat_get_type(f.PollFD().Sysfd) + if err != nil { + return nil, err + } + net, err := fileConnNet(filetype) + if err != nil { + return nil, err + } + pfd := f.PollFD().Copy() + fd := newPollFD(net, pfd) + if err := fd.init(); err != nil { + pfd.Close() + return nil, err + } + return newFileConn(fd), nil +} + +func filePacketConn(f *os.File) (PacketConn, error) { + return nil, syscall.ENOPROTOOPT +} + +func fileListenNet(filetype syscall.Filetype) (string, error) { + switch filetype { + case syscall.FILETYPE_SOCKET_STREAM: + return "tcp", nil + case syscall.FILETYPE_SOCKET_DGRAM: + return "", syscall.EOPNOTSUPP + default: + return "", syscall.ENOTSOCK + } +} + +func fileConnNet(filetype syscall.Filetype) (string, error) { + switch filetype { + case syscall.FILETYPE_SOCKET_STREAM: + return "tcp", nil + case syscall.FILETYPE_SOCKET_DGRAM: + return "udp", nil + default: + return "", syscall.ENOTSOCK + } +} + +func newFileListener(fd *netFD) Listener { + switch fd.net { + case "tcp": + return &TCPListener{fd: fd} + default: + panic("unsupported network for file listener: " + fd.net) + } +} + +func newFileConn(fd *netFD) Conn { + switch fd.net { + case "tcp": + return &TCPConn{conn{fd: fd}} + case "udp": + return &UDPConn{conn{fd: fd}} + default: + panic("unsupported network for file connection: " + fd.net) + } +} + +// This helper is implemented in the syscall package. It means we don't have +// to redefine the fd_fdstat_get host import or the fdstat struct it +// populates. +// +//go:linkname fd_fdstat_get_type syscall.fd_fdstat_get_type +func fd_fdstat_get_type(fd int) (uint8, error) diff --git a/go/src/net/file_wasip1_test.go b/go/src/net/file_wasip1_test.go new file mode 100644 index 0000000000000000000000000000000000000000..91f57eecdacf6ea5d32853a1bacb33cf6b63b70e --- /dev/null +++ b/go/src/net/file_wasip1_test.go @@ -0,0 +1,112 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build wasip1 + +package net + +import ( + "syscall" + "testing" +) + +// The tests in this file intend to validate the ability for net.FileConn and +// net.FileListener to handle both TCP and UDP sockets. Ideally we would test +// the public interface by constructing an *os.File from a file descriptor +// opened on a socket, but the WASI preview 1 specification is too limited to +// support this approach for UDP sockets. Instead, we test the internals that +// make it possible for WASI host runtimes and guest programs to integrate +// socket extensions with the net package using net.FileConn/net.FileListener. +// +// Note that the creation of net.Conn and net.Listener values for TCP sockets +// has an end-to-end test in src/internal/runtime/wasitest, here we are only +// verifying the code paths specific to UDP, and error handling for invalid use +// of the functions. + +func TestWasip1FileConnNet(t *testing.T) { + tests := []struct { + filetype syscall.Filetype + network string + error error + }{ + {syscall.FILETYPE_SOCKET_STREAM, "tcp", nil}, + {syscall.FILETYPE_SOCKET_DGRAM, "udp", nil}, + {syscall.FILETYPE_BLOCK_DEVICE, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_CHARACTER_DEVICE, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_DIRECTORY, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_REGULAR_FILE, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_SYMBOLIC_LINK, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_UNKNOWN, "", syscall.ENOTSOCK}, + } + for _, test := range tests { + net, err := fileConnNet(test.filetype) + if net != test.network { + t.Errorf("fileConnNet: network mismatch: want=%q got=%q", test.network, net) + } + if err != test.error { + t.Errorf("fileConnNet: error mismatch: want=%v got=%v", test.error, err) + } + } +} + +func TestWasip1FileListenNet(t *testing.T) { + tests := []struct { + filetype syscall.Filetype + network string + error error + }{ + {syscall.FILETYPE_SOCKET_STREAM, "tcp", nil}, + {syscall.FILETYPE_SOCKET_DGRAM, "", syscall.EOPNOTSUPP}, + {syscall.FILETYPE_BLOCK_DEVICE, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_CHARACTER_DEVICE, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_DIRECTORY, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_REGULAR_FILE, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_SYMBOLIC_LINK, "", syscall.ENOTSOCK}, + {syscall.FILETYPE_UNKNOWN, "", syscall.ENOTSOCK}, + } + for _, test := range tests { + net, err := fileListenNet(test.filetype) + if net != test.network { + t.Errorf("fileListenNet: network mismatch: want=%q got=%q", test.network, net) + } + if err != test.error { + t.Errorf("fileListenNet: error mismatch: want=%v got=%v", test.error, err) + } + } +} + +func TestWasip1NewFileListener(t *testing.T) { + if l, ok := newFileListener(newFD("tcp", -1)).(*TCPListener); !ok { + t.Errorf("newFileListener: tcp listener type mismatch: %T", l) + } else { + testIsTCPAddr(t, "Addr", l.Addr()) + } +} + +func TestWasip1NewFileConn(t *testing.T) { + if c, ok := newFileConn(newFD("tcp", -1)).(*TCPConn); !ok { + t.Errorf("newFileConn: tcp conn type mismatch: %T", c) + } else { + testIsTCPAddr(t, "LocalAddr", c.LocalAddr()) + testIsTCPAddr(t, "RemoteAddr", c.RemoteAddr()) + } + if c, ok := newFileConn(newFD("udp", -1)).(*UDPConn); !ok { + t.Errorf("newFileConn: udp conn type mismatch: %T", c) + } else { + testIsUDPAddr(t, "LocalAddr", c.LocalAddr()) + testIsUDPAddr(t, "RemoteAddr", c.RemoteAddr()) + } +} + +func testIsTCPAddr(t *testing.T, method string, addr Addr) { + if _, ok := addr.(*TCPAddr); !ok { + t.Errorf("%s: returned address is not a *TCPAddr: %T", method, addr) + } +} + +func testIsUDPAddr(t *testing.T, method string, addr Addr) { + if _, ok := addr.(*UDPAddr); !ok { + t.Errorf("%s: returned address is not a *UDPAddr: %T", method, addr) + } +} diff --git a/go/src/net/file_windows.go b/go/src/net/file_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..6a6305035a151aae3c9da9c7cd14beaa9051bcd0 --- /dev/null +++ b/go/src/net/file_windows.go @@ -0,0 +1,49 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/syscall/windows" + "os" + "syscall" +) + +const _SO_TYPE = windows.SO_TYPE + +func dupSocket(h syscall.Handle) (syscall.Handle, error) { + var info syscall.WSAProtocolInfo + err := windows.WSADuplicateSocket(h, uint32(syscall.Getpid()), &info) + if err != nil { + return 0, err + } + return windows.WSASocket(-1, -1, -1, &info, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT) +} + +func dupFileSocket(f *os.File) (syscall.Handle, error) { + // Call Fd to disassociate the IOCP from the handle, + // it is not safe to share a duplicated handle + // that is associated with IOCP. + // Don't use the returned fd, as it might be closed + // if f happens to be the last reference to the file. + f.Fd() + + sc, err := f.SyscallConn() + if err != nil { + return 0, err + } + + var h syscall.Handle + var syserr error + err = sc.Control(func(fd uintptr) { + h, syserr = dupSocket(syscall.Handle(fd)) + }) + if err == nil { + err = syserr + } + if err != nil { + return 0, err + } + return h, nil +} diff --git a/go/src/net/hook.go b/go/src/net/hook.go new file mode 100644 index 0000000000000000000000000000000000000000..08d1aa893481f2003f8ea61352ee632742c5288e --- /dev/null +++ b/go/src/net/hook.go @@ -0,0 +1,31 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" +) + +var ( + // if non-nil, overrides dialTCP. + testHookDialTCP func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error) + + testHookLookupIP = func( + ctx context.Context, + fn func(context.Context, string, string) ([]IPAddr, error), + network string, + host string, + ) ([]IPAddr, error) { + return fn(ctx, network, host) + } + testPreHookSetKeepAlive = func(*netFD) {} + testHookSetKeepAlive = func(KeepAliveConfig) {} + + // testHookStepTime sleeps until time has moved forward by a nonzero amount. + // This helps to avoid flakes in timeout tests by ensuring that an implausibly + // short deadline (such as 1ns in the future) is always expired by the time + // a relevant system call occurs. + testHookStepTime = func() {} +) diff --git a/go/src/net/hook_plan9.go b/go/src/net/hook_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..6020d329240272e0933034a59fbb03a8f312908e --- /dev/null +++ b/go/src/net/hook_plan9.go @@ -0,0 +1,9 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +var ( + hostsFilePath = "/etc/hosts" +) diff --git a/go/src/net/hook_unix.go b/go/src/net/hook_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..69b375598dc6adbd4a071681da67c704ef9fa38a --- /dev/null +++ b/go/src/net/hook_unix.go @@ -0,0 +1,21 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 + +package net + +import "syscall" + +var ( + testHookCanceledDial = func() {} // for golang.org/issue/16523 + + hostsFilePath = "/etc/hosts" + + // Placeholders for socket system calls. + socketFunc func(int, int, int) (int, error) = syscall.Socket + connectFunc func(int, syscall.Sockaddr) error = syscall.Connect + listenFunc func(int, int) error = syscall.Listen + getsockoptIntFunc func(int, int, int) (int, error) = syscall.GetsockoptInt +) diff --git a/go/src/net/hook_windows.go b/go/src/net/hook_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..f7c5b5af90fe354f9d4238dade86aa0e08481e35 --- /dev/null +++ b/go/src/net/hook_windows.go @@ -0,0 +1,19 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/syscall/windows" + "syscall" +) + +var ( + hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts" + + // Placeholders for socket system calls. + wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket + connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect + listenFunc func(syscall.Handle, int) error = syscall.Listen +) diff --git a/go/src/net/hosts.go b/go/src/net/hosts.go new file mode 100644 index 0000000000000000000000000000000000000000..73e6fcc7a4ae7dfbab02a44d6b4fb0e531beb8c9 --- /dev/null +++ b/go/src/net/hosts.go @@ -0,0 +1,165 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "internal/bytealg" + "io/fs" + "net/netip" + "sync" + "time" +) + +const cacheMaxAge = 5 * time.Second + +func parseLiteralIP(addr string) string { + ip, err := netip.ParseAddr(addr) + if err != nil { + return "" + } + return ip.String() +} + +type byName struct { + addrs []string + canonicalName string +} + +// hosts contains known host entries. +var hosts struct { + sync.Mutex + + // Key for the list of literal IP addresses must be a host + // name. It would be part of DNS labels, a FQDN or an absolute + // FQDN. + // For now the key is converted to lower case for convenience. + byName map[string]byName + + // Key for the list of host names must be a literal IP address + // including IPv6 address with zone identifier. + // We don't support old-classful IP address notation. + byAddr map[string][]string + + expire time.Time + path string + mtime time.Time + size int64 +} + +func readHosts() { + now := time.Now() + hp := hostsFilePath + + if now.Before(hosts.expire) && hosts.path == hp && len(hosts.byName) > 0 { + return + } + mtime, size, err := stat(hp) + if err == nil && hosts.path == hp && hosts.mtime.Equal(mtime) && hosts.size == size { + hosts.expire = now.Add(cacheMaxAge) + return + } + + hs := make(map[string]byName) + is := make(map[string][]string) + + file, err := open(hp) + if err != nil { + if !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, fs.ErrPermission) { + return + } + } + + if file != nil { + defer file.close() + for line, ok := file.readLine(); ok; line, ok = file.readLine() { + if i := bytealg.IndexByteString(line, '#'); i >= 0 { + // Discard comments. + line = line[0:i] + } + f := getFields(line) + if len(f) < 2 { + continue + } + addr := parseLiteralIP(f[0]) + if addr == "" { + continue + } + + var canonical string + for i := 1; i < len(f); i++ { + name := absDomainName(f[i]) + h := []byte(f[i]) + lowerASCIIBytes(h) + key := absDomainName(string(h)) + + if i == 1 { + canonical = key + } + + is[addr] = append(is[addr], name) + + if v, ok := hs[key]; ok { + hs[key] = byName{ + addrs: append(v.addrs, addr), + canonicalName: v.canonicalName, + } + continue + } + + hs[key] = byName{ + addrs: []string{addr}, + canonicalName: canonical, + } + } + } + } + // Update the data cache. + hosts.expire = now.Add(cacheMaxAge) + hosts.path = hp + hosts.byName = hs + hosts.byAddr = is + hosts.mtime = mtime + hosts.size = size +} + +// lookupStaticHost looks up the addresses and the canonical name for the given host from /etc/hosts. +func lookupStaticHost(host string) ([]string, string) { + hosts.Lock() + defer hosts.Unlock() + readHosts() + if len(hosts.byName) != 0 { + if hasUpperCase(host) { + lowerHost := []byte(host) + lowerASCIIBytes(lowerHost) + host = string(lowerHost) + } + if byName, ok := hosts.byName[absDomainName(host)]; ok { + ipsCp := make([]string, len(byName.addrs)) + copy(ipsCp, byName.addrs) + return ipsCp, byName.canonicalName + } + } + return nil, "" +} + +// lookupStaticAddr looks up the hosts for the given address from /etc/hosts. +func lookupStaticAddr(addr string) []string { + hosts.Lock() + defer hosts.Unlock() + readHosts() + addr = parseLiteralIP(addr) + if addr == "" { + return nil + } + if len(hosts.byAddr) != 0 { + if hosts, ok := hosts.byAddr[addr]; ok { + hostsCp := make([]string, len(hosts)) + copy(hostsCp, hosts) + return hostsCp + } + } + return nil +} diff --git a/go/src/net/hosts_test.go b/go/src/net/hosts_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2661e79d993d203641b8f4e169ec8e8cbacdd959 --- /dev/null +++ b/go/src/net/hosts_test.go @@ -0,0 +1,214 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "slices" + "strings" + "testing" +) + +type staticHostEntry struct { + in string + out []string +} + +var lookupStaticHostTests = []struct { + name string + ents []staticHostEntry +}{ + { + "testdata/hosts", + []staticHostEntry{ + {"odin", []string{"127.0.0.2", "127.0.0.3", "::2"}}, + {"thor", []string{"127.1.1.1"}}, + {"ullr", []string{"127.1.1.2"}}, + {"ullrhost", []string{"127.1.1.2"}}, + {"localhost", []string{"fe80::1%lo0"}}, + }, + }, + { + "testdata/singleline-hosts", // see golang.org/issue/6646 + []staticHostEntry{ + {"odin", []string{"127.0.0.2"}}, + }, + }, + { + "testdata/ipv4-hosts", + []staticHostEntry{ + {"localhost", []string{"127.0.0.1", "127.0.0.2", "127.0.0.3"}}, + {"localhost.localdomain", []string{"127.0.0.3"}}, + }, + }, + { + "testdata/ipv6-hosts", // see golang.org/issue/8996 + []staticHostEntry{ + {"localhost", []string{"::1", "fe80::1", "fe80::2%lo0", "fe80::3%lo0"}}, + {"localhost.localdomain", []string{"fe80::3%lo0"}}, + }, + }, + { + "testdata/case-hosts", // see golang.org/issue/12806 + []staticHostEntry{ + {"PreserveMe", []string{"127.0.0.1", "::1"}}, + {"PreserveMe.local", []string{"127.0.0.1", "::1"}}, + }, + }, +} + +func TestLookupStaticHost(t *testing.T) { + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + + for _, tt := range lookupStaticHostTests { + hostsFilePath = tt.name + for _, ent := range tt.ents { + testStaticHost(t, tt.name, ent) + } + } +} + +func testStaticHost(t *testing.T, hostsPath string, ent staticHostEntry) { + ins := []string{ent.in, absDomainName(ent.in), strings.ToLower(ent.in), strings.ToUpper(ent.in)} + for _, in := range ins { + addrs, _ := lookupStaticHost(in) + if !slices.Equal(addrs, ent.out) { + t.Errorf("%s, lookupStaticHost(%s) = %v; want %v", hostsPath, in, addrs, ent.out) + } + } +} + +var lookupStaticAddrTests = []struct { + name string + ents []staticHostEntry +}{ + { + "testdata/hosts", + []staticHostEntry{ + {"255.255.255.255", []string{"broadcasthost"}}, + {"127.0.0.2", []string{"odin"}}, + {"127.0.0.3", []string{"odin"}}, + {"::2", []string{"odin"}}, + {"127.1.1.1", []string{"thor"}}, + {"127.1.1.2", []string{"ullr", "ullrhost"}}, + {"fe80::1%lo0", []string{"localhost"}}, + }, + }, + { + "testdata/singleline-hosts", // see golang.org/issue/6646 + []staticHostEntry{ + {"127.0.0.2", []string{"odin"}}, + }, + }, + { + "testdata/ipv4-hosts", + []staticHostEntry{ + {"127.0.0.1", []string{"localhost"}}, + {"127.0.0.2", []string{"localhost"}}, + {"127.0.0.3", []string{"localhost", "localhost.localdomain"}}, + }, + }, + { + "testdata/ipv6-hosts", // see golang.org/issue/8996 + []staticHostEntry{ + {"::1", []string{"localhost"}}, + {"fe80::1", []string{"localhost"}}, + {"fe80::2%lo0", []string{"localhost"}}, + {"fe80::3%lo0", []string{"localhost", "localhost.localdomain"}}, + }, + }, + { + "testdata/case-hosts", // see golang.org/issue/12806 + []staticHostEntry{ + {"127.0.0.1", []string{"PreserveMe", "PreserveMe.local"}}, + {"::1", []string{"PreserveMe", "PreserveMe.local"}}, + }, + }, +} + +func TestLookupStaticAddr(t *testing.T) { + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + + for _, tt := range lookupStaticAddrTests { + hostsFilePath = tt.name + for _, ent := range tt.ents { + testStaticAddr(t, tt.name, ent) + } + } +} + +func testStaticAddr(t *testing.T, hostsPath string, ent staticHostEntry) { + hosts := lookupStaticAddr(ent.in) + for i := range ent.out { + ent.out[i] = absDomainName(ent.out[i]) + } + if !slices.Equal(hosts, ent.out) { + t.Errorf("%s, lookupStaticAddr(%s) = %v; want %v", hostsPath, ent.in, hosts, ent.out) + } +} + +func TestHostCacheModification(t *testing.T) { + // Ensure that programs can't modify the internals of the host cache. + // See https://golang.org/issues/14212. + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + + hostsFilePath = "testdata/ipv4-hosts" + ent := staticHostEntry{"localhost", []string{"127.0.0.1", "127.0.0.2", "127.0.0.3"}} + testStaticHost(t, hostsFilePath, ent) + // Modify the addresses return by lookupStaticHost. + addrs, _ := lookupStaticHost(ent.in) + for i := range addrs { + addrs[i] += "junk" + } + testStaticHost(t, hostsFilePath, ent) + + hostsFilePath = "testdata/ipv6-hosts" + ent = staticHostEntry{"::1", []string{"localhost"}} + testStaticAddr(t, hostsFilePath, ent) + // Modify the hosts return by lookupStaticAddr. + hosts := lookupStaticAddr(ent.in) + for i := range hosts { + hosts[i] += "junk" + } + testStaticAddr(t, hostsFilePath, ent) +} + +var lookupStaticHostAliasesTest = []struct { + lookup, res string +}{ + // 127.0.0.1 + {"test", "test"}, + // 127.0.0.2 + {"test2.example.com", "test2.example.com"}, + {"2.test", "test2.example.com"}, + // 127.0.0.3 + {"test3.example.com", "3.test"}, + {"3.test", "3.test"}, + // 127.0.0.4 + {"example.com", "example.com"}, + // 127.0.0.5 + {"test5.example.com", "test4.example.com"}, + {"5.test", "test4.example.com"}, + {"4.test", "test4.example.com"}, + {"test4.example.com", "test4.example.com"}, +} + +func TestLookupStaticHostAliases(t *testing.T) { + defer func(orig string) { hostsFilePath = orig }(hostsFilePath) + + hostsFilePath = "testdata/aliases" + for _, ent := range lookupStaticHostAliasesTest { + testLookupStaticHostAliases(t, ent.lookup, absDomainName(ent.res)) + } +} + +func testLookupStaticHostAliases(t *testing.T, lookup, lookupRes string) { + ins := []string{lookup, absDomainName(lookup), strings.ToLower(lookup), strings.ToUpper(lookup)} + for _, in := range ins { + _, res := lookupStaticHost(in) + if res != lookupRes { + t.Errorf("lookupStaticHost(%v): got %v, want %v", in, res, lookupRes) + } + } +} diff --git a/go/src/net/interface.go b/go/src/net/interface.go new file mode 100644 index 0000000000000000000000000000000000000000..3cf52c53713001c9ec8af1078bb5341135c06573 --- /dev/null +++ b/go/src/net/interface.go @@ -0,0 +1,262 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "internal/strconv" + "sync" + "time" + _ "unsafe" +) + +// BUG(mikio): On JS, methods and functions related to +// Interface are not implemented. + +// BUG(mikio): On AIX, DragonFly BSD, NetBSD, OpenBSD, Plan 9 and +// Solaris, the MulticastAddrs method of Interface is not implemented. + +var ( + errInvalidInterface = errors.New("invalid network interface") + errInvalidInterfaceIndex = errors.New("invalid network interface index") + errInvalidInterfaceName = errors.New("invalid network interface name") + errNoSuchInterface = errors.New("no such network interface") + errNoSuchMulticastInterface = errors.New("no such multicast network interface") +) + +// Interface represents a mapping between network interface name +// and index. It also represents network interface facility +// information. +type Interface struct { + Index int // positive integer that starts at one, zero is never used + MTU int // maximum transmission unit + Name string // e.g., "en0", "lo0", "eth0.100"; may be the empty string + HardwareAddr HardwareAddr // IEEE MAC-48, EUI-48 and EUI-64 form + Flags Flags // e.g., FlagUp, FlagLoopback, FlagMulticast +} + +type Flags uint + +const ( + FlagUp Flags = 1 << iota // interface is administratively up + FlagBroadcast // interface supports broadcast access capability + FlagLoopback // interface is a loopback interface + FlagPointToPoint // interface belongs to a point-to-point link + FlagMulticast // interface supports multicast access capability + FlagRunning // interface is in running state +) + +var flagNames = []string{ + "up", + "broadcast", + "loopback", + "pointtopoint", + "multicast", + "running", +} + +func (f Flags) String() string { + s := "" + for i, name := range flagNames { + if f&(1< 0 { + ifm := (*syscall.IfMsgHdr)(unsafe.Pointer(&tab[0])) + if ifm.Msglen == 0 { + break + } + if ifm.Type == syscall.RTM_IFINFO { + if ifindex == 0 || ifindex == int(ifm.Index) { + sdl := (*rawSockaddrDatalink)(unsafe.Pointer(&tab[syscall.SizeofIfMsghdr])) + + ifi := &Interface{Index: int(ifm.Index), Flags: linkFlags(ifm.Flags)} + ifi.Name = string(sdl.Data[:sdl.Nlen]) + ifi.HardwareAddr = sdl.Data[sdl.Nlen : sdl.Nlen+sdl.Alen] + + // Retrieve MTU + ifr := &ifreq{} + copy(ifr.Name[:], ifi.Name) + err = unix.Ioctl(sock, syscall.SIOCGIFMTU, unsafe.Pointer(ifr)) + if err != nil { + return nil, err + } + ifi.MTU = int(ifr.Ifru[0])<<24 | int(ifr.Ifru[1])<<16 | int(ifr.Ifru[2])<<8 | int(ifr.Ifru[3]) + + ift = append(ift, *ifi) + if ifindex == int(ifm.Index) { + break + } + } + } + tab = tab[ifm.Msglen:] + } + + return ift, nil +} + +func linkFlags(rawFlags int32) Flags { + var f Flags + if rawFlags&syscall.IFF_UP != 0 { + f |= FlagUp + } + if rawFlags&syscall.IFF_RUNNING != 0 { + f |= FlagRunning + } + if rawFlags&syscall.IFF_BROADCAST != 0 { + f |= FlagBroadcast + } + if rawFlags&syscall.IFF_LOOPBACK != 0 { + f |= FlagLoopback + } + if rawFlags&syscall.IFF_POINTOPOINT != 0 { + f |= FlagPointToPoint + } + if rawFlags&syscall.IFF_MULTICAST != 0 { + f |= FlagMulticast + } + return f +} + +// If the ifi is nil, interfaceAddrTable returns addresses for all +// network interfaces. Otherwise it returns addresses for a specific +// interface. +func interfaceAddrTable(ifi *Interface) ([]Addr, error) { + tab, err := getIfList() + if err != nil { + return nil, err + } + + var ifat []Addr + for len(tab) > 0 { + ifm := (*syscall.IfMsgHdr)(unsafe.Pointer(&tab[0])) + if ifm.Msglen == 0 { + break + } + if ifm.Type == syscall.RTM_NEWADDR { + if ifi == nil || ifi.Index == int(ifm.Index) { + mask := ifm.Addrs + off := uint(syscall.SizeofIfMsghdr) + + var iprsa, nmrsa *syscall.RawSockaddr + for i := uint(0); i < _RTAX_MAX; i++ { + if mask&(1< 0 { + ift[n].HardwareAddr = make([]byte, len(sa.Addr)) + copy(ift[n].HardwareAddr, sa.Addr) + } + ift[n].MTU = m.MTU() + n++ + if ifindex == m.Index { + return ift[:n], nil + } + } + } + return ift[:n], nil +} + +func linkFlags(rawFlags int) Flags { + var f Flags + if rawFlags&syscall.IFF_UP != 0 { + f |= FlagUp + } + if rawFlags&syscall.IFF_RUNNING != 0 { + f |= FlagRunning + } + if rawFlags&syscall.IFF_BROADCAST != 0 { + f |= FlagBroadcast + } + if rawFlags&syscall.IFF_LOOPBACK != 0 { + f |= FlagLoopback + } + if rawFlags&syscall.IFF_POINTOPOINT != 0 { + f |= FlagPointToPoint + } + if rawFlags&syscall.IFF_MULTICAST != 0 { + f |= FlagMulticast + } + return f +} + +// If the ifi is nil, interfaceAddrTable returns addresses for all +// network interfaces. Otherwise it returns addresses for a specific +// interface. +func interfaceAddrTable(ifi *Interface) ([]Addr, error) { + index := 0 + if ifi != nil { + index = ifi.Index + } + msgs, err := interfaceMessages(index) + if err != nil { + return nil, err + } + ifat := make([]Addr, 0, len(msgs)) + for _, m := range msgs { + switch m := m.(type) { + case *routebsd.InterfaceAddrMessage: + if index != 0 && index != m.Index { + continue + } + var mask IPMask + switch sa := m.Addrs[syscall.RTAX_NETMASK].(type) { + case *routebsd.InetAddr: + if sa.IP.Is4() { + a := sa.IP.As4() + mask = IPv4Mask(a[0], a[1], a[2], a[3]) + } else if sa.IP.Is6() { + a := sa.IP.As16() + mask = make(IPMask, IPv6len) + copy(mask, a[:]) + } + } + var ip IP + switch sa := m.Addrs[syscall.RTAX_IFA].(type) { + case *routebsd.InetAddr: + if sa.IP.Is4() { + a := sa.IP.As4() + ip = IPv4(a[0], a[1], a[2], a[3]) + } else if sa.IP.Is6() { + a := sa.IP.As16() + ip = make(IP, IPv6len) + copy(ip, a[:]) + } + } + if ip != nil && mask != nil { // NetBSD may contain routebsd.LinkAddr + ifat = append(ifat, &IPNet{IP: ip, Mask: mask}) + } + } + } + return ifat, nil +} diff --git a/go/src/net/interface_bsd_test.go b/go/src/net/interface_bsd_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ce59962f6108f42e50f4f740b368933dbd420b15 --- /dev/null +++ b/go/src/net/interface_bsd_test.go @@ -0,0 +1,60 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || dragonfly || freebsd || netbsd || openbsd + +package net + +import ( + "errors" + "fmt" + "os/exec" + "runtime" +) + +func (ti *testInterface) setBroadcast(vid int) error { + if runtime.GOOS == "openbsd" { + ti.name = fmt.Sprintf("vether%d", vid) + } else { + ti.name = fmt.Sprintf("vlan%d", vid) + } + xname, err := exec.LookPath("ifconfig") + if err != nil { + return err + } + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ifconfig", ti.name, "create"}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ifconfig", ti.name, "destroy"}, + }) + return nil +} + +func (ti *testInterface) setPointToPoint(suffix int) error { + ti.name = fmt.Sprintf("gif%d", suffix) + xname, err := exec.LookPath("ifconfig") + if err != nil { + return err + } + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ifconfig", ti.name, "create"}, + }) + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ifconfig", ti.name, "inet", ti.local, ti.remote}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ifconfig", ti.name, "destroy"}, + }) + return nil +} + +func (ti *testInterface) setLinkLocal(suffix int) error { + return errors.New("not yet implemented for BSD") +} diff --git a/go/src/net/interface_bsdvar.go b/go/src/net/interface_bsdvar.go new file mode 100644 index 0000000000000000000000000000000000000000..dc6c293a8e4b1abb4dfbc708eebfcdcc6f9a19c9 --- /dev/null +++ b/go/src/net/interface_bsdvar.go @@ -0,0 +1,23 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build dragonfly || netbsd || openbsd + +package net + +import ( + "internal/routebsd" + "syscall" +) + +func interfaceMessages(ifindex int) ([]routebsd.Message, error) { + return routebsd.FetchRIBMessages(syscall.NET_RT_IFLIST, ifindex) +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + // TODO(mikio): Implement this like other platforms. + return nil, nil +} diff --git a/go/src/net/interface_darwin.go b/go/src/net/interface_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..95c44e68e63a1ec9d478a38372f2e9d2ff8f8de2 --- /dev/null +++ b/go/src/net/interface_darwin.go @@ -0,0 +1,48 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/routebsd" + "syscall" +) + +func interfaceMessages(ifindex int) ([]routebsd.Message, error) { + return routebsd.FetchRIBMessages(syscall.NET_RT_IFLIST, ifindex) +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + msgs, err := routebsd.FetchRIBMessages(syscall.NET_RT_IFLIST2, ifi.Index) + if err != nil { + return nil, err + } + ifmat := make([]Addr, 0, len(msgs)) + for _, m := range msgs { + switch m := m.(type) { + case *routebsd.InterfaceMulticastAddrMessage: + if ifi.Index != m.Index { + continue + } + var ip IP + switch sa := m.Addrs[syscall.RTAX_IFA].(type) { + case *routebsd.InetAddr: + if sa.IP.Is4() { + a := sa.IP.As4() + ip = IPv4(a[0], a[1], a[2], a[3]) + } else if sa.IP.Is6() { + a := sa.IP.As16() + ip = make(IP, IPv6len) + copy(ip, a[:]) + } + } + if ip != nil { + ifmat = append(ifmat, &IPAddr{IP: ip}) + } + } + } + return ifmat, nil +} diff --git a/go/src/net/interface_freebsd.go b/go/src/net/interface_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..301faa47baef791d3768b1254496e6e30683b692 --- /dev/null +++ b/go/src/net/interface_freebsd.go @@ -0,0 +1,48 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/routebsd" + "syscall" +) + +func interfaceMessages(ifindex int) ([]routebsd.Message, error) { + return routebsd.FetchRIBMessages(syscall.NET_RT_IFLIST, ifindex) +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + msgs, err := routebsd.FetchRIBMessages(syscall.NET_RT_IFMALIST, ifi.Index) + if err != nil { + return nil, err + } + ifmat := make([]Addr, 0, len(msgs)) + for _, m := range msgs { + switch m := m.(type) { + case *routebsd.InterfaceMulticastAddrMessage: + if ifi.Index != m.Index { + continue + } + var ip IP + switch sa := m.Addrs[syscall.RTAX_IFA].(type) { + case *routebsd.InetAddr: + if sa.IP.Is4() { + a := sa.IP.As4() + ip = IPv4(a[0], a[1], a[2], a[3]) + } else if sa.IP.Is6() { + a := sa.IP.As16() + ip = make(IP, IPv6len) + copy(ip, a[:]) + } + } + if ip != nil { + ifmat = append(ifmat, &IPAddr{IP: ip}) + } + } + } + return ifmat, nil +} diff --git a/go/src/net/interface_linux.go b/go/src/net/interface_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..7856dae8fc878b72a5444a069b53580498418d63 --- /dev/null +++ b/go/src/net/interface_linux.go @@ -0,0 +1,257 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "os" + "syscall" + "unsafe" +) + +// If the ifindex is zero, interfaceTable returns mappings of all +// network interfaces. Otherwise it returns a mapping of a specific +// interface. +func interfaceTable(ifindex int) ([]Interface, error) { + tab, err := syscall.NetlinkRIB(syscall.RTM_GETLINK, syscall.AF_UNSPEC) + if err != nil { + return nil, os.NewSyscallError("netlinkrib", err) + } + msgs, err := syscall.ParseNetlinkMessage(tab) + if err != nil { + return nil, os.NewSyscallError("parsenetlinkmessage", err) + } + var ift []Interface +loop: + for _, m := range msgs { + switch m.Header.Type { + case syscall.NLMSG_DONE: + break loop + case syscall.RTM_NEWLINK: + ifim := (*syscall.IfInfomsg)(unsafe.Pointer(&m.Data[0])) + if ifindex == 0 || ifindex == int(ifim.Index) { + attrs, err := syscall.ParseNetlinkRouteAttr(&m) + if err != nil { + return nil, os.NewSyscallError("parsenetlinkrouteattr", err) + } + ift = append(ift, *newLink(ifim, attrs)) + if ifindex == int(ifim.Index) { + break loop + } + } + } + } + return ift, nil +} + +const ( + // See linux/if_arp.h. + // Note that Linux doesn't support IPv4 over IPv6 tunneling. + sysARPHardwareIPv4IPv4 = 768 // IPv4 over IPv4 tunneling + sysARPHardwareIPv6IPv6 = 769 // IPv6 over IPv6 tunneling + sysARPHardwareIPv6IPv4 = 776 // IPv6 over IPv4 tunneling + sysARPHardwareGREIPv4 = 778 // any over GRE over IPv4 tunneling + sysARPHardwareGREIPv6 = 823 // any over GRE over IPv6 tunneling +) + +func newLink(ifim *syscall.IfInfomsg, attrs []syscall.NetlinkRouteAttr) *Interface { + ifi := &Interface{Index: int(ifim.Index), Flags: linkFlags(ifim.Flags)} + for _, a := range attrs { + switch a.Attr.Type { + case syscall.IFLA_ADDRESS: + // We never return any /32 or /128 IP address + // prefix on any IP tunnel interface as the + // hardware address. + switch len(a.Value) { + case IPv4len: + switch ifim.Type { + case sysARPHardwareIPv4IPv4, sysARPHardwareGREIPv4, sysARPHardwareIPv6IPv4: + continue + } + case IPv6len: + switch ifim.Type { + case sysARPHardwareIPv6IPv6, sysARPHardwareGREIPv6: + continue + } + } + var nonzero bool + for _, b := range a.Value { + if b != 0 { + nonzero = true + break + } + } + if nonzero { + ifi.HardwareAddr = a.Value[:] + } + case syscall.IFLA_IFNAME: + ifi.Name = string(a.Value[:len(a.Value)-1]) + case syscall.IFLA_MTU: + ifi.MTU = int(*(*uint32)(unsafe.Pointer(&a.Value[:4][0]))) + } + } + return ifi +} + +func linkFlags(rawFlags uint32) Flags { + var f Flags + if rawFlags&syscall.IFF_UP != 0 { + f |= FlagUp + } + if rawFlags&syscall.IFF_RUNNING != 0 { + f |= FlagRunning + } + if rawFlags&syscall.IFF_BROADCAST != 0 { + f |= FlagBroadcast + } + if rawFlags&syscall.IFF_LOOPBACK != 0 { + f |= FlagLoopback + } + if rawFlags&syscall.IFF_POINTOPOINT != 0 { + f |= FlagPointToPoint + } + if rawFlags&syscall.IFF_MULTICAST != 0 { + f |= FlagMulticast + } + return f +} + +// If the ifi is nil, interfaceAddrTable returns addresses for all +// network interfaces. Otherwise it returns addresses for a specific +// interface. +func interfaceAddrTable(ifi *Interface) ([]Addr, error) { + tab, err := syscall.NetlinkRIB(syscall.RTM_GETADDR, syscall.AF_UNSPEC) + if err != nil { + return nil, os.NewSyscallError("netlinkrib", err) + } + msgs, err := syscall.ParseNetlinkMessage(tab) + if err != nil { + return nil, os.NewSyscallError("parsenetlinkmessage", err) + } + ifat, err := addrTable(ifi, msgs) + if err != nil { + return nil, err + } + return ifat, nil +} + +func addrTable(ifi *Interface, msgs []syscall.NetlinkMessage) ([]Addr, error) { + var ifat []Addr +loop: + for _, m := range msgs { + switch m.Header.Type { + case syscall.NLMSG_DONE: + break loop + case syscall.RTM_NEWADDR: + ifam := (*syscall.IfAddrmsg)(unsafe.Pointer(&m.Data[0])) + if ifi == nil || ifi.Index == int(ifam.Index) { + attrs, err := syscall.ParseNetlinkRouteAttr(&m) + if err != nil { + return nil, os.NewSyscallError("parsenetlinkrouteattr", err) + } + ifa := newAddr(ifam, attrs) + if ifa != nil { + ifat = append(ifat, ifa) + } + } + } + } + return ifat, nil +} + +func newAddr(ifam *syscall.IfAddrmsg, attrs []syscall.NetlinkRouteAttr) Addr { + var ipPointToPoint bool + // Seems like we need to make sure whether the IP interface + // stack consists of IP point-to-point numbered or unnumbered + // addressing. + for _, a := range attrs { + if a.Attr.Type == syscall.IFA_LOCAL { + ipPointToPoint = true + break + } + } + for _, a := range attrs { + if ipPointToPoint && a.Attr.Type == syscall.IFA_ADDRESS { + continue + } + switch ifam.Family { + case syscall.AF_INET: + return &IPNet{IP: IPv4(a.Value[0], a.Value[1], a.Value[2], a.Value[3]), Mask: CIDRMask(int(ifam.Prefixlen), 8*IPv4len)} + case syscall.AF_INET6: + ifa := &IPNet{IP: make(IP, IPv6len), Mask: CIDRMask(int(ifam.Prefixlen), 8*IPv6len)} + copy(ifa.IP, a.Value[:]) + return ifa + } + } + return nil +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + ifmat4 := parseProcNetIGMP("/proc/net/igmp", ifi) + ifmat6 := parseProcNetIGMP6("/proc/net/igmp6", ifi) + return append(ifmat4, ifmat6...), nil +} + +func parseProcNetIGMP(path string, ifi *Interface) []Addr { + fd, err := open(path) + if err != nil { + return nil + } + defer fd.close() + var ( + ifmat []Addr + name string + ) + fd.readLine() // skip first line + b := make([]byte, IPv4len) + for l, ok := fd.readLine(); ok; l, ok = fd.readLine() { + f := splitAtBytes(l, " :\r\t\n") + if len(f) < 4 { + continue + } + switch { + case l[0] != ' ' && l[0] != '\t': // new interface line + name = f[1] + case len(f[0]) == 8: + if ifi == nil || name == ifi.Name { + // The Linux kernel puts the IP + // address in /proc/net/igmp in native + // endianness. + for i := 0; i+1 < len(f[0]); i += 2 { + b[i/2], _ = xtoi2(f[0][i:i+2], 0) + } + i := *(*uint32)(unsafe.Pointer(&b[:4][0])) + ifma := &IPAddr{IP: IPv4(byte(i>>24), byte(i>>16), byte(i>>8), byte(i))} + ifmat = append(ifmat, ifma) + } + } + } + return ifmat +} + +func parseProcNetIGMP6(path string, ifi *Interface) []Addr { + fd, err := open(path) + if err != nil { + return nil + } + defer fd.close() + var ifmat []Addr + b := make([]byte, IPv6len) + for l, ok := fd.readLine(); ok; l, ok = fd.readLine() { + f := splitAtBytes(l, " \r\t\n") + if len(f) < 6 { + continue + } + if ifi == nil || f[1] == ifi.Name { + for i := 0; i+1 < len(f[2]); i += 2 { + b[i/2], _ = xtoi2(f[2][i:i+2], 0) + } + ifma := &IPAddr{IP: IP{b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]}} + ifmat = append(ifmat, ifma) + } + } + return ifmat +} diff --git a/go/src/net/interface_linux_test.go b/go/src/net/interface_linux_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0699fec636833f8fe36469012ebb569222e60c1b --- /dev/null +++ b/go/src/net/interface_linux_test.go @@ -0,0 +1,133 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "fmt" + "os/exec" + "testing" +) + +func (ti *testInterface) setBroadcast(suffix int) error { + ti.name = fmt.Sprintf("gotest%d", suffix) + xname, err := exec.LookPath("ip") + if err != nil { + return err + } + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "link", "add", ti.name, "type", "dummy"}, + }) + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "address", "add", ti.local, "peer", ti.remote, "dev", ti.name}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "address", "del", ti.local, "peer", ti.remote, "dev", ti.name}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "link", "delete", ti.name, "type", "dummy"}, + }) + return nil +} + +func (ti *testInterface) setLinkLocal(suffix int) error { + ti.name = fmt.Sprintf("gotest%d", suffix) + xname, err := exec.LookPath("ip") + if err != nil { + return err + } + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "link", "add", ti.name, "type", "dummy"}, + }) + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "address", "add", ti.local, "dev", ti.name}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "address", "del", ti.local, "dev", ti.name}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "link", "delete", ti.name, "type", "dummy"}, + }) + return nil +} + +func (ti *testInterface) setPointToPoint(suffix int) error { + ti.name = fmt.Sprintf("gotest%d", suffix) + xname, err := exec.LookPath("ip") + if err != nil { + return err + } + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "tunnel", "add", ti.name, "mode", "gre", "local", ti.local, "remote", ti.remote}, + }) + ti.setupCmds = append(ti.setupCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "address", "add", ti.local, "peer", ti.remote, "dev", ti.name}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "address", "del", ti.local, "peer", ti.remote, "dev", ti.name}, + }) + ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{ + Path: xname, + Args: []string{"ip", "tunnel", "del", ti.name, "mode", "gre", "local", ti.local, "remote", ti.remote}, + }) + return nil +} + +const ( + numOfTestIPv4MCAddrs = 14 + numOfTestIPv6MCAddrs = 18 +) + +var ( + igmpInterfaceTable = []Interface{ + {Name: "lo"}, + {Name: "eth0"}, {Name: "eth1"}, {Name: "eth2"}, + {Name: "eth0.100"}, {Name: "eth0.101"}, {Name: "eth0.102"}, {Name: "eth0.103"}, + {Name: "device1tap2"}, + } + igmp6InterfaceTable = []Interface{ + {Name: "lo"}, + {Name: "eth0"}, {Name: "eth1"}, {Name: "eth2"}, + {Name: "eth0.100"}, {Name: "eth0.101"}, {Name: "eth0.102"}, {Name: "eth0.103"}, + {Name: "device1tap2"}, + {Name: "pan0"}, + } +) + +func TestParseProcNet(t *testing.T) { + defer func() { + if p := recover(); p != nil { + t.Fatalf("panicked: %v", p) + } + }() + + var ifmat4 []Addr + for _, ifi := range igmpInterfaceTable { + ifmat := parseProcNetIGMP("testdata/igmp", &ifi) + ifmat4 = append(ifmat4, ifmat...) + } + if len(ifmat4) != numOfTestIPv4MCAddrs { + t.Fatalf("got %d; want %d", len(ifmat4), numOfTestIPv4MCAddrs) + } + + var ifmat6 []Addr + for _, ifi := range igmp6InterfaceTable { + ifmat := parseProcNetIGMP6("testdata/igmp6", &ifi) + ifmat6 = append(ifmat6, ifmat...) + } + if len(ifmat6) != numOfTestIPv6MCAddrs { + t.Fatalf("got %d; want %d", len(ifmat6), numOfTestIPv6MCAddrs) + } +} diff --git a/go/src/net/interface_plan9.go b/go/src/net/interface_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..88f1325ab22039970f9ef80666f4c327aa658eda --- /dev/null +++ b/go/src/net/interface_plan9.go @@ -0,0 +1,212 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "internal/strconv" + "internal/stringslite" + "os" +) + +// If the ifindex is zero, interfaceTable returns mappings of all +// network interfaces. Otherwise it returns a mapping of a specific +// interface. +func interfaceTable(ifindex int) ([]Interface, error) { + if ifindex == 0 { + n, err := interfaceCount() + if err != nil { + return nil, err + } + ifcs := make([]Interface, n) + for i := range ifcs { + ifc, err := readInterface(i) + if err != nil { + return nil, err + } + ifcs[i] = *ifc + } + return ifcs, nil + } + + ifc, err := readInterface(ifindex - 1) + if err != nil { + return nil, err + } + return []Interface{*ifc}, nil +} + +func readInterface(i int) (*Interface, error) { + ifc := &Interface{ + Index: i + 1, // Offset the index by one to suit the contract + Name: netdir + "/ipifc/" + strconv.Itoa(i), // Name is the full path to the interface path in plan9 + } + + ifcstat := ifc.Name + "/status" + ifcstatf, err := open(ifcstat) + if err != nil { + return nil, err + } + defer ifcstatf.close() + + line, ok := ifcstatf.readLine() + if !ok { + return nil, errors.New("invalid interface status file: " + ifcstat) + } + + fields := getFields(line) + + // If the interface has no device file then we see two spaces between "device" and + // "maxtu" and getFields treats the two spaces as one delimiter. + // Insert a gap for the missing device name. + // See https://go.dev/issue/72060. + if stringslite.HasPrefix(line, "device maxtu ") { + fields = append(fields, "") + copy(fields[2:], fields[1:]) + fields[1] = "" + } + + if len(fields) < 4 { + return nil, errors.New("invalid interface status file: " + ifcstat) + } + + device := fields[1] + mtustr := fields[3] + + mtu, _, ok := dtoi(mtustr) + if !ok { + return nil, errors.New("invalid status file of interface: " + ifcstat) + } + ifc.MTU = mtu + + // Not a loopback device ("/dev/null") or packet interface (e.g. "pkt2") + if stringslite.HasPrefix(device, netdir+"/") { + deviceaddrf, err := open(device + "/addr") + if err != nil { + return nil, err + } + defer deviceaddrf.close() + + line, ok = deviceaddrf.readLine() + if !ok { + return nil, errors.New("invalid address file for interface: " + device + "/addr") + } + + if len(line) > 0 && len(line)%2 == 0 { + ifc.HardwareAddr = make([]byte, len(line)/2) + var ok bool + for i := range ifc.HardwareAddr { + j := (i + 1) * 2 + ifc.HardwareAddr[i], ok = xtoi2(line[i*2:j], 0) + if !ok { + ifc.HardwareAddr = ifc.HardwareAddr[:i] + break + } + } + } + + ifc.Flags = FlagUp | FlagRunning | FlagBroadcast | FlagMulticast + } else { + ifc.Flags = FlagUp | FlagRunning | FlagMulticast | FlagLoopback + } + + return ifc, nil +} + +func interfaceCount() (int, error) { + d, err := os.Open(netdir + "/ipifc") + if err != nil { + return -1, err + } + defer d.Close() + + names, err := d.Readdirnames(0) + if err != nil { + return -1, err + } + + // Assumes that numbered files in ipifc are strictly + // the incrementing numbered directories for the + // interfaces + c := 0 + for _, name := range names { + if _, _, ok := dtoi(name); !ok { + continue + } + c++ + } + + return c, nil +} + +// If the ifi is nil, interfaceAddrTable returns addresses for all +// network interfaces. Otherwise it returns addresses for a specific +// interface. +func interfaceAddrTable(ifi *Interface) ([]Addr, error) { + var ifcs []Interface + if ifi == nil { + var err error + ifcs, err = interfaceTable(0) + if err != nil { + return nil, err + } + } else { + ifcs = []Interface{*ifi} + } + + var addrs []Addr + for _, ifc := range ifcs { + status := ifc.Name + "/status" + statusf, err := open(status) + if err != nil { + return nil, err + } + defer statusf.close() + + // Read but ignore first line as it only contains the table header. + // See https://9p.io/magic/man2html/3/ip + if _, ok := statusf.readLine(); !ok { + return nil, errors.New("cannot read header line for interface: " + status) + } + + for line, ok := statusf.readLine(); ok; line, ok = statusf.readLine() { + fields := getFields(line) + if len(fields) < 1 { + continue + } + addr := fields[0] + ip := ParseIP(addr) + if ip == nil { + return nil, errors.New("cannot parse IP address for interface: " + status) + } + + // The mask is represented as CIDR relative to the IPv6 address. + // Plan 9 internal representation is always IPv6. + maskfld := fields[1] + maskfld = maskfld[1:] + pfxlen, _, ok := dtoi(maskfld) + if !ok { + return nil, errors.New("cannot parse network mask for interface: " + status) + } + var mask IPMask + if ip.To4() != nil { // IPv4 or IPv6 IPv4-mapped address + mask = CIDRMask(pfxlen-8*len(v4InV6Prefix), 8*IPv4len) + } + if ip.To16() != nil && ip.To4() == nil { // IPv6 address + mask = CIDRMask(pfxlen, 8*IPv6len) + } + + addrs = append(addrs, &IPNet{IP: ip, Mask: mask}) + } + } + + return addrs, nil +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + return nil, nil +} diff --git a/go/src/net/interface_solaris.go b/go/src/net/interface_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..32f503f45b29bac6857cd1e93f142747cc0fed4f --- /dev/null +++ b/go/src/net/interface_solaris.go @@ -0,0 +1,92 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "syscall" + + "golang.org/x/net/lif" +) + +// If the ifindex is zero, interfaceTable returns mappings of all +// network interfaces. Otherwise it returns a mapping of a specific +// interface. +func interfaceTable(ifindex int) ([]Interface, error) { + lls, err := lif.Links(syscall.AF_UNSPEC, "") + if err != nil { + return nil, err + } + var ift []Interface + for _, ll := range lls { + if ifindex != 0 && ifindex != ll.Index { + continue + } + ifi := Interface{Index: ll.Index, MTU: ll.MTU, Name: ll.Name, Flags: linkFlags(ll.Flags)} + if len(ll.Addr) > 0 { + ifi.HardwareAddr = HardwareAddr(ll.Addr) + } + ift = append(ift, ifi) + } + return ift, nil +} + +func linkFlags(rawFlags int) Flags { + var f Flags + if rawFlags&syscall.IFF_UP != 0 { + f |= FlagUp + } + if rawFlags&syscall.IFF_RUNNING != 0 { + f |= FlagRunning + } + if rawFlags&syscall.IFF_BROADCAST != 0 { + f |= FlagBroadcast + } + if rawFlags&syscall.IFF_LOOPBACK != 0 { + f |= FlagLoopback + } + if rawFlags&syscall.IFF_POINTOPOINT != 0 { + f |= FlagPointToPoint + } + if rawFlags&syscall.IFF_MULTICAST != 0 { + f |= FlagMulticast + } + return f +} + +// If the ifi is nil, interfaceAddrTable returns addresses for all +// network interfaces. Otherwise it returns addresses for a specific +// interface. +func interfaceAddrTable(ifi *Interface) ([]Addr, error) { + var name string + if ifi != nil { + name = ifi.Name + } + as, err := lif.Addrs(syscall.AF_UNSPEC, name) + if err != nil { + return nil, err + } + var ifat []Addr + for _, a := range as { + var ip IP + var mask IPMask + switch a := a.(type) { + case *lif.Inet4Addr: + ip = IPv4(a.IP[0], a.IP[1], a.IP[2], a.IP[3]) + mask = CIDRMask(a.PrefixLen, 8*IPv4len) + case *lif.Inet6Addr: + ip = make(IP, IPv6len) + copy(ip, a.IP[:]) + mask = CIDRMask(a.PrefixLen, 8*IPv6len) + } + ifat = append(ifat, &IPNet{IP: ip, Mask: mask}) + } + return ifat, nil +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + return nil, nil +} diff --git a/go/src/net/interface_stub.go b/go/src/net/interface_stub.go new file mode 100644 index 0000000000000000000000000000000000000000..4c280c6ff2efa48250d0a60359165fe32430a616 --- /dev/null +++ b/go/src/net/interface_stub.go @@ -0,0 +1,27 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js || wasip1 + +package net + +// If the ifindex is zero, interfaceTable returns mappings of all +// network interfaces. Otherwise it returns a mapping of a specific +// interface. +func interfaceTable(ifindex int) ([]Interface, error) { + return nil, nil +} + +// If the ifi is nil, interfaceAddrTable returns addresses for all +// network interfaces. Otherwise it returns addresses for a specific +// interface. +func interfaceAddrTable(ifi *Interface) ([]Addr, error) { + return nil, nil +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + return nil, nil +} diff --git a/go/src/net/interface_test.go b/go/src/net/interface_test.go new file mode 100644 index 0000000000000000000000000000000000000000..72befca0d89c9543c56c90d17d1cc307fcf1f243 --- /dev/null +++ b/go/src/net/interface_test.go @@ -0,0 +1,382 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "fmt" + "reflect" + "runtime" + "testing" +) + +// loopbackInterface returns an available logical network interface +// for loopback tests. It returns nil if no suitable interface is +// found. +func loopbackInterface() *Interface { + ift, err := Interfaces() + if err != nil { + return nil + } + for _, ifi := range ift { + if ifi.Flags&FlagLoopback != 0 && ifi.Flags&FlagUp != 0 { + return &ifi + } + } + return nil +} + +// ipv6LinkLocalUnicastAddr returns an IPv6 link-local unicast address +// on the given network interface for tests. It returns "" if no +// suitable address is found. +func ipv6LinkLocalUnicastAddr(ifi *Interface) string { + if ifi == nil { + return "" + } + ifat, err := ifi.Addrs() + if err != nil { + return "" + } + for _, ifa := range ifat { + if ifa, ok := ifa.(*IPNet); ok { + if ifa.IP.To4() == nil && ifa.IP.IsLinkLocalUnicast() { + return ifa.IP.String() + } + } + } + return "" +} + +func TestInterfaces(t *testing.T) { + ift, err := Interfaces() + if err != nil { + t.Fatal(err) + } + for _, ifi := range ift { + ifxi, err := InterfaceByIndex(ifi.Index) + if err != nil { + t.Fatal(err) + } + switch runtime.GOOS { + case "solaris", "illumos": + if ifxi.Index != ifi.Index { + t.Errorf("got %v; want %v", ifxi, ifi) + } + default: + if !reflect.DeepEqual(ifxi, &ifi) { + t.Errorf("got %v; want %v", ifxi, ifi) + } + } + if ifi.Name != "" { + ifxn, err := InterfaceByName(ifi.Name) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(ifxn, &ifi) { + t.Errorf("got %v; want %v", ifxn, ifi) + } + } + t.Logf("%s: flags=%v index=%d mtu=%d hwaddr=%v", ifi.Name, ifi.Flags, ifi.Index, ifi.MTU, ifi.HardwareAddr) + } +} + +func TestInterfaceAddrs(t *testing.T) { + ift, err := Interfaces() + if err != nil { + t.Fatal(err) + } + ifStats := interfaceStats(ift) + ifat, err := InterfaceAddrs() + if err != nil { + t.Fatal(err) + } + uniStats, err := validateInterfaceUnicastAddrs(ifat) + if err != nil { + t.Fatal(err) + } + if err := checkUnicastStats(ifStats, uniStats); err != nil { + t.Fatal(err) + } +} + +func TestInterfaceUnicastAddrs(t *testing.T) { + ift, err := Interfaces() + if err != nil { + t.Fatal(err) + } + ifStats := interfaceStats(ift) + if err != nil { + t.Fatal(err) + } + var uniStats routeStats + for _, ifi := range ift { + ifat, err := ifi.Addrs() + if err != nil { + t.Fatal(ifi, err) + } + stats, err := validateInterfaceUnicastAddrs(ifat) + if err != nil { + t.Fatal(ifi, err) + } + uniStats.ipv4 += stats.ipv4 + uniStats.ipv6 += stats.ipv6 + } + if err := checkUnicastStats(ifStats, &uniStats); err != nil { + t.Fatal(err) + } +} + +func TestInterfaceMulticastAddrs(t *testing.T) { + ift, err := Interfaces() + if err != nil { + t.Fatal(err) + } + ifStats := interfaceStats(ift) + ifat, err := InterfaceAddrs() + if err != nil { + t.Fatal(err) + } + uniStats, err := validateInterfaceUnicastAddrs(ifat) + if err != nil { + t.Fatal(err) + } + var multiStats routeStats + for _, ifi := range ift { + ifmat, err := ifi.MulticastAddrs() + if err != nil { + t.Fatal(ifi, err) + } + stats, err := validateInterfaceMulticastAddrs(ifmat) + if err != nil { + t.Fatal(ifi, err) + } + multiStats.ipv4 += stats.ipv4 + multiStats.ipv6 += stats.ipv6 + } + if err := checkMulticastStats(ifStats, uniStats, &multiStats); err != nil { + t.Fatal(err) + } +} + +type ifStats struct { + loop int // # of active loopback interfaces + other int // # of active other interfaces +} + +func interfaceStats(ift []Interface) *ifStats { + var stats ifStats + for _, ifi := range ift { + if ifi.Flags&FlagUp != 0 { + if ifi.Flags&FlagLoopback != 0 { + stats.loop++ + } else { + stats.other++ + } + } + } + return &stats +} + +type routeStats struct { + ipv4, ipv6 int // # of active connected unicast, anycast or multicast routes +} + +func validateInterfaceUnicastAddrs(ifat []Addr) (*routeStats, error) { + // Note: BSD variants allow assigning any IPv4/IPv6 address + // prefix to IP interface. For example, + // - 0.0.0.0/0 through 255.255.255.255/32 + // - ::/0 through ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128 + // In other words, there is no tightly-coupled combination of + // interface address prefixes and connected routes. + stats := new(routeStats) + for _, ifa := range ifat { + switch ifa := ifa.(type) { + case *IPNet: + if ifa == nil || ifa.IP == nil || ifa.IP.IsMulticast() || ifa.Mask == nil { + return nil, fmt.Errorf("unexpected value: %#v", ifa) + } + if len(ifa.IP) != IPv6len { + return nil, fmt.Errorf("should be internal representation either IPv6 or IPv4-mapped IPv6 address: %#v", ifa) + } + prefixLen, maxPrefixLen := ifa.Mask.Size() + if ifa.IP.To4() != nil { + if 0 >= prefixLen || prefixLen > 8*IPv4len || maxPrefixLen != 8*IPv4len { + return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa) + } + if ifa.IP.IsLoopback() && prefixLen < 8 { // see RFC 1122 + return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa) + } + stats.ipv4++ + } + if ifa.IP.To16() != nil && ifa.IP.To4() == nil { + if 0 >= prefixLen || prefixLen > 8*IPv6len || maxPrefixLen != 8*IPv6len { + return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa) + } + if ifa.IP.IsLoopback() && prefixLen != 8*IPv6len { // see RFC 4291 + return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa) + } + stats.ipv6++ + } + case *IPAddr: + if ifa == nil || ifa.IP == nil || ifa.IP.IsMulticast() { + return nil, fmt.Errorf("unexpected value: %#v", ifa) + } + if len(ifa.IP) != IPv6len { + return nil, fmt.Errorf("should be internal representation either IPv6 or IPv4-mapped IPv6 address: %#v", ifa) + } + if ifa.IP.To4() != nil { + stats.ipv4++ + } + if ifa.IP.To16() != nil && ifa.IP.To4() == nil { + stats.ipv6++ + } + default: + return nil, fmt.Errorf("unexpected type: %T", ifa) + } + } + return stats, nil +} + +func validateInterfaceMulticastAddrs(ifat []Addr) (*routeStats, error) { + stats := new(routeStats) + for _, ifa := range ifat { + switch ifa := ifa.(type) { + case *IPAddr: + if ifa == nil || ifa.IP == nil || ifa.IP.IsUnspecified() || !ifa.IP.IsMulticast() { + return nil, fmt.Errorf("unexpected value: %#v", ifa) + } + if len(ifa.IP) != IPv6len { + return nil, fmt.Errorf("should be internal representation either IPv6 or IPv4-mapped IPv6 address: %#v", ifa) + } + if ifa.IP.To4() != nil { + stats.ipv4++ + } + if ifa.IP.To16() != nil && ifa.IP.To4() == nil { + stats.ipv6++ + } + default: + return nil, fmt.Errorf("unexpected type: %T", ifa) + } + } + return stats, nil +} + +func checkUnicastStats(ifStats *ifStats, uniStats *routeStats) error { + // Test the existence of connected unicast routes for IPv4. + if supportsIPv4() && ifStats.loop+ifStats.other > 0 && uniStats.ipv4 == 0 { + return fmt.Errorf("num IPv4 unicast routes = 0; want >0; summary: %+v, %+v", ifStats, uniStats) + } + // Test the existence of connected unicast routes for IPv6. + // We can assume the existence of ::1/128 when at least one + // loopback interface is installed. + if supportsIPv6() && ifStats.loop > 0 && uniStats.ipv6 == 0 { + return fmt.Errorf("num IPv6 unicast routes = 0; want >0; summary: %+v, %+v", ifStats, uniStats) + } + return nil +} + +func checkMulticastStats(ifStats *ifStats, uniStats, multiStats *routeStats) error { + switch runtime.GOOS { + case "aix", "dragonfly", "netbsd", "openbsd", "plan9", "solaris", "illumos": + default: + // Test the existence of connected multicast route + // clones for IPv4. Unlike IPv6, IPv4 multicast + // capability is not a mandatory feature, and so IPv4 + // multicast validation is ignored and we only check + // IPv6 below. + // + // Test the existence of connected multicast route + // clones for IPv6. Some platform never uses loopback + // interface as the nexthop for multicast routing. + // We can assume the existence of connected multicast + // route clones when at least two connected unicast + // routes, ::1/128 and other, are installed. + if supportsIPv6() && ifStats.loop > 0 && uniStats.ipv6 > 1 && multiStats.ipv6 == 0 { + return fmt.Errorf("num IPv6 multicast route clones = 0; want >0; summary: %+v, %+v, %+v", ifStats, uniStats, multiStats) + } + } + return nil +} + +func BenchmarkInterfaces(b *testing.B) { + b.ReportAllocs() + testHookUninstaller.Do(uninstallTestHooks) + + for i := 0; i < b.N; i++ { + if _, err := Interfaces(); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkInterfaceByIndex(b *testing.B) { + b.ReportAllocs() + testHookUninstaller.Do(uninstallTestHooks) + + ifi := loopbackInterface() + if ifi == nil { + b.Skip("loopback interface not found") + } + for i := 0; i < b.N; i++ { + if _, err := InterfaceByIndex(ifi.Index); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkInterfaceByName(b *testing.B) { + b.ReportAllocs() + testHookUninstaller.Do(uninstallTestHooks) + + ifi := loopbackInterface() + if ifi == nil { + b.Skip("loopback interface not found") + } + for i := 0; i < b.N; i++ { + if _, err := InterfaceByName(ifi.Name); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkInterfaceAddrs(b *testing.B) { + b.ReportAllocs() + testHookUninstaller.Do(uninstallTestHooks) + + for i := 0; i < b.N; i++ { + if _, err := InterfaceAddrs(); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkInterfacesAndAddrs(b *testing.B) { + b.ReportAllocs() + testHookUninstaller.Do(uninstallTestHooks) + + ifi := loopbackInterface() + if ifi == nil { + b.Skip("loopback interface not found") + } + for i := 0; i < b.N; i++ { + if _, err := ifi.Addrs(); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkInterfacesAndMulticastAddrs(b *testing.B) { + b.ReportAllocs() + testHookUninstaller.Do(uninstallTestHooks) + + ifi := loopbackInterface() + if ifi == nil { + b.Skip("loopback interface not found") + } + for i := 0; i < b.N; i++ { + if _, err := ifi.MulticastAddrs(); err != nil { + b.Fatal(err) + } + } +} diff --git a/go/src/net/interface_unix_test.go b/go/src/net/interface_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b0a9bcf253d1ce20f7c08c3e976d7f28abf5de62 --- /dev/null +++ b/go/src/net/interface_unix_test.go @@ -0,0 +1,215 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd + +package net + +import ( + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "testing" + "time" +) + +type testInterface struct { + name string + local string + remote string + setupCmds []*exec.Cmd + teardownCmds []*exec.Cmd +} + +func (ti *testInterface) setup() error { + for _, cmd := range ti.setupCmds { + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("args=%v out=%q err=%v", cmd.Args, string(out), err) + } + } + return nil +} + +func (ti *testInterface) teardown() error { + for _, cmd := range ti.teardownCmds { + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("args=%v out=%q err=%v ", cmd.Args, string(out), err) + } + } + return nil +} + +func TestPointToPointInterface(t *testing.T) { + if testing.Short() { + t.Skip("avoid external network") + } + if runtime.GOOS == "darwin" || runtime.GOOS == "ios" { + t.Skipf("not supported on %s", runtime.GOOS) + } + if os.Getuid() != 0 { + t.Skip("must be root") + } + + // We suppose that using IPv4 link-local addresses doesn't + // harm anyone. + local, remote := "169.254.0.1", "169.254.0.254" + ip := ParseIP(remote) + for i := 0; i < 3; i++ { + ti := &testInterface{local: local, remote: remote} + if err := ti.setPointToPoint(5963 + i); err != nil { + t.Skipf("test requires external command: %v", err) + } + if err := ti.setup(); err != nil { + if e := err.Error(); strings.Contains(e, "No such device") && strings.Contains(e, "gre0") { + t.Skip("skipping test; no gre0 device. likely running in container?") + } + t.Fatal(err) + } else { + time.Sleep(3 * time.Millisecond) + } + ift, err := Interfaces() + if err != nil { + ti.teardown() + t.Fatal(err) + } + for _, ifi := range ift { + if ti.name != ifi.Name { + continue + } + ifat, err := ifi.Addrs() + if err != nil { + ti.teardown() + t.Fatal(err) + } + for _, ifa := range ifat { + if ip.Equal(ifa.(*IPNet).IP) { + ti.teardown() + t.Fatalf("got %v", ifa) + } + } + } + if err := ti.teardown(); err != nil { + t.Fatal(err) + } else { + time.Sleep(3 * time.Millisecond) + } + } +} + +func TestInterfaceArrivalAndDeparture(t *testing.T) { + if testing.Short() { + t.Skip("avoid external network") + } + if os.Getuid() != 0 { + t.Skip("must be root") + } + + // We suppose that using IPv4 link-local addresses and the + // dot1Q ID for Token Ring and FDDI doesn't harm anyone. + local, remote := "169.254.0.1", "169.254.0.254" + ip := ParseIP(remote) + for _, vid := range []int{1002, 1003, 1004, 1005} { + ift1, err := Interfaces() + if err != nil { + t.Fatal(err) + } + ti := &testInterface{local: local, remote: remote} + if err := ti.setBroadcast(vid); err != nil { + t.Skipf("test requires external command: %v", err) + } + if err := ti.setup(); err != nil { + t.Fatal(err) + } else { + time.Sleep(3 * time.Millisecond) + } + ift2, err := Interfaces() + if err != nil { + ti.teardown() + t.Fatal(err) + } + if len(ift2) <= len(ift1) { + for _, ifi := range ift1 { + t.Logf("before: %v", ifi) + } + for _, ifi := range ift2 { + t.Logf("after: %v", ifi) + } + ti.teardown() + t.Fatalf("got %v; want gt %v", len(ift2), len(ift1)) + } + for _, ifi := range ift2 { + if ti.name != ifi.Name { + continue + } + ifat, err := ifi.Addrs() + if err != nil { + ti.teardown() + t.Fatal(err) + } + for _, ifa := range ifat { + if ip.Equal(ifa.(*IPNet).IP) { + ti.teardown() + t.Fatalf("got %v", ifa) + } + } + } + if err := ti.teardown(); err != nil { + t.Fatal(err) + } else { + time.Sleep(3 * time.Millisecond) + } + ift3, err := Interfaces() + if err != nil { + t.Fatal(err) + } + if len(ift3) >= len(ift2) { + for _, ifi := range ift2 { + t.Logf("before: %v", ifi) + } + for _, ifi := range ift3 { + t.Logf("after: %v", ifi) + } + t.Fatalf("got %v; want lt %v", len(ift3), len(ift2)) + } + } +} + +func TestInterfaceArrivalAndDepartureZoneCache(t *testing.T) { + if testing.Short() { + t.Skip("avoid external network") + } + if os.Getuid() != 0 { + t.Skip("must be root") + } + + // Ensure zoneCache is filled: + _, _ = Listen("tcp", "[fe80::1%nonexistent]:0") + + ti := &testInterface{local: "fe80::1"} + if err := ti.setLinkLocal(0); err != nil { + t.Skipf("test requires external command: %v", err) + } + if err := ti.setup(); err != nil { + if e := err.Error(); strings.Contains(e, "Permission denied") { + t.Skipf("permission denied, skipping test: %v", e) + } + t.Fatal(err) + } + defer ti.teardown() + + time.Sleep(3 * time.Millisecond) + + // If Listen fails (on Linux with “bind: invalid argument”), zoneCache was + // not updated when encountering a nonexistent interface: + ln, err := Listen("tcp", "[fe80::1%"+ti.name+"]:0") + if err != nil { + t.Fatal(err) + } + ln.Close() + if err := ti.teardown(); err != nil { + t.Fatal(err) + } +} diff --git a/go/src/net/interface_windows.go b/go/src/net/interface_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..7a5cb5723f1b6bce3239a7ed30fe0d7b5074f25d --- /dev/null +++ b/go/src/net/interface_windows.go @@ -0,0 +1,179 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/syscall/windows" + "os" + "syscall" + "unsafe" +) + +// adapterAddresses returns a list of IP adapter and address +// structures. The structure contains an IP adapter and flattened +// multiple IP addresses including unicast, anycast and multicast +// addresses. +func adapterAddresses() ([]*windows.IpAdapterAddresses, error) { + var b []byte + l := uint32(15000) // recommended initial size + for { + b = make([]byte, l) + const flags = windows.GAA_FLAG_INCLUDE_PREFIX | windows.GAA_FLAG_INCLUDE_GATEWAYS + err := windows.GetAdaptersAddresses(syscall.AF_UNSPEC, flags, nil, (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])), &l) + if err == nil { + if l == 0 { + return nil, nil + } + break + } + if err.(syscall.Errno) != syscall.ERROR_BUFFER_OVERFLOW { + return nil, os.NewSyscallError("getadaptersaddresses", err) + } + if l <= uint32(len(b)) { + return nil, os.NewSyscallError("getadaptersaddresses", err) + } + } + var aas []*windows.IpAdapterAddresses + for aa := (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])); aa != nil; aa = aa.Next { + aas = append(aas, aa) + } + return aas, nil +} + +// If the ifindex is zero, interfaceTable returns mappings of all +// network interfaces. Otherwise it returns a mapping of a specific +// interface. +func interfaceTable(ifindex int) ([]Interface, error) { + aas, err := adapterAddresses() + if err != nil { + return nil, err + } + var ift []Interface + for _, aa := range aas { + index := aa.IfIndex + if index == 0 { // ipv6IfIndex is a substitute for ifIndex + index = aa.Ipv6IfIndex + } + if ifindex == 0 || ifindex == int(index) { + ifi := Interface{ + Index: int(index), + Name: windows.UTF16PtrToString(aa.FriendlyName), + } + if aa.OperStatus == windows.IfOperStatusUp { + ifi.Flags |= FlagUp + ifi.Flags |= FlagRunning + } + // For now we need to infer link-layer service + // capabilities from media types. + // TODO: use MIB_IF_ROW2.AccessType now that we no longer support + // Windows XP. + switch aa.IfType { + case windows.IF_TYPE_ETHERNET_CSMACD, windows.IF_TYPE_ISO88025_TOKENRING, windows.IF_TYPE_IEEE80211, windows.IF_TYPE_IEEE1394: + ifi.Flags |= FlagBroadcast | FlagMulticast + case windows.IF_TYPE_PPP, windows.IF_TYPE_TUNNEL: + ifi.Flags |= FlagPointToPoint | FlagMulticast + case windows.IF_TYPE_SOFTWARE_LOOPBACK: + ifi.Flags |= FlagLoopback | FlagMulticast + case windows.IF_TYPE_ATM: + ifi.Flags |= FlagBroadcast | FlagPointToPoint | FlagMulticast // assume all services available; LANE, point-to-point and point-to-multipoint + } + if aa.Mtu == 0xffffffff { + ifi.MTU = -1 + } else { + ifi.MTU = int(aa.Mtu) + } + if aa.PhysicalAddressLength > 0 { + ifi.HardwareAddr = make(HardwareAddr, aa.PhysicalAddressLength) + copy(ifi.HardwareAddr, aa.PhysicalAddress[:]) + } + ift = append(ift, ifi) + if ifindex == ifi.Index { + break + } + } + } + return ift, nil +} + +// If the ifi is nil, interfaceAddrTable returns addresses for all +// network interfaces. Otherwise it returns addresses for a specific +// interface. +func interfaceAddrTable(ifi *Interface) ([]Addr, error) { + aas, err := adapterAddresses() + if err != nil { + return nil, err + } + var ifat []Addr + for _, aa := range aas { + index := aa.IfIndex + if index == 0 { // ipv6IfIndex is a substitute for ifIndex + index = aa.Ipv6IfIndex + } + if ifi == nil || ifi.Index == int(index) { + for puni := aa.FirstUnicastAddress; puni != nil; puni = puni.Next { + sa, err := puni.Address.Sockaddr.Sockaddr() + if err != nil { + return nil, os.NewSyscallError("sockaddr", err) + } + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + ifat = append(ifat, &IPNet{IP: IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3]), Mask: CIDRMask(int(puni.OnLinkPrefixLength), 8*IPv4len)}) + case *syscall.SockaddrInet6: + ifa := &IPNet{IP: make(IP, IPv6len), Mask: CIDRMask(int(puni.OnLinkPrefixLength), 8*IPv6len)} + copy(ifa.IP, sa.Addr[:]) + ifat = append(ifat, ifa) + } + } + for pany := aa.FirstAnycastAddress; pany != nil; pany = pany.Next { + sa, err := pany.Address.Sockaddr.Sockaddr() + if err != nil { + return nil, os.NewSyscallError("sockaddr", err) + } + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + ifat = append(ifat, &IPAddr{IP: IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3])}) + case *syscall.SockaddrInet6: + ifa := &IPAddr{IP: make(IP, IPv6len)} + copy(ifa.IP, sa.Addr[:]) + ifat = append(ifat, ifa) + } + } + } + } + return ifat, nil +} + +// interfaceMulticastAddrTable returns addresses for a specific +// interface. +func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) { + aas, err := adapterAddresses() + if err != nil { + return nil, err + } + var ifat []Addr + for _, aa := range aas { + index := aa.IfIndex + if index == 0 { // ipv6IfIndex is a substitute for ifIndex + index = aa.Ipv6IfIndex + } + if ifi == nil || ifi.Index == int(index) { + for pmul := aa.FirstMulticastAddress; pmul != nil; pmul = pmul.Next { + sa, err := pmul.Address.Sockaddr.Sockaddr() + if err != nil { + return nil, os.NewSyscallError("sockaddr", err) + } + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + ifat = append(ifat, &IPAddr{IP: IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3])}) + case *syscall.SockaddrInet6: + ifa := &IPAddr{IP: make(IP, IPv6len)} + copy(ifa.IP, sa.Addr[:]) + ifat = append(ifat, ifa) + } + } + } + } + return ifat, nil +} diff --git a/go/src/net/ip.go b/go/src/net/ip.go new file mode 100644 index 0000000000000000000000000000000000000000..7d58e89e112786d8b38cdb1db85d6ed73afc6601 --- /dev/null +++ b/go/src/net/ip.go @@ -0,0 +1,574 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// IP address manipulations +// +// IPv4 addresses are 4 bytes; IPv6 addresses are 16 bytes. +// An IPv4 address can be converted to an IPv6 address by +// adding a canonical prefix (10 zeros, 2 0xFFs). +// This library accepts either size of byte slice but always +// returns 16-byte addresses. + +package net + +import ( + "internal/bytealg" + "internal/strconv" + "internal/stringslite" + "net/netip" +) + +// IP address lengths (bytes). +const ( + IPv4len = 4 + IPv6len = 16 +) + +// An IP is a single IP address, a slice of bytes. +// Functions in this package accept either 4-byte (IPv4) +// or 16-byte (IPv6) slices as input. +// +// Note that in this documentation, referring to an +// IP address as an IPv4 address or an IPv6 address +// is a semantic property of the address, not just the +// length of the byte slice: a 16-byte slice can still +// be an IPv4 address. +type IP []byte + +// An IPMask is a bitmask that can be used to manipulate +// IP addresses for IP addressing and routing. +// +// See type [IPNet] and func [ParseCIDR] for details. +type IPMask []byte + +// An IPNet represents an IP network. +type IPNet struct { + IP IP // network number + Mask IPMask // network mask +} + +// IPv4 returns the IP address (in 16-byte form) of the +// IPv4 address a.b.c.d. +func IPv4(a, b, c, d byte) IP { + p := make(IP, IPv6len) + copy(p, v4InV6Prefix) + p[12] = a + p[13] = b + p[14] = c + p[15] = d + return p +} + +var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff} + +// IPv4Mask returns the IP mask (in 4-byte form) of the +// IPv4 mask a.b.c.d. +func IPv4Mask(a, b, c, d byte) IPMask { + p := make(IPMask, IPv4len) + p[0] = a + p[1] = b + p[2] = c + p[3] = d + return p +} + +// CIDRMask returns an [IPMask] consisting of 'ones' 1 bits +// followed by 0s up to a total length of 'bits' bits. +// For a mask of this form, CIDRMask is the inverse of [IPMask.Size]. +func CIDRMask(ones, bits int) IPMask { + if bits != 8*IPv4len && bits != 8*IPv6len { + return nil + } + if ones < 0 || ones > bits { + return nil + } + l := bits / 8 + m := make(IPMask, l) + n := uint(ones) + for i := 0; i < l; i++ { + if n >= 8 { + m[i] = 0xff + n -= 8 + continue + } + m[i] = ^byte(0xff >> n) + n = 0 + } + return m +} + +// Well-known IPv4 addresses +var ( + IPv4bcast = IPv4(255, 255, 255, 255) // limited broadcast + IPv4allsys = IPv4(224, 0, 0, 1) // all systems + IPv4allrouter = IPv4(224, 0, 0, 2) // all routers + IPv4zero = IPv4(0, 0, 0, 0) // all zeros +) + +// Well-known IPv6 addresses +var ( + IPv6zero = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + IPv6unspecified = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + IPv6loopback = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} + IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01} + IPv6linklocalallnodes = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01} + IPv6linklocalallrouters = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02} +) + +// IsUnspecified reports whether ip is an unspecified address, either +// the IPv4 address "0.0.0.0" or the IPv6 address "::". +func (ip IP) IsUnspecified() bool { + return ip.Equal(IPv4zero) || ip.Equal(IPv6unspecified) +} + +// IsLoopback reports whether ip is a loopback address. +func (ip IP) IsLoopback() bool { + if ip4 := ip.To4(); ip4 != nil { + return ip4[0] == 127 + } + return ip.Equal(IPv6loopback) +} + +// IsPrivate reports whether ip is a private address, according to +// RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). +func (ip IP) IsPrivate() bool { + if ip4 := ip.To4(); ip4 != nil { + // Following RFC 1918, Section 3. Private Address Space which says: + // The Internet Assigned Numbers Authority (IANA) has reserved the + // following three blocks of the IP address space for private internets: + // 10.0.0.0 - 10.255.255.255 (10/8 prefix) + // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) + // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) + return ip4[0] == 10 || + (ip4[0] == 172 && ip4[1]&0xf0 == 16) || + (ip4[0] == 192 && ip4[1] == 168) + } + // Following RFC 4193, Section 8. IANA Considerations which says: + // The IANA has assigned the FC00::/7 prefix to "Unique Local Unicast". + return len(ip) == IPv6len && ip[0]&0xfe == 0xfc +} + +// IsMulticast reports whether ip is a multicast address. +func (ip IP) IsMulticast() bool { + if ip4 := ip.To4(); ip4 != nil { + return ip4[0]&0xf0 == 0xe0 + } + return len(ip) == IPv6len && ip[0] == 0xff +} + +// IsInterfaceLocalMulticast reports whether ip is +// an interface-local multicast address. +func (ip IP) IsInterfaceLocalMulticast() bool { + return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x01 +} + +// IsLinkLocalMulticast reports whether ip is a link-local +// multicast address. +func (ip IP) IsLinkLocalMulticast() bool { + if ip4 := ip.To4(); ip4 != nil { + return ip4[0] == 224 && ip4[1] == 0 && ip4[2] == 0 + } + return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x02 +} + +// IsLinkLocalUnicast reports whether ip is a link-local +// unicast address. +func (ip IP) IsLinkLocalUnicast() bool { + if ip4 := ip.To4(); ip4 != nil { + return ip4[0] == 169 && ip4[1] == 254 + } + return len(ip) == IPv6len && ip[0] == 0xfe && ip[1]&0xc0 == 0x80 +} + +// IsGlobalUnicast reports whether ip is a global unicast +// address. +// +// The identification of global unicast addresses uses address type +// identification as defined in RFC 1122, RFC 4632 and RFC 4291 with +// the exception of IPv4 directed broadcast addresses. +// It returns true even if ip is in IPv4 private address space or +// local IPv6 unicast address space. +func (ip IP) IsGlobalUnicast() bool { + return (len(ip) == IPv4len || len(ip) == IPv6len) && + !ip.Equal(IPv4bcast) && + !ip.IsUnspecified() && + !ip.IsLoopback() && + !ip.IsMulticast() && + !ip.IsLinkLocalUnicast() +} + +// Is p all zeros? +func isZeros(p IP) bool { + for i := 0; i < len(p); i++ { + if p[i] != 0 { + return false + } + } + return true +} + +// To4 converts the IPv4 address ip to a 4-byte representation. +// If ip is not an IPv4 address, To4 returns nil. +func (ip IP) To4() IP { + if len(ip) == IPv4len { + return ip + } + if len(ip) == IPv6len && + isZeros(ip[0:10]) && + ip[10] == 0xff && + ip[11] == 0xff { + return ip[12:16] + } + return nil +} + +// To16 converts the IP address ip to a 16-byte representation. +// If ip is not an IP address (it is the wrong length), To16 returns nil. +func (ip IP) To16() IP { + if len(ip) == IPv4len { + return IPv4(ip[0], ip[1], ip[2], ip[3]) + } + if len(ip) == IPv6len { + return ip + } + return nil +} + +// Default route masks for IPv4. +var ( + classAMask = IPv4Mask(0xff, 0, 0, 0) + classBMask = IPv4Mask(0xff, 0xff, 0, 0) + classCMask = IPv4Mask(0xff, 0xff, 0xff, 0) +) + +// DefaultMask returns the default IP mask for the IP address ip. +// Only IPv4 addresses have default masks; DefaultMask returns +// nil if ip is not a valid IPv4 address. +func (ip IP) DefaultMask() IPMask { + if ip = ip.To4(); ip == nil { + return nil + } + switch { + case ip[0] < 0x80: + return classAMask + case ip[0] < 0xC0: + return classBMask + default: + return classCMask + } +} + +func allFF(b []byte) bool { + for _, c := range b { + if c != 0xff { + return false + } + } + return true +} + +// Mask returns the result of masking the IP address ip with mask. +func (ip IP) Mask(mask IPMask) IP { + if len(mask) == IPv6len && len(ip) == IPv4len && allFF(mask[:12]) { + mask = mask[12:] + } + if len(mask) == IPv4len && len(ip) == IPv6len && bytealg.Equal(ip[:12], v4InV6Prefix) { + ip = ip[12:] + } + n := len(ip) + if n != len(mask) { + return nil + } + out := make(IP, n) + for i := 0; i < n; i++ { + out[i] = ip[i] & mask[i] + } + return out +} + +// String returns the string form of the IP address ip. +// It returns one of 4 forms: +// - "", if ip has length 0 +// - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address +// - IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address +// - the hexadecimal form of ip, without punctuation, if no other cases apply +func (ip IP) String() string { + if len(ip) == 0 { + return "" + } + + if len(ip) != IPv4len && len(ip) != IPv6len { + return "?" + hexString(ip) + } + + var buf []byte + switch len(ip) { + case IPv4len: + const maxCap = len("255.255.255.255") + buf = make([]byte, 0, maxCap) + case IPv6len: + const maxCap = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") + buf = make([]byte, 0, maxCap) + } + buf = ip.appendTo(buf) + return string(buf) +} + +func hexString(b []byte) string { + s := make([]byte, len(b)*2) + for i, tn := range b { + s[i*2], s[i*2+1] = hexDigit[tn>>4], hexDigit[tn&0xf] + } + return string(s) +} + +// ipEmptyString is like ip.String except that it returns +// an empty string when ip is unset. +func ipEmptyString(ip IP) string { + if len(ip) == 0 { + return "" + } + return ip.String() +} + +// appendTo appends the string representation of ip to b and returns the expanded b +// If len(ip) != IPv4len or IPv6len, it appends nothing. +func (ip IP) appendTo(b []byte) []byte { + // If IPv4, use dotted notation. + if p4 := ip.To4(); len(p4) == IPv4len { + ip = p4 + } + addr, _ := netip.AddrFromSlice(ip) + return addr.AppendTo(b) +} + +// AppendText implements the [encoding.TextAppender] interface. +// The encoding is the same as returned by [IP.String], with one exception: +// When len(ip) is zero, it appends nothing. +func (ip IP) AppendText(b []byte) ([]byte, error) { + if len(ip) == 0 { + return b, nil + } + if len(ip) != IPv4len && len(ip) != IPv6len { + return b, &AddrError{Err: "invalid IP address", Addr: hexString(ip)} + } + + return ip.appendTo(b), nil +} + +// MarshalText implements the [encoding.TextMarshaler] interface. +// The encoding is the same as returned by [IP.String], with one exception: +// When len(ip) is zero, it returns an empty slice. +func (ip IP) MarshalText() ([]byte, error) { + // 24 is satisfied with all IPv4 addresses and short IPv6 addresses + b, err := ip.AppendText(make([]byte, 0, 24)) + if err != nil { + return nil, err + } + return b, nil +} + +// UnmarshalText implements the [encoding.TextUnmarshaler] interface. +// The IP address is expected in a form accepted by [ParseIP]. +func (ip *IP) UnmarshalText(text []byte) error { + if len(text) == 0 { + *ip = nil + return nil + } + s := string(text) + x := ParseIP(s) + if x == nil { + return &ParseError{Type: "IP address", Text: s} + } + *ip = x + return nil +} + +// Equal reports whether ip and x are the same IP address. +// An IPv4 address and that same address in IPv6 form are +// considered to be equal. +func (ip IP) Equal(x IP) bool { + if len(ip) == len(x) { + return bytealg.Equal(ip, x) + } + if len(ip) == IPv4len && len(x) == IPv6len { + return bytealg.Equal(x[0:12], v4InV6Prefix) && bytealg.Equal(ip, x[12:]) + } + if len(ip) == IPv6len && len(x) == IPv4len { + return bytealg.Equal(ip[0:12], v4InV6Prefix) && bytealg.Equal(ip[12:], x) + } + return false +} + +func (ip IP) matchAddrFamily(x IP) bool { + return ip.To4() != nil && x.To4() != nil || ip.To16() != nil && ip.To4() == nil && x.To16() != nil && x.To4() == nil +} + +// If mask is a sequence of 1 bits followed by 0 bits, +// return the number of 1 bits. +func simpleMaskLength(mask IPMask) int { + var n int + for i, v := range mask { + if v == 0xff { + n += 8 + continue + } + // found non-ff byte + // count 1 bits + for v&0x80 != 0 { + n++ + v <<= 1 + } + // rest must be 0 bits + if v != 0 { + return -1 + } + for i++; i < len(mask); i++ { + if mask[i] != 0 { + return -1 + } + } + break + } + return n +} + +// Size returns the number of leading ones and total bits in the mask. +// If the mask is not in the canonical form--ones followed by zeros--then +// Size returns 0, 0. +func (m IPMask) Size() (ones, bits int) { + ones, bits = simpleMaskLength(m), len(m)*8 + if ones == -1 { + return 0, 0 + } + return +} + +// String returns the hexadecimal form of m, with no punctuation. +func (m IPMask) String() string { + if len(m) == 0 { + return "" + } + return hexString(m) +} + +func networkNumberAndMask(n *IPNet) (ip IP, m IPMask) { + if ip = n.IP.To4(); ip == nil { + ip = n.IP + if len(ip) != IPv6len { + return nil, nil + } + } + m = n.Mask + switch len(m) { + case IPv4len: + if len(ip) != IPv4len { + return nil, nil + } + case IPv6len: + if len(ip) == IPv4len { + m = m[12:] + } + default: + return nil, nil + } + return +} + +// Contains reports whether the network includes ip. +func (n *IPNet) Contains(ip IP) bool { + nn, m := networkNumberAndMask(n) + if x := ip.To4(); x != nil { + ip = x + } + l := len(ip) + if l != len(nn) { + return false + } + for i := 0; i < l; i++ { + if nn[i]&m[i] != ip[i]&m[i] { + return false + } + } + return true +} + +// Network returns the address's network name, "ip+net". +func (n *IPNet) Network() string { return "ip+net" } + +// String returns the CIDR notation of n like "192.0.2.0/24" +// or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. +// If the mask is not in the canonical form, it returns the +// string which consists of an IP address, followed by a slash +// character and a mask expressed as hexadecimal form with no +// punctuation like "198.51.100.0/c000ff00". +func (n *IPNet) String() string { + if n == nil { + return "" + } + nn, m := networkNumberAndMask(n) + if nn == nil || m == nil { + return "" + } + l := simpleMaskLength(m) + if l == -1 { + return nn.String() + "/" + m.String() + } + return nn.String() + "/" + strconv.Itoa(l) +} + +// ParseIP parses s as an IP address, returning the result. +// The string s can be in IPv4 dotted decimal ("192.0.2.1"), IPv6 +// ("2001:db8::68"), or IPv4-mapped IPv6 ("::ffff:192.0.2.1") form. +// If s is not a valid textual representation of an IP address, +// ParseIP returns nil. The returned address is always 16 bytes, +// IPv4 addresses are returned in IPv4-mapped IPv6 form. +func ParseIP(s string) IP { + if addr, valid := parseIP(s); valid { + return IP(addr[:]) + } + return nil +} + +func parseIP(s string) ([16]byte, bool) { + ip, err := netip.ParseAddr(s) + if err != nil || ip.Zone() != "" { + return [16]byte{}, false + } + return ip.As16(), true +} + +// ParseCIDR parses s as a CIDR notation IP address and prefix length, +// like "192.0.2.0/24" or "2001:db8::/32", as defined in +// RFC 4632 and RFC 4291. +// +// It returns the IP address and the network implied by the IP and +// prefix length. +// For example, ParseCIDR("192.0.2.1/24") returns the IP address +// 192.0.2.1 and the network 192.0.2.0/24. +func ParseCIDR(s string) (IP, *IPNet, error) { + addr, mask, found := stringslite.Cut(s, "/") + if !found { + return nil, nil, &ParseError{Type: "CIDR address", Text: s} + } + + ipAddr, err := netip.ParseAddr(addr) + if err != nil || ipAddr.Zone() != "" { + return nil, nil, &ParseError{Type: "CIDR address", Text: s} + } + + n, i, ok := dtoi(mask) + if !ok || i != len(mask) || n < 0 || n > ipAddr.BitLen() { + return nil, nil, &ParseError{Type: "CIDR address", Text: s} + } + m := CIDRMask(n, ipAddr.BitLen()) + addr16 := ipAddr.As16() + return IP(addr16[:]), &IPNet{IP: IP(addr16[:]).Mask(m), Mask: m}, nil +} + +func copyIP(x IP) IP { + y := make(IP, len(x)) + copy(y, x) + return y +} diff --git a/go/src/net/ip_test.go b/go/src/net/ip_test.go new file mode 100644 index 0000000000000000000000000000000000000000..55c66fdf31e116903b8d8e90a93bcb41274a9810 --- /dev/null +++ b/go/src/net/ip_test.go @@ -0,0 +1,839 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "bytes" + "math/rand" + "reflect" + "runtime" + "testing" +) + +var parseIPTests = []struct { + in string + out IP +}{ + {"127.0.1.2", IPv4(127, 0, 1, 2)}, + {"127.0.0.1", IPv4(127, 0, 0, 1)}, + {"::ffff:127.1.2.3", IPv4(127, 1, 2, 3)}, + {"::ffff:7f01:0203", IPv4(127, 1, 2, 3)}, + {"0:0:0:0:0000:ffff:127.1.2.3", IPv4(127, 1, 2, 3)}, + {"0:0:0:0::ffff:127.1.2.3", IPv4(127, 1, 2, 3)}, + + {"2001:4860:0:2001::68", IP{0x20, 0x01, 0x48, 0x60, 0, 0, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0x68}}, + {"2001:4860:0000:2001:0000:0000:0000:0068", IP{0x20, 0x01, 0x48, 0x60, 0, 0, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0x68}}, + + {"-0.0.0.0", nil}, + {"0.-1.0.0", nil}, + {"0.0.-2.0", nil}, + {"0.0.0.-3", nil}, + {"127.0.0.256", nil}, + {"abc", nil}, + {"123:", nil}, + {"fe80::1%lo0", nil}, + {"fe80::1%911", nil}, + {"", nil}, + //6 zeroes in one group + {"0:0:0:0:000000:ffff:127.1.2.3", nil}, + //5 zeroes in one group edge case + {"0:0:0:0:00000:ffff:127.1.2.3", nil}, + {"a1:a2:a3:a4::b1:b2:b3:b4", nil}, // Issue 6628 + {"127.001.002.003", nil}, + {"::ffff:127.001.002.003", nil}, + {"123.000.000.000", nil}, + {"1.2..4", nil}, + {"0123.0.0.1", nil}, +} + +func TestParseIP(t *testing.T) { + for _, tt := range parseIPTests { + if out := ParseIP(tt.in); !reflect.DeepEqual(out, tt.out) { + t.Errorf("ParseIP(%q) = %v, want %v", tt.in, out, tt.out) + } + if tt.in == "" { + // Tested in TestMarshalEmptyIP below. + continue + } + var out IP + if err := out.UnmarshalText([]byte(tt.in)); !reflect.DeepEqual(out, tt.out) || (tt.out == nil) != (err != nil) { + t.Errorf("IP.UnmarshalText(%q) = %v, %v, want %v", tt.in, out, err, tt.out) + } + } +} + +func TestLookupWithIP(t *testing.T) { + _, err := LookupIP("") + if err == nil { + t.Errorf(`LookupIP("") succeeded, should fail`) + } + _, err = LookupHost("") + if err == nil { + t.Errorf(`LookupIP("") succeeded, should fail`) + } + + // Test that LookupHost and LookupIP, which normally + // expect host names, work with IP addresses. + for _, tt := range parseIPTests { + if tt.out != nil { + addrs, err := LookupHost(tt.in) + if len(addrs) != 1 || addrs[0] != tt.in || err != nil { + t.Errorf("LookupHost(%q) = %v, %v, want %v, nil", tt.in, addrs, err, []string{tt.in}) + } + } else if !testing.Short() { + // We can't control what the host resolver does; if it can resolve, say, + // 127.0.0.256 or fe80::1%911 or a host named 'abc', who are we to judge? + // Warn about these discrepancies but don't fail the test. + addrs, err := LookupHost(tt.in) + if err == nil { + t.Logf("warning: LookupHost(%q) = %v, want error", tt.in, addrs) + } + } + + if tt.out != nil { + ips, err := LookupIP(tt.in) + if len(ips) != 1 || !reflect.DeepEqual(ips[0], tt.out) || err != nil { + t.Errorf("LookupIP(%q) = %v, %v, want %v, nil", tt.in, ips, err, []IP{tt.out}) + } + } else if !testing.Short() { + ips, err := LookupIP(tt.in) + // We can't control what the host resolver does. See above. + if err == nil { + t.Logf("warning: LookupIP(%q) = %v, want error", tt.in, ips) + } + } + } +} + +func BenchmarkParseIP(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + + for i := 0; i < b.N; i++ { + for _, tt := range parseIPTests { + ParseIP(tt.in) + } + } +} + +func BenchmarkParseIPValidIPv4(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + + for i := 0; i < b.N; i++ { + ParseIP("192.0.2.1") + } +} + +func BenchmarkParseIPValidIPv6(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + + for i := 0; i < b.N; i++ { + ParseIP("2001:DB8::1") + } +} + +// Issue 6339 +func TestMarshalEmptyIP(t *testing.T) { + for _, in := range [][]byte{nil, []byte("")} { + var out = IP{1, 2, 3, 4} + if err := out.UnmarshalText(in); err != nil || out != nil { + t.Errorf("UnmarshalText(%v) = %v, %v; want nil, nil", in, out, err) + } + } + var ip IP + got, err := ip.MarshalText() + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, []byte("")) { + t.Errorf(`got %#v, want []byte("")`, got) + } + + buf := make([]byte, 4) + got, err = ip.AppendText(buf) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, []byte("\x00\x00\x00\x00")) { + t.Errorf(`got %#v, want []byte("\x00\x00\x00\x00")`, got) + } +} + +var ipStringTests = []*struct { + in IP // see RFC 791 and RFC 4291 + str string // see RFC 791, RFC 4291 and RFC 5952 + byt []byte + error +}{ + // IPv4 address + { + IP{192, 0, 2, 1}, + "192.0.2.1", + []byte("192.0.2.1"), + nil, + }, + { + IP{0, 0, 0, 0}, + "0.0.0.0", + []byte("0.0.0.0"), + nil, + }, + + // IPv4-mapped IPv6 address + { + IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 1}, + "192.0.2.1", + []byte("192.0.2.1"), + nil, + }, + { + IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0}, + "0.0.0.0", + []byte("0.0.0.0"), + nil, + }, + + // IPv6 address + { + IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0x1, 0x23, 0, 0x12, 0, 0x1}, + "2001:db8::123:12:1", + []byte("2001:db8::123:12:1"), + nil, + }, + { + IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1}, + "2001:db8::1", + []byte("2001:db8::1"), + nil, + }, + { + IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0x1, 0, 0, 0, 0x1, 0, 0, 0, 0x1}, + "2001:db8:0:1:0:1:0:1", + []byte("2001:db8:0:1:0:1:0:1"), + nil, + }, + { + IP{0x20, 0x1, 0xd, 0xb8, 0, 0x1, 0, 0, 0, 0x1, 0, 0, 0, 0x1, 0, 0}, + "2001:db8:1:0:1:0:1:0", + []byte("2001:db8:1:0:1:0:1:0"), + nil, + }, + { + IP{0x20, 0x1, 0, 0, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0x1}, + "2001::1:0:0:1", + []byte("2001::1:0:0:1"), + nil, + }, + { + IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0}, + "2001:db8:0:0:1::", + []byte("2001:db8:0:0:1::"), + nil, + }, + { + IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0x1}, + "2001:db8::1:0:0:1", + []byte("2001:db8::1:0:0:1"), + nil, + }, + { + IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0xa, 0, 0xb, 0, 0xc, 0, 0xd}, + "2001:db8::a:b:c:d", + []byte("2001:db8::a:b:c:d"), + nil, + }, + { + IPv6unspecified, + "::", + []byte("::"), + nil, + }, + + // IP wildcard equivalent address in Dial/Listen API + { + nil, + "", + nil, + nil, + }, + + // Opaque byte sequence + { + IP{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, + "?0123456789abcdef", + nil, + &AddrError{Err: "invalid IP address", Addr: "0123456789abcdef"}, + }, +} + +func TestIPString(t *testing.T) { + for _, tt := range ipStringTests { + if out := tt.in.String(); out != tt.str { + t.Errorf("IP.String(%v) = %q, want %q", tt.in, out, tt.str) + } + if out, err := tt.in.MarshalText(); !bytes.Equal(out, tt.byt) || !reflect.DeepEqual(err, tt.error) { + t.Errorf("IP.MarshalText(%v) = %v, %v, want %v, %v", tt.in, out, err, tt.byt, tt.error) + } + buf := make([]byte, 4, 32) + if out, err := tt.in.AppendText(buf); !bytes.Equal(out[4:], tt.byt) || !reflect.DeepEqual(err, tt.error) { + t.Errorf("IP.AppendText(%v) = %v, %v, want %v, %v", tt.in, out[4:], err, tt.byt, tt.error) + } + } +} + +func TestIPAppendTextNoAllocs(t *testing.T) { + // except the invalid IP + for _, tt := range ipStringTests[:len(ipStringTests)-1] { + allocs := int(testing.AllocsPerRun(1000, func() { + buf := make([]byte, 0, 64) + _, _ = tt.in.AppendText(buf) + })) + if allocs != 0 { + t.Errorf("IP(%q) AppendText allocs: %d times, want 0", tt.in, allocs) + } + } +} + +func BenchmarkIPMarshalText(b *testing.B) { + b.Run("IPv4", func(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() + ip := IP{192, 0, 2, 1} + for range b.N { + _, _ = ip.MarshalText() + } + }) + b.Run("IPv6", func(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() + ip := IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0xa, 0, 0xb, 0, 0xc, 0, 0xd} + for range b.N { + _, _ = ip.MarshalText() + } + }) + b.Run("IPv6_long", func(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() + // fd7a:115c:a1e0:ab12:4843:cd96:626b:430b + ip := IP{253, 122, 17, 92, 161, 224, 171, 18, 72, 67, 205, 150, 98, 107, 67, 11} + for range b.N { + _, _ = ip.MarshalText() + } + }) +} + +var sink string + +func BenchmarkIPString(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + + b.Run("IPv4", func(b *testing.B) { + benchmarkIPString(b, IPv4len) + }) + + b.Run("IPv6", func(b *testing.B) { + benchmarkIPString(b, IPv6len) + }) +} + +func benchmarkIPString(b *testing.B, size int) { + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + for _, tt := range ipStringTests { + if tt.in != nil && len(tt.in) == size { + sink = tt.in.String() + } + } + } +} + +var ipMaskTests = []struct { + in IP + mask IPMask + out IP +}{ + {IPv4(192, 168, 1, 127), IPv4Mask(255, 255, 255, 128), IPv4(192, 168, 1, 0)}, + {IPv4(192, 168, 1, 127), IPMask(ParseIP("255.255.255.192")), IPv4(192, 168, 1, 64)}, + {IPv4(192, 168, 1, 127), IPMask(ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0")), IPv4(192, 168, 1, 96)}, + {IPv4(192, 168, 1, 127), IPv4Mask(255, 0, 255, 0), IPv4(192, 0, 1, 0)}, + {ParseIP("2001:db8::1"), IPMask(ParseIP("ffff:ff80::")), ParseIP("2001:d80::")}, + {ParseIP("2001:db8::1"), IPMask(ParseIP("f0f0:0f0f::")), ParseIP("2000:d08::")}, +} + +func TestIPMask(t *testing.T) { + for _, tt := range ipMaskTests { + if out := tt.in.Mask(tt.mask); out == nil || !tt.out.Equal(out) { + t.Errorf("IP(%v).Mask(%v) = %v, want %v", tt.in, tt.mask, out, tt.out) + } + } +} + +var ipMaskStringTests = []struct { + in IPMask + out string +}{ + {IPv4Mask(255, 255, 255, 240), "fffffff0"}, + {IPv4Mask(255, 0, 128, 0), "ff008000"}, + {IPMask(ParseIP("ffff:ff80::")), "ffffff80000000000000000000000000"}, + {IPMask(ParseIP("ef00:ff80::cafe:0")), "ef00ff800000000000000000cafe0000"}, + {nil, ""}, +} + +func TestIPMaskString(t *testing.T) { + for _, tt := range ipMaskStringTests { + if out := tt.in.String(); out != tt.out { + t.Errorf("IPMask.String(%v) = %q, want %q", tt.in, out, tt.out) + } + } +} + +func BenchmarkIPMaskString(b *testing.B) { + testHookUninstaller.Do(uninstallTestHooks) + + for i := 0; i < b.N; i++ { + for _, tt := range ipMaskStringTests { + sink = tt.in.String() + } + } +} + +var parseCIDRTests = []struct { + in string + ip IP + net *IPNet + err error +}{ + {"135.104.0.0/32", IPv4(135, 104, 0, 0), &IPNet{IP: IPv4(135, 104, 0, 0), Mask: IPv4Mask(255, 255, 255, 255)}, nil}, + {"0.0.0.0/24", IPv4(0, 0, 0, 0), &IPNet{IP: IPv4(0, 0, 0, 0), Mask: IPv4Mask(255, 255, 255, 0)}, nil}, + {"135.104.0.0/24", IPv4(135, 104, 0, 0), &IPNet{IP: IPv4(135, 104, 0, 0), Mask: IPv4Mask(255, 255, 255, 0)}, nil}, + {"135.104.0.1/32", IPv4(135, 104, 0, 1), &IPNet{IP: IPv4(135, 104, 0, 1), Mask: IPv4Mask(255, 255, 255, 255)}, nil}, + {"135.104.0.1/24", IPv4(135, 104, 0, 1), &IPNet{IP: IPv4(135, 104, 0, 0), Mask: IPv4Mask(255, 255, 255, 0)}, nil}, + {"::1/128", ParseIP("::1"), &IPNet{IP: ParseIP("::1"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"))}, nil}, + {"abcd:2345::/127", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"))}, nil}, + {"abcd:2345::/65", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff:8000::"))}, nil}, + {"abcd:2345::/64", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff::"))}, nil}, + {"abcd:2345::/63", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:fffe::"))}, nil}, + {"abcd:2345::/33", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:8000::"))}, nil}, + {"abcd:2345::/32", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff::"))}, nil}, + {"abcd:2344::/31", ParseIP("abcd:2344::"), &IPNet{IP: ParseIP("abcd:2344::"), Mask: IPMask(ParseIP("ffff:fffe::"))}, nil}, + {"abcd:2300::/24", ParseIP("abcd:2300::"), &IPNet{IP: ParseIP("abcd:2300::"), Mask: IPMask(ParseIP("ffff:ff00::"))}, nil}, + {"abcd:2345::/24", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2300::"), Mask: IPMask(ParseIP("ffff:ff00::"))}, nil}, + {"2001:DB8::/48", ParseIP("2001:DB8::"), &IPNet{IP: ParseIP("2001:DB8::"), Mask: IPMask(ParseIP("ffff:ffff:ffff::"))}, nil}, + {"2001:DB8::1/48", ParseIP("2001:DB8::1"), &IPNet{IP: ParseIP("2001:DB8::"), Mask: IPMask(ParseIP("ffff:ffff:ffff::"))}, nil}, + {"192.168.1.1/255.255.255.0", nil, nil, &ParseError{Type: "CIDR address", Text: "192.168.1.1/255.255.255.0"}}, + {"192.168.1.1/35", nil, nil, &ParseError{Type: "CIDR address", Text: "192.168.1.1/35"}}, + {"2001:db8::1/-1", nil, nil, &ParseError{Type: "CIDR address", Text: "2001:db8::1/-1"}}, + {"2001:db8::1/-0", nil, nil, &ParseError{Type: "CIDR address", Text: "2001:db8::1/-0"}}, + {"-0.0.0.0/32", nil, nil, &ParseError{Type: "CIDR address", Text: "-0.0.0.0/32"}}, + {"0.-1.0.0/32", nil, nil, &ParseError{Type: "CIDR address", Text: "0.-1.0.0/32"}}, + {"0.0.-2.0/32", nil, nil, &ParseError{Type: "CIDR address", Text: "0.0.-2.0/32"}}, + {"0.0.0.-3/32", nil, nil, &ParseError{Type: "CIDR address", Text: "0.0.0.-3/32"}}, + {"0.0.0.0/-0", nil, nil, &ParseError{Type: "CIDR address", Text: "0.0.0.0/-0"}}, + {"127.000.000.001/32", nil, nil, &ParseError{Type: "CIDR address", Text: "127.000.000.001/32"}}, + {"", nil, nil, &ParseError{Type: "CIDR address", Text: ""}}, +} + +func TestParseCIDR(t *testing.T) { + for _, tt := range parseCIDRTests { + ip, net, err := ParseCIDR(tt.in) + if !reflect.DeepEqual(err, tt.err) { + t.Errorf("ParseCIDR(%q) = %v, %v; want %v, %v", tt.in, ip, net, tt.ip, tt.net) + } + if err == nil && (!tt.ip.Equal(ip) || !tt.net.IP.Equal(net.IP) || !reflect.DeepEqual(net.Mask, tt.net.Mask)) { + t.Errorf("ParseCIDR(%q) = %v, {%v, %v}; want %v, {%v, %v}", tt.in, ip, net.IP, net.Mask, tt.ip, tt.net.IP, tt.net.Mask) + } + } +} + +var ipNetContainsTests = []struct { + ip IP + net *IPNet + ok bool +}{ + {IPv4(172, 16, 1, 1), &IPNet{IP: IPv4(172, 16, 0, 0), Mask: CIDRMask(12, 32)}, true}, + {IPv4(172, 24, 0, 1), &IPNet{IP: IPv4(172, 16, 0, 0), Mask: CIDRMask(13, 32)}, false}, + {IPv4(192, 168, 0, 3), &IPNet{IP: IPv4(192, 168, 0, 0), Mask: IPv4Mask(0, 0, 255, 252)}, true}, + {IPv4(192, 168, 0, 4), &IPNet{IP: IPv4(192, 168, 0, 0), Mask: IPv4Mask(0, 255, 0, 252)}, false}, + {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:1::"), Mask: CIDRMask(47, 128)}, true}, + {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:2::"), Mask: CIDRMask(47, 128)}, false}, + {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:1::"), Mask: IPMask(ParseIP("ffff:0:ffff::"))}, true}, + {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:1::"), Mask: IPMask(ParseIP("0:0:0:ffff::"))}, false}, +} + +func TestIPNetContains(t *testing.T) { + for _, tt := range ipNetContainsTests { + if ok := tt.net.Contains(tt.ip); ok != tt.ok { + t.Errorf("IPNet(%v).Contains(%v) = %v, want %v", tt.net, tt.ip, ok, tt.ok) + } + } +} + +var ipNetStringTests = []struct { + in *IPNet + out string +}{ + {&IPNet{IP: IPv4(192, 168, 1, 0), Mask: CIDRMask(26, 32)}, "192.168.1.0/26"}, + {&IPNet{IP: IPv4(192, 168, 1, 0), Mask: IPv4Mask(255, 0, 255, 0)}, "192.168.1.0/ff00ff00"}, + {&IPNet{IP: ParseIP("2001:db8::"), Mask: CIDRMask(55, 128)}, "2001:db8::/55"}, + {&IPNet{IP: ParseIP("2001:db8::"), Mask: IPMask(ParseIP("8000:f123:0:cafe::"))}, "2001:db8::/8000f1230000cafe0000000000000000"}, + {nil, ""}, +} + +func TestIPNetString(t *testing.T) { + for _, tt := range ipNetStringTests { + if out := tt.in.String(); out != tt.out { + t.Errorf("IPNet.String(%v) = %q, want %q", tt.in, out, tt.out) + } + } +} + +var cidrMaskTests = []struct { + ones int + bits int + out IPMask +}{ + {0, 32, IPv4Mask(0, 0, 0, 0)}, + {12, 32, IPv4Mask(255, 240, 0, 0)}, + {24, 32, IPv4Mask(255, 255, 255, 0)}, + {32, 32, IPv4Mask(255, 255, 255, 255)}, + {0, 128, IPMask{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + {4, 128, IPMask{0xf0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + {48, 128, IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + {128, 128, IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, + {33, 32, nil}, + {32, 33, nil}, + {-1, 128, nil}, + {128, -1, nil}, +} + +func TestCIDRMask(t *testing.T) { + for _, tt := range cidrMaskTests { + if out := CIDRMask(tt.ones, tt.bits); !reflect.DeepEqual(out, tt.out) { + t.Errorf("CIDRMask(%v, %v) = %v, want %v", tt.ones, tt.bits, out, tt.out) + } + } +} + +var ( + v4addr = IP{192, 168, 0, 1} + v4mappedv6addr = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 168, 0, 1} + v6addr = IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0x1, 0x23, 0, 0x12, 0, 0x1} + v4mask = IPMask{255, 255, 255, 0} + v4mappedv6mask = IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 255, 255, 255, 0} + v6mask = IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0} + badaddr = IP{192, 168, 0} + badmask = IPMask{255, 255, 0} + v4maskzero = IPMask{0, 0, 0, 0} +) + +var networkNumberAndMaskTests = []struct { + in IPNet + out IPNet +}{ + {IPNet{IP: v4addr, Mask: v4mask}, IPNet{IP: v4addr, Mask: v4mask}}, + {IPNet{IP: v4addr, Mask: v4mappedv6mask}, IPNet{IP: v4addr, Mask: v4mask}}, + {IPNet{IP: v4mappedv6addr, Mask: v4mappedv6mask}, IPNet{IP: v4addr, Mask: v4mask}}, + {IPNet{IP: v4mappedv6addr, Mask: v6mask}, IPNet{IP: v4addr, Mask: v4maskzero}}, + {IPNet{IP: v4addr, Mask: v6mask}, IPNet{IP: v4addr, Mask: v4maskzero}}, + {IPNet{IP: v6addr, Mask: v6mask}, IPNet{IP: v6addr, Mask: v6mask}}, + {IPNet{IP: v6addr, Mask: v4mappedv6mask}, IPNet{IP: v6addr, Mask: v4mappedv6mask}}, + {in: IPNet{IP: v6addr, Mask: v4mask}}, + {in: IPNet{IP: v4addr, Mask: badmask}}, + {in: IPNet{IP: v4mappedv6addr, Mask: badmask}}, + {in: IPNet{IP: v6addr, Mask: badmask}}, + {in: IPNet{IP: badaddr, Mask: v4mask}}, + {in: IPNet{IP: badaddr, Mask: v4mappedv6mask}}, + {in: IPNet{IP: badaddr, Mask: v6mask}}, + {in: IPNet{IP: badaddr, Mask: badmask}}, +} + +func TestNetworkNumberAndMask(t *testing.T) { + for _, tt := range networkNumberAndMaskTests { + ip, m := networkNumberAndMask(&tt.in) + out := &IPNet{IP: ip, Mask: m} + if !reflect.DeepEqual(&tt.out, out) { + t.Errorf("networkNumberAndMask(%v) = %v, want %v", tt.in, out, &tt.out) + } + } +} + +func TestSplitHostPort(t *testing.T) { + for _, tt := range []struct { + hostPort string + host string + port string + }{ + // Host name + {"localhost:http", "localhost", "http"}, + {"localhost:80", "localhost", "80"}, + + // Go-specific host name with zone identifier + {"localhost%lo0:http", "localhost%lo0", "http"}, + {"localhost%lo0:80", "localhost%lo0", "80"}, + {"[localhost%lo0]:http", "localhost%lo0", "http"}, // Go 1 behavior + {"[localhost%lo0]:80", "localhost%lo0", "80"}, // Go 1 behavior + + // IP literal + {"127.0.0.1:http", "127.0.0.1", "http"}, + {"127.0.0.1:80", "127.0.0.1", "80"}, + {"[::1]:http", "::1", "http"}, + {"[::1]:80", "::1", "80"}, + + // IP literal with zone identifier + {"[::1%lo0]:http", "::1%lo0", "http"}, + {"[::1%lo0]:80", "::1%lo0", "80"}, + + // Go-specific wildcard for host name + {":http", "", "http"}, // Go 1 behavior + {":80", "", "80"}, // Go 1 behavior + + // Go-specific wildcard for service name or transport port number + {"golang.org:", "golang.org", ""}, // Go 1 behavior + {"127.0.0.1:", "127.0.0.1", ""}, // Go 1 behavior + {"[::1]:", "::1", ""}, // Go 1 behavior + + // Opaque service name + {"golang.org:https%foo", "golang.org", "https%foo"}, // Go 1 behavior + } { + if host, port, err := SplitHostPort(tt.hostPort); host != tt.host || port != tt.port || err != nil { + t.Errorf("SplitHostPort(%q) = %q, %q, %v; want %q, %q, nil", tt.hostPort, host, port, err, tt.host, tt.port) + } + } + + for _, tt := range []struct { + hostPort string + err string + }{ + {"golang.org", "missing port in address"}, + {"127.0.0.1", "missing port in address"}, + {"[::1]", "missing port in address"}, + {"[fe80::1%lo0]", "missing port in address"}, + {"[localhost%lo0]", "missing port in address"}, + {"localhost%lo0", "missing port in address"}, + + {"::1", "too many colons in address"}, + {"fe80::1%lo0", "too many colons in address"}, + {"fe80::1%lo0:80", "too many colons in address"}, + + // Test cases that didn't fail in Go 1 + + {"[foo:bar]", "missing port in address"}, + {"[foo:bar]baz", "missing port in address"}, + {"[foo]bar:baz", "missing port in address"}, + + {"[foo]:[bar]:baz", "too many colons in address"}, + + {"[foo]:[bar]baz", "unexpected '[' in address"}, + {"foo[bar]:baz", "unexpected '[' in address"}, + + {"foo]bar:baz", "unexpected ']' in address"}, + } { + if host, port, err := SplitHostPort(tt.hostPort); err == nil { + t.Errorf("SplitHostPort(%q) should have failed", tt.hostPort) + } else { + e := err.(*AddrError) + if e.Err != tt.err { + t.Errorf("SplitHostPort(%q) = _, _, %q; want %q", tt.hostPort, e.Err, tt.err) + } + if host != "" || port != "" { + t.Errorf("SplitHostPort(%q) = %q, %q, err; want %q, %q, err on failure", tt.hostPort, host, port, "", "") + } + } + } +} + +func TestJoinHostPort(t *testing.T) { + for _, tt := range []struct { + host string + port string + hostPort string + }{ + // Host name + {"localhost", "http", "localhost:http"}, + {"localhost", "80", "localhost:80"}, + + // Go-specific host name with zone identifier + {"localhost%lo0", "http", "localhost%lo0:http"}, + {"localhost%lo0", "80", "localhost%lo0:80"}, + + // IP literal + {"127.0.0.1", "http", "127.0.0.1:http"}, + {"127.0.0.1", "80", "127.0.0.1:80"}, + {"::1", "http", "[::1]:http"}, + {"::1", "80", "[::1]:80"}, + + // IP literal with zone identifier + {"::1%lo0", "http", "[::1%lo0]:http"}, + {"::1%lo0", "80", "[::1%lo0]:80"}, + + // Go-specific wildcard for host name + {"", "http", ":http"}, // Go 1 behavior + {"", "80", ":80"}, // Go 1 behavior + + // Go-specific wildcard for service name or transport port number + {"golang.org", "", "golang.org:"}, // Go 1 behavior + {"127.0.0.1", "", "127.0.0.1:"}, // Go 1 behavior + {"::1", "", "[::1]:"}, // Go 1 behavior + + // Opaque service name + {"golang.org", "https%foo", "golang.org:https%foo"}, // Go 1 behavior + } { + if hostPort := JoinHostPort(tt.host, tt.port); hostPort != tt.hostPort { + t.Errorf("JoinHostPort(%q, %q) = %q; want %q", tt.host, tt.port, hostPort, tt.hostPort) + } + } +} + +var ipAddrFamilyTests = []struct { + in IP + af4 bool + af6 bool +}{ + {IPv4bcast, true, false}, + {IPv4allsys, true, false}, + {IPv4allrouter, true, false}, + {IPv4zero, true, false}, + {IPv4(224, 0, 0, 1), true, false}, + {IPv4(127, 0, 0, 1), true, false}, + {IPv4(240, 0, 0, 1), true, false}, + {IPv6unspecified, false, true}, + {IPv6loopback, false, true}, + {IPv6interfacelocalallnodes, false, true}, + {IPv6linklocalallnodes, false, true}, + {IPv6linklocalallrouters, false, true}, + {ParseIP("ff05::a:b:c:d"), false, true}, + {ParseIP("fe80::1:2:3:4"), false, true}, + {ParseIP("2001:db8::123:12:1"), false, true}, +} + +func TestIPAddrFamily(t *testing.T) { + for _, tt := range ipAddrFamilyTests { + if af := tt.in.To4() != nil; af != tt.af4 { + t.Errorf("verifying IPv4 address family for %q = %v, want %v", tt.in, af, tt.af4) + } + if af := len(tt.in) == IPv6len && tt.in.To4() == nil; af != tt.af6 { + t.Errorf("verifying IPv6 address family for %q = %v, want %v", tt.in, af, tt.af6) + } + } +} + +var ipAddrScopeTests = []struct { + scope func(IP) bool + in IP + ok bool +}{ + {IP.IsUnspecified, IPv4zero, true}, + {IP.IsUnspecified, IPv4(127, 0, 0, 1), false}, + {IP.IsUnspecified, IPv6unspecified, true}, + {IP.IsUnspecified, IPv6interfacelocalallnodes, false}, + {IP.IsUnspecified, nil, false}, + {IP.IsLoopback, IPv4(127, 0, 0, 1), true}, + {IP.IsLoopback, IPv4(127, 255, 255, 254), true}, + {IP.IsLoopback, IPv4(128, 1, 2, 3), false}, + {IP.IsLoopback, IPv6loopback, true}, + {IP.IsLoopback, IPv6linklocalallrouters, false}, + {IP.IsLoopback, nil, false}, + {IP.IsMulticast, IPv4(224, 0, 0, 0), true}, + {IP.IsMulticast, IPv4(239, 0, 0, 0), true}, + {IP.IsMulticast, IPv4(240, 0, 0, 0), false}, + {IP.IsMulticast, IPv6linklocalallnodes, true}, + {IP.IsMulticast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true}, + {IP.IsMulticast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false}, + {IP.IsMulticast, nil, false}, + {IP.IsInterfaceLocalMulticast, IPv4(224, 0, 0, 0), false}, + {IP.IsInterfaceLocalMulticast, IPv4(0xff, 0x01, 0, 0), false}, + {IP.IsInterfaceLocalMulticast, IPv6interfacelocalallnodes, true}, + {IP.IsInterfaceLocalMulticast, nil, false}, + {IP.IsLinkLocalMulticast, IPv4(224, 0, 0, 0), true}, + {IP.IsLinkLocalMulticast, IPv4(239, 0, 0, 0), false}, + {IP.IsLinkLocalMulticast, IPv4(0xff, 0x02, 0, 0), false}, + {IP.IsLinkLocalMulticast, IPv6linklocalallrouters, true}, + {IP.IsLinkLocalMulticast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false}, + {IP.IsLinkLocalMulticast, nil, false}, + {IP.IsLinkLocalUnicast, IPv4(169, 254, 0, 0), true}, + {IP.IsLinkLocalUnicast, IPv4(169, 255, 0, 0), false}, + {IP.IsLinkLocalUnicast, IPv4(0xfe, 0x80, 0, 0), false}, + {IP.IsLinkLocalUnicast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true}, + {IP.IsLinkLocalUnicast, IP{0xfe, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false}, + {IP.IsLinkLocalUnicast, nil, false}, + {IP.IsGlobalUnicast, IPv4(240, 0, 0, 0), true}, + {IP.IsGlobalUnicast, IPv4(232, 0, 0, 0), false}, + {IP.IsGlobalUnicast, IPv4(169, 254, 0, 0), false}, + {IP.IsGlobalUnicast, IPv4bcast, false}, + {IP.IsGlobalUnicast, IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0x1, 0x23, 0, 0x12, 0, 0x1}, true}, + {IP.IsGlobalUnicast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false}, + {IP.IsGlobalUnicast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false}, + {IP.IsGlobalUnicast, nil, false}, + {IP.IsPrivate, nil, false}, + {IP.IsPrivate, IPv4(1, 1, 1, 1), false}, + {IP.IsPrivate, IPv4(9, 255, 255, 255), false}, + {IP.IsPrivate, IPv4(10, 0, 0, 0), true}, + {IP.IsPrivate, IPv4(10, 255, 255, 255), true}, + {IP.IsPrivate, IPv4(11, 0, 0, 0), false}, + {IP.IsPrivate, IPv4(172, 15, 255, 255), false}, + {IP.IsPrivate, IPv4(172, 16, 0, 0), true}, + {IP.IsPrivate, IPv4(172, 16, 255, 255), true}, + {IP.IsPrivate, IPv4(172, 23, 18, 255), true}, + {IP.IsPrivate, IPv4(172, 31, 255, 255), true}, + {IP.IsPrivate, IPv4(172, 31, 0, 0), true}, + {IP.IsPrivate, IPv4(172, 32, 0, 0), false}, + {IP.IsPrivate, IPv4(192, 167, 255, 255), false}, + {IP.IsPrivate, IPv4(192, 168, 0, 0), true}, + {IP.IsPrivate, IPv4(192, 168, 255, 255), true}, + {IP.IsPrivate, IPv4(192, 169, 0, 0), false}, + {IP.IsPrivate, IP{0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, false}, + {IP.IsPrivate, IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true}, + {IP.IsPrivate, IP{0xfc, 0xff, 0x12, 0, 0, 0, 0, 0x44, 0, 0, 0, 0, 0, 0, 0, 0}, true}, + {IP.IsPrivate, IP{0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, true}, + {IP.IsPrivate, IP{0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false}, +} + +func name(f any) string { + return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() +} + +func TestIPAddrScope(t *testing.T) { + for _, tt := range ipAddrScopeTests { + if ok := tt.scope(tt.in); ok != tt.ok { + t.Errorf("%s(%q) = %v, want %v", name(tt.scope), tt.in, ok, tt.ok) + } + ip := tt.in.To4() + if ip == nil { + continue + } + if ok := tt.scope(ip); ok != tt.ok { + t.Errorf("%s(%q) = %v, want %v", name(tt.scope), ip, ok, tt.ok) + } + } +} + +func BenchmarkIPEqual(b *testing.B) { + b.Run("IPv4", func(b *testing.B) { + benchmarkIPEqual(b, IPv4len) + }) + b.Run("IPv6", func(b *testing.B) { + benchmarkIPEqual(b, IPv6len) + }) +} + +func benchmarkIPEqual(b *testing.B, size int) { + ips := make([]IP, 1000) + for i := range ips { + ips[i] = make(IP, size) + rand.Read(ips[i]) + } + // Half of the N are equal. + for i := 0; i < b.N/2; i++ { + x := ips[i%len(ips)] + y := ips[i%len(ips)] + x.Equal(y) + } + // The other half are not equal. + for i := 0; i < b.N/2; i++ { + x := ips[i%len(ips)] + y := ips[(i+1)%len(ips)] + x.Equal(y) + } +} diff --git a/go/src/net/iprawsock.go b/go/src/net/iprawsock.go new file mode 100644 index 0000000000000000000000000000000000000000..26134d7e76a2ecbaed85aa692d7d1de458ad193f --- /dev/null +++ b/go/src/net/iprawsock.go @@ -0,0 +1,258 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "net/netip" + "syscall" +) + +// BUG(mikio): On every POSIX platform, reads from the "ip4" network +// using the ReadFrom or ReadFromIP method might not return a complete +// IPv4 packet, including its header, even if there is space +// available. This can occur even in cases where Read or ReadMsgIP +// could return a complete packet. For this reason, it is recommended +// that you do not use these methods if it is important to receive a +// full packet. +// +// The Go 1 compatibility guidelines make it impossible for us to +// change the behavior of these methods; use Read or ReadMsgIP +// instead. + +// BUG(mikio): On JS and Plan 9, methods and functions related +// to IPConn are not implemented. + +// BUG: On Windows, raw IP sockets are restricted by the operating system. +// Sending TCP data, sending UDP data with invalid source addresses, +// and calling bind with TCP protocol don't work. +// +// See Winsock reference for details. + +func ipAddrFromAddr(addr netip.Addr) *IPAddr { + return &IPAddr{ + IP: addr.AsSlice(), + Zone: addr.Zone(), + } +} + +// IPAddr represents the address of an IP end point. +type IPAddr struct { + IP IP + Zone string // IPv6 scoped addressing zone +} + +// Network returns the address's network name, "ip". +func (a *IPAddr) Network() string { return "ip" } + +func (a *IPAddr) String() string { + if a == nil { + return "" + } + ip := ipEmptyString(a.IP) + if a.Zone != "" { + return ip + "%" + a.Zone + } + return ip +} + +func (a *IPAddr) isWildcard() bool { + if a == nil || a.IP == nil { + return true + } + return a.IP.IsUnspecified() +} + +func (a *IPAddr) opAddr() Addr { + if a == nil { + return nil + } + return a +} + +// ResolveIPAddr returns an address of IP end point. +// +// The network must be an IP network name. +// +// If the host in the address parameter is not a literal IP address, +// ResolveIPAddr resolves the address to an address of IP end point. +// Otherwise, it parses the address as a literal IP address. +// The address parameter can use a host name, but this is not +// recommended, because it will return at most one of the host name's +// IP addresses. +// +// See func [Dial] for a description of the network and address +// parameters. +func ResolveIPAddr(network, address string) (*IPAddr, error) { + if network == "" { // a hint wildcard for Go 1.0 undocumented behavior + network = "ip" + } + afnet, _, err := parseNetwork(context.Background(), network, false) + if err != nil { + return nil, err + } + switch afnet { + case "ip", "ip4", "ip6": + default: + return nil, UnknownNetworkError(network) + } + addrs, err := DefaultResolver.internetAddrList(context.Background(), afnet, address) + if err != nil { + return nil, err + } + return addrs.forResolve(network, address).(*IPAddr), nil +} + +// IPConn is the implementation of the [Conn] and [PacketConn] interfaces +// for IP network connections. +type IPConn struct { + conn +} + +// SyscallConn returns a raw network connection. +// This implements the [syscall.Conn] interface. +func (c *IPConn) SyscallConn() (syscall.RawConn, error) { + if !c.ok() { + return nil, syscall.EINVAL + } + return newRawConn(c.fd), nil +} + +// ReadFromIP acts like ReadFrom but returns an IPAddr. +func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error) { + if !c.ok() { + return 0, nil, syscall.EINVAL + } + n, addr, err := c.readFrom(b) + if err != nil { + err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return n, addr, err +} + +// ReadFrom implements the [PacketConn] ReadFrom method. +func (c *IPConn) ReadFrom(b []byte) (int, Addr, error) { + if !c.ok() { + return 0, nil, syscall.EINVAL + } + n, addr, err := c.readFrom(b) + if err != nil { + err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + if addr == nil { + return n, nil, err + } + return n, addr, err +} + +// ReadMsgIP reads a message from c, copying the payload into b and +// the associated out-of-band data into oob. It returns the number of +// bytes copied into b, the number of bytes copied into oob, the flags +// that were set on the message and the source address of the message. +// +// The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be +// used to manipulate IP-level socket options in oob. +func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error) { + if !c.ok() { + return 0, 0, 0, nil, syscall.EINVAL + } + n, oobn, flags, addr, err = c.readMsg(b, oob) + if err != nil { + err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return +} + +// WriteToIP acts like [IPConn.WriteTo] but takes an [IPAddr]. +func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error) { + if !c.ok() { + return 0, syscall.EINVAL + } + n, err := c.writeTo(b, addr) + if err != nil { + err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr.opAddr(), Err: err} + } + return n, err +} + +// WriteTo implements the [PacketConn] WriteTo method. +func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error) { + if !c.ok() { + return 0, syscall.EINVAL + } + a, ok := addr.(*IPAddr) + if !ok { + return 0, &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr, Err: syscall.EINVAL} + } + n, err := c.writeTo(b, a) + if err != nil { + err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: a.opAddr(), Err: err} + } + return n, err +} + +// WriteMsgIP writes a message to addr via c, copying the payload from +// b and the associated out-of-band data from oob. It returns the +// number of payload and out-of-band bytes written. +// +// The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be +// used to manipulate IP-level socket options in oob. +func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error) { + if !c.ok() { + return 0, 0, syscall.EINVAL + } + n, oobn, err = c.writeMsg(b, oob, addr) + if err != nil { + err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr.opAddr(), Err: err} + } + return +} + +func newIPConn(fd *netFD) *IPConn { return &IPConn{conn{fd}} } + +// DialIP acts like [Dial] for IP networks. +// +// The network must be an IP network name; see func Dial for details. +// +// If laddr is nil, a local address is automatically chosen. +// If the IP field of raddr is nil or an unspecified IP address, the +// local system is assumed. +func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error) { + return dialIP(context.Background(), nil, network, laddr, raddr) +} + +func dialIP(ctx context.Context, dialer *Dialer, network string, laddr, raddr *IPAddr) (*IPConn, error) { + if raddr == nil { + return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: nil, Err: errMissingAddress} + } + sd := &sysDialer{network: network, address: raddr.String()} + if dialer != nil { + sd.Dialer = *dialer + } + c, err := sd.dialIP(ctx, laddr, raddr) + if err != nil { + return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: err} + } + return c, nil +} + +// ListenIP acts like [ListenPacket] for IP networks. +// +// The network must be an IP network name; see func Dial for details. +// +// If the IP field of laddr is nil or an unspecified IP address, +// ListenIP listens on all available IP addresses of the local system +// except multicast IP addresses. +func ListenIP(network string, laddr *IPAddr) (*IPConn, error) { + if laddr == nil { + laddr = &IPAddr{} + } + sl := &sysListener{network: network, address: laddr.String()} + c, err := sl.listenIP(context.Background(), laddr) + if err != nil { + return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: err} + } + return c, nil +} diff --git a/go/src/net/iprawsock_plan9.go b/go/src/net/iprawsock_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..ebe58088642de4b2f0bfaccb0f478af95cda44bd --- /dev/null +++ b/go/src/net/iprawsock_plan9.go @@ -0,0 +1,34 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "syscall" +) + +func (c *IPConn) readFrom(b []byte) (int, *IPAddr, error) { + return 0, nil, syscall.EPLAN9 +} + +func (c *IPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error) { + return 0, 0, 0, nil, syscall.EPLAN9 +} + +func (c *IPConn) writeTo(b []byte, addr *IPAddr) (int, error) { + return 0, syscall.EPLAN9 +} + +func (c *IPConn) writeMsg(b, oob []byte, addr *IPAddr) (n, oobn int, err error) { + return 0, 0, syscall.EPLAN9 +} + +func (sd *sysDialer) dialIP(ctx context.Context, laddr, raddr *IPAddr) (*IPConn, error) { + return nil, syscall.EPLAN9 +} + +func (sl *sysListener) listenIP(ctx context.Context, laddr *IPAddr) (*IPConn, error) { + return nil, syscall.EPLAN9 +} diff --git a/go/src/net/iprawsock_posix.go b/go/src/net/iprawsock_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..b25cb648c3dc0d1bf51e9692b887ff651519db38 --- /dev/null +++ b/go/src/net/iprawsock_posix.go @@ -0,0 +1,159 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 || windows + +package net + +import ( + "context" + "syscall" +) + +func sockaddrToIP(sa syscall.Sockaddr) Addr { + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + return &IPAddr{IP: sa.Addr[0:]} + case *syscall.SockaddrInet6: + return &IPAddr{IP: sa.Addr[0:], Zone: zoneCache.name(int(sa.ZoneId))} + } + return nil +} + +func (a *IPAddr) family() int { + if a == nil || len(a.IP) <= IPv4len { + return syscall.AF_INET + } + if a.IP.To4() != nil { + return syscall.AF_INET + } + return syscall.AF_INET6 +} + +func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, error) { + if a == nil { + return nil, nil + } + return ipToSockaddr(family, a.IP, 0, a.Zone) +} + +func (a *IPAddr) toLocal(net string) sockaddr { + return &IPAddr{loopbackIP(net), a.Zone} +} + +func (c *IPConn) readFrom(b []byte) (int, *IPAddr, error) { + // TODO(cw,rsc): consider using readv if we know the family + // type to avoid the header trim/copy + var addr *IPAddr + n, sa, err := c.fd.readFrom(b) + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + addr = &IPAddr{IP: sa.Addr[0:]} + n = stripIPv4Header(n, b) + case *syscall.SockaddrInet6: + addr = &IPAddr{IP: sa.Addr[0:], Zone: zoneCache.name(int(sa.ZoneId))} + } + return n, addr, err +} + +func stripIPv4Header(n int, b []byte) int { + if len(b) < 20 { + return n + } + l := int(b[0]&0x0f) << 2 + if 20 > l || l > len(b) { + return n + } + if b[0]>>4 != 4 { + return n + } + copy(b, b[l:]) + return n - l +} + +func (c *IPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error) { + var sa syscall.Sockaddr + n, oobn, flags, sa, err = c.fd.readMsg(b, oob, 0) + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + addr = &IPAddr{IP: sa.Addr[0:]} + case *syscall.SockaddrInet6: + addr = &IPAddr{IP: sa.Addr[0:], Zone: zoneCache.name(int(sa.ZoneId))} + } + return +} + +func (c *IPConn) writeTo(b []byte, addr *IPAddr) (int, error) { + if c.fd.isConnected { + return 0, ErrWriteToConnected + } + if addr == nil { + return 0, errMissingAddress + } + sa, err := addr.sockaddr(c.fd.family) + if err != nil { + return 0, err + } + return c.fd.writeTo(b, sa) +} + +func (c *IPConn) writeMsg(b, oob []byte, addr *IPAddr) (n, oobn int, err error) { + if c.fd.isConnected { + return 0, 0, ErrWriteToConnected + } + if addr == nil { + return 0, 0, errMissingAddress + } + sa, err := addr.sockaddr(c.fd.family) + if err != nil { + return 0, 0, err + } + return c.fd.writeMsg(b, oob, sa) +} + +func (sd *sysDialer) dialIP(ctx context.Context, laddr, raddr *IPAddr) (*IPConn, error) { + network, proto, err := parseNetwork(ctx, sd.network, true) + if err != nil { + return nil, err + } + switch network { + case "ip", "ip4", "ip6": + default: + return nil, UnknownNetworkError(sd.network) + } + ctrlCtxFn := sd.Dialer.ControlContext + if ctrlCtxFn == nil && sd.Dialer.Control != nil { + ctrlCtxFn = func(ctx context.Context, network, address string, c syscall.RawConn) error { + return sd.Dialer.Control(network, address, c) + } + } + fd, err := internetSocket(ctx, network, laddr, raddr, syscall.SOCK_RAW, proto, "dial", ctrlCtxFn) + if err != nil { + return nil, err + } + return newIPConn(fd), nil +} + +func (sl *sysListener) listenIP(ctx context.Context, laddr *IPAddr) (*IPConn, error) { + network, proto, err := parseNetwork(ctx, sl.network, true) + if err != nil { + return nil, err + } + switch network { + case "ip", "ip4", "ip6": + default: + return nil, UnknownNetworkError(sl.network) + } + var ctrlCtxFn func(ctx context.Context, network, address string, c syscall.RawConn) error + if sl.ListenConfig.Control != nil { + ctrlCtxFn = func(ctx context.Context, network, address string, c syscall.RawConn) error { + return sl.ListenConfig.Control(network, address, c) + } + } + fd, err := internetSocket(ctx, network, laddr, nil, syscall.SOCK_RAW, proto, "listen", ctrlCtxFn) + if err != nil { + return nil, err + } + return newIPConn(fd), nil +} diff --git a/go/src/net/iprawsock_test.go b/go/src/net/iprawsock_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1fc139abc82c4589213eb3a0beb70eb44d58d4 --- /dev/null +++ b/go/src/net/iprawsock_test.go @@ -0,0 +1,200 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/testenv" + "reflect" + "testing" +) + +// The full stack test cases for IPConn have been moved to the +// following: +// golang.org/x/net/ipv4 +// golang.org/x/net/ipv6 +// golang.org/x/net/icmp + +type resolveIPAddrTest struct { + network string + litAddrOrName string + addr *IPAddr + err error +} + +var resolveIPAddrTests = []resolveIPAddrTest{ + {"ip", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, + {"ip4", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, + {"ip4:icmp", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, + + {"ip", "::1", &IPAddr{IP: ParseIP("::1")}, nil}, + {"ip6", "::1", &IPAddr{IP: ParseIP("::1")}, nil}, + {"ip6:ipv6-icmp", "::1", &IPAddr{IP: ParseIP("::1")}, nil}, + {"ip6:IPv6-ICMP", "::1", &IPAddr{IP: ParseIP("::1")}, nil}, + + {"ip", "::1%en0", &IPAddr{IP: ParseIP("::1"), Zone: "en0"}, nil}, + {"ip6", "::1%911", &IPAddr{IP: ParseIP("::1"), Zone: "911"}, nil}, + + {"", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, // Go 1.0 behavior + {"", "::1", &IPAddr{IP: ParseIP("::1")}, nil}, // Go 1.0 behavior + + {"ip4:icmp", "", &IPAddr{}, nil}, + + {"l2tp", "127.0.0.1", nil, UnknownNetworkError("l2tp")}, + {"l2tp:gre", "127.0.0.1", nil, UnknownNetworkError("l2tp:gre")}, + {"tcp", "1.2.3.4:123", nil, UnknownNetworkError("tcp")}, + + {"ip4", "2001:db8::1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "2001:db8::1"}}, + {"ip4:icmp", "2001:db8::1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "2001:db8::1"}}, + {"ip6", "127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "127.0.0.1"}}, + {"ip6", "::ffff:127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "::ffff:127.0.0.1"}}, + {"ip6:ipv6-icmp", "127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "127.0.0.1"}}, + {"ip6:ipv6-icmp", "::ffff:127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "::ffff:127.0.0.1"}}, +} + +func TestResolveIPAddr(t *testing.T) { + if !testableNetwork("ip+nopriv") { + t.Skip("ip+nopriv test") + } + + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + testHookLookupIP = lookupLocalhost + + for _, tt := range resolveIPAddrTests { + addr, err := ResolveIPAddr(tt.network, tt.litAddrOrName) + if !reflect.DeepEqual(addr, tt.addr) || !reflect.DeepEqual(err, tt.err) { + t.Errorf("ResolveIPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr, err, tt.addr, tt.err) + continue + } + if err == nil { + addr2, err := ResolveIPAddr(addr.Network(), addr.String()) + if !reflect.DeepEqual(addr2, tt.addr) || err != tt.err { + t.Errorf("(%q, %q): ResolveIPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr.Network(), addr.String(), addr2, err, tt.addr, tt.err) + } + } + } +} + +var ipConnLocalNameTests = []struct { + net string + laddr *IPAddr +}{ + {"ip4:icmp", &IPAddr{IP: IPv4(127, 0, 0, 1)}}, + {"ip4:icmp", &IPAddr{}}, + {"ip4:icmp", nil}, +} + +func TestIPConnLocalName(t *testing.T) { + for _, tt := range ipConnLocalNameTests { + if !testableNetwork(tt.net) { + t.Logf("skipping %s test", tt.net) + continue + } + c, err := ListenIP(tt.net, tt.laddr) + if testenv.SyscallIsNotSupported(err) { + // May be inside a container that disallows creating a socket. + t.Logf("skipping %s test: %v", tt.net, err) + continue + } else if err != nil { + t.Fatal(err) + } + defer c.Close() + if la := c.LocalAddr(); la == nil { + t.Fatal("should not fail") + } + } +} + +func TestIPConnRemoteName(t *testing.T) { + network := "ip:tcp" + if !testableNetwork(network) { + t.Skipf("skipping %s test", network) + } + + raddr := &IPAddr{IP: IPv4(127, 0, 0, 1).To4()} + c, err := DialIP(network, &IPAddr{IP: IPv4(127, 0, 0, 1)}, raddr) + if testenv.SyscallIsNotSupported(err) { + // May be inside a container that disallows creating a socket. + t.Skipf("skipping %s test: %v", network, err) + } else if err != nil { + t.Fatal(err) + } + defer c.Close() + if !reflect.DeepEqual(raddr, c.RemoteAddr()) { + t.Fatalf("got %#v; want %#v", c.RemoteAddr(), raddr) + } +} + +func TestDialListenIPArgs(t *testing.T) { + type test struct { + argLists [][2]string + shouldFail bool + } + tests := []test{ + { + argLists: [][2]string{ + {"ip", "127.0.0.1"}, + {"ip:", "127.0.0.1"}, + {"ip::", "127.0.0.1"}, + {"ip", "::1"}, + {"ip:", "::1"}, + {"ip::", "::1"}, + {"ip4", "127.0.0.1"}, + {"ip4:", "127.0.0.1"}, + {"ip4::", "127.0.0.1"}, + {"ip6", "::1"}, + {"ip6:", "::1"}, + {"ip6::", "::1"}, + }, + shouldFail: true, + }, + } + if testableNetwork("ip") { + priv := test{shouldFail: false} + for _, tt := range []struct { + network, address string + args [2]string + }{ + {"ip4:47", "127.0.0.1", [2]string{"ip4:47", "127.0.0.1"}}, + {"ip6:47", "::1", [2]string{"ip6:47", "::1"}}, + } { + c, err := ListenPacket(tt.network, tt.address) + if err != nil { + continue + } + c.Close() + priv.argLists = append(priv.argLists, tt.args) + } + if len(priv.argLists) > 0 { + tests = append(tests, priv) + } + } + + for _, tt := range tests { + for _, args := range tt.argLists { + _, err := Dial(args[0], args[1]) + if tt.shouldFail != (err != nil) { + t.Errorf("Dial(%q, %q) = %v; want (err != nil) is %t", args[0], args[1], err, tt.shouldFail) + } + _, err = ListenPacket(args[0], args[1]) + if tt.shouldFail != (err != nil) { + t.Errorf("ListenPacket(%q, %q) = %v; want (err != nil) is %t", args[0], args[1], err, tt.shouldFail) + } + a, err := ResolveIPAddr("ip", args[1]) + if err != nil { + t.Errorf("ResolveIPAddr(\"ip\", %q) = %v", args[1], err) + continue + } + _, err = DialIP(args[0], nil, a) + if tt.shouldFail != (err != nil) { + t.Errorf("DialIP(%q, %v) = %v; want (err != nil) is %t", args[0], a, err, tt.shouldFail) + } + _, err = ListenIP(args[0], a) + if tt.shouldFail != (err != nil) { + t.Errorf("ListenIP(%q, %v) = %v; want (err != nil) is %t", args[0], a, err, tt.shouldFail) + } + } + } +} diff --git a/go/src/net/ipsock.go b/go/src/net/ipsock.go new file mode 100644 index 0000000000000000000000000000000000000000..496faf346ec1e0e33ba5c3779d4455d5d94bd154 --- /dev/null +++ b/go/src/net/ipsock.go @@ -0,0 +1,327 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "internal/bytealg" + "runtime" + "sync" + _ "unsafe" // for linkname +) + +// BUG(rsc,mikio): On DragonFly BSD and OpenBSD, listening on the +// "tcp" and "udp" networks does not listen for both IPv4 and IPv6 +// connections. This is due to the fact that IPv4 traffic will not be +// routed to an IPv6 socket - two separate sockets are required if +// both address families are to be supported. +// See inet6(4) for details. + +type ipStackCapabilities struct { + sync.Once // guards following + ipv4Enabled bool + ipv6Enabled bool + ipv4MappedIPv6Enabled bool +} + +var ipStackCaps ipStackCapabilities + +// supportsIPv4 reports whether the platform supports IPv4 networking +// functionality. +func supportsIPv4() bool { + ipStackCaps.Once.Do(ipStackCaps.probe) + return ipStackCaps.ipv4Enabled +} + +// supportsIPv6 reports whether the platform supports IPv6 networking +// functionality. +func supportsIPv6() bool { + ipStackCaps.Once.Do(ipStackCaps.probe) + return ipStackCaps.ipv6Enabled +} + +// supportsIPv4map reports whether the platform supports mapping an +// IPv4 address inside an IPv6 address at transport layer +// protocols. See RFC 4291, RFC 4038 and RFC 3493. +func supportsIPv4map() bool { + // Some operating systems provide no support for mapping IPv4 + // addresses to IPv6, and a runtime check is unnecessary. + switch runtime.GOOS { + case "dragonfly", "openbsd": + return false + } + + ipStackCaps.Once.Do(ipStackCaps.probe) + return ipStackCaps.ipv4MappedIPv6Enabled +} + +// An addrList represents a list of network endpoint addresses. +type addrList []Addr + +// isIPv4 reports whether addr contains an IPv4 address. +func isIPv4(addr Addr) bool { + switch addr := addr.(type) { + case *TCPAddr: + return addr.IP.To4() != nil + case *UDPAddr: + return addr.IP.To4() != nil + case *IPAddr: + return addr.IP.To4() != nil + } + return false +} + +// isNotIPv4 reports whether addr does not contain an IPv4 address. +func isNotIPv4(addr Addr) bool { return !isIPv4(addr) } + +// forResolve returns the most appropriate address in address for +// a call to ResolveTCPAddr, ResolveUDPAddr, or ResolveIPAddr. +// IPv4 is preferred, unless addr contains an IPv6 literal. +func (addrs addrList) forResolve(network, addr string) Addr { + var want6 bool + switch network { + case "ip": + // IPv6 literal (addr does NOT contain a port) + want6 = bytealg.CountString(addr, ':') > 0 + case "tcp", "udp": + // IPv6 literal. (addr contains a port, so look for '[') + want6 = bytealg.CountString(addr, '[') > 0 + } + if want6 { + return addrs.first(isNotIPv4) + } + return addrs.first(isIPv4) +} + +// first returns the first address which satisfies strategy, or if +// none do, then the first address of any kind. +func (addrs addrList) first(strategy func(Addr) bool) Addr { + for _, addr := range addrs { + if strategy(addr) { + return addr + } + } + return addrs[0] +} + +// partition divides an address list into two categories, using a +// strategy function to assign a boolean label to each address. +// The first address, and any with a matching label, are returned as +// primaries, while addresses with the opposite label are returned +// as fallbacks. For non-empty inputs, primaries is guaranteed to be +// non-empty. +func (addrs addrList) partition(strategy func(Addr) bool) (primaries, fallbacks addrList) { + var primaryLabel bool + for i, addr := range addrs { + label := strategy(addr) + if i == 0 || label == primaryLabel { + primaryLabel = label + primaries = append(primaries, addr) + } else { + fallbacks = append(fallbacks, addr) + } + } + return +} + +// filterAddrList applies a filter to a list of IP addresses, +// yielding a list of Addr objects. Known filters are nil, ipv4only, +// and ipv6only. It returns every address when the filter is nil. +// The result contains at least one address when error is nil. +func filterAddrList(filter func(IPAddr) bool, ips []IPAddr, inetaddr func(IPAddr) Addr, originalAddr string) (addrList, error) { + var addrs addrList + for _, ip := range ips { + if filter == nil || filter(ip) { + addrs = append(addrs, inetaddr(ip)) + } + } + if len(addrs) == 0 { + return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: originalAddr} + } + return addrs, nil +} + +// ipv4only reports whether addr is an IPv4 address. +func ipv4only(addr IPAddr) bool { + return addr.IP.To4() != nil +} + +// ipv6only reports whether addr is an IPv6 address except IPv4-mapped IPv6 address. +func ipv6only(addr IPAddr) bool { + return len(addr.IP) == IPv6len && addr.IP.To4() == nil +} + +// SplitHostPort splits a network address of the form "host:port", +// "host%zone:port", "[host]:port" or "[host%zone]:port" into host or +// host%zone and port. +// +// A literal IPv6 address in hostport must be enclosed in square +// brackets, as in "[::1]:80", "[::1%lo0]:80". +// +// See func Dial for a description of the hostport parameter, and host +// and port results. +func SplitHostPort(hostport string) (host, port string, err error) { + const ( + missingPort = "missing port in address" + tooManyColons = "too many colons in address" + ) + addrErr := func(addr, why string) (host, port string, err error) { + return "", "", &AddrError{Err: why, Addr: addr} + } + j, k := 0, 0 + + // The port starts after the last colon. + i := bytealg.LastIndexByteString(hostport, ':') + if i < 0 { + return addrErr(hostport, missingPort) + } + + if hostport[0] == '[' { + // Expect the first ']' just before the last ':'. + end := bytealg.IndexByteString(hostport, ']') + if end < 0 { + return addrErr(hostport, "missing ']' in address") + } + switch end + 1 { + case len(hostport): + // There can't be a ':' behind the ']' now. + return addrErr(hostport, missingPort) + case i: + // The expected result. + default: + // Either ']' isn't followed by a colon, or it is + // followed by a colon that is not the last one. + if hostport[end+1] == ':' { + return addrErr(hostport, tooManyColons) + } + return addrErr(hostport, missingPort) + } + host = hostport[1:end] + j, k = 1, end+1 // there can't be a '[' resp. ']' before these positions + } else { + host = hostport[:i] + if bytealg.IndexByteString(host, ':') >= 0 { + return addrErr(hostport, tooManyColons) + } + } + if bytealg.IndexByteString(hostport[j:], '[') >= 0 { + return addrErr(hostport, "unexpected '[' in address") + } + if bytealg.IndexByteString(hostport[k:], ']') >= 0 { + return addrErr(hostport, "unexpected ']' in address") + } + + port = hostport[i+1:] + return host, port, nil +} + +func splitHostZone(s string) (host, zone string) { + // The IPv6 scoped addressing zone identifier starts after the + // last percent sign. + if i := bytealg.LastIndexByteString(s, '%'); i > 0 { + host, zone = s[:i], s[i+1:] + } else { + host = s + } + return +} + +// JoinHostPort combines host and port into a network address of the +// form "host:port". If host contains a colon, as found in literal +// IPv6 addresses, then JoinHostPort returns "[host]:port". +// +// See func Dial for a description of the host and port parameters. +func JoinHostPort(host, port string) string { + // We assume that host is a literal IPv6 address if host has + // colons. + if bytealg.IndexByteString(host, ':') >= 0 { + return "[" + host + "]:" + port + } + return host + ":" + port +} + +// internetAddrList resolves addr, which may be a literal IP +// address or a DNS name, and returns a list of internet protocol +// family addresses. The result contains at least one address when +// error is nil. +func (r *Resolver) internetAddrList(ctx context.Context, net, addr string) (addrList, error) { + var ( + err error + host, port string + portnum int + ) + switch net { + case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6": + if addr != "" { + if host, port, err = SplitHostPort(addr); err != nil { + return nil, err + } + if portnum, err = r.LookupPort(ctx, net, port); err != nil { + return nil, err + } + } + case "ip", "ip4", "ip6": + if addr != "" { + host = addr + } + default: + return nil, UnknownNetworkError(net) + } + inetaddr := func(ip IPAddr) Addr { + switch net { + case "tcp", "tcp4", "tcp6": + return &TCPAddr{IP: ip.IP, Port: portnum, Zone: ip.Zone} + case "udp", "udp4", "udp6": + return &UDPAddr{IP: ip.IP, Port: portnum, Zone: ip.Zone} + case "ip", "ip4", "ip6": + return &IPAddr{IP: ip.IP, Zone: ip.Zone} + default: + panic("unexpected network: " + net) + } + } + if host == "" { + return addrList{inetaddr(IPAddr{})}, nil + } + + // Try as a literal IP address, then as a DNS name. + ips, err := r.lookupIPAddr(ctx, net, host) + if err != nil { + return nil, err + } + // Issue 18806: if the machine has halfway configured + // IPv6 such that it can bind on "::" (IPv6unspecified) + // but not connect back to that same address, fall + // back to dialing 0.0.0.0. + if len(ips) == 1 && ips[0].IP.Equal(IPv6unspecified) { + ips = append(ips, IPAddr{IP: IPv4zero}) + } + + var filter func(IPAddr) bool + if net != "" && net[len(net)-1] == '4' { + filter = ipv4only + } + if net != "" && net[len(net)-1] == '6' { + filter = ipv6only + } + return filterAddrList(filter, ips, inetaddr, host) +} + +// loopbackIP should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/database64128/tfo-go/v2 +// - github.com/metacubex/tfo-go +// - github.com/sagernet/tfo-go +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname loopbackIP +func loopbackIP(net string) IP { + if net != "" && net[len(net)-1] == '6' { + return IPv6loopback + } + return IP{127, 0, 0, 1} +} diff --git a/go/src/net/ipsock_plan9.go b/go/src/net/ipsock_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..2bd5071d56a598f61ba53d0348fd2a174135ddb4 --- /dev/null +++ b/go/src/net/ipsock_plan9.go @@ -0,0 +1,367 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "internal/bytealg" + "internal/strconv" + "io/fs" + "os" + "syscall" +) + +// probe probes IPv4, IPv6 and IPv4-mapped IPv6 communication +// capabilities. +// +// Plan 9 uses IPv6 natively, see ip(3). +func (p *ipStackCapabilities) probe() { + p.ipv4Enabled = probe(netdir+"/iproute", "4i") + p.ipv6Enabled = probe(netdir+"/iproute", "6i") + if p.ipv4Enabled && p.ipv6Enabled { + p.ipv4MappedIPv6Enabled = true + } +} + +func probe(filename, query string) bool { + var file *file + var err error + if file, err = open(filename); err != nil { + return false + } + defer file.close() + + r := false + for line, ok := file.readLine(); ok && !r; line, ok = file.readLine() { + f := getFields(line) + if len(f) < 3 { + continue + } + for i := 0; i < len(f); i++ { + if query == f[i] { + r = true + break + } + } + } + return r +} + +// parsePlan9Addr parses address of the form [ip!]port (e.g. 127.0.0.1!80). +func parsePlan9Addr(s string) (ip IP, iport int, err error) { + addr := IPv4zero // address contains port only + i := bytealg.IndexByteString(s, '!') + if i >= 0 { + addr = ParseIP(s[:i]) + if addr == nil { + return nil, 0, &ParseError{Type: "IP address", Text: s} + } + } + p, plen, ok := dtoi(s[i+1:]) + if !ok { + return nil, 0, &ParseError{Type: "port", Text: s} + } + if p < 0 || p > 0xFFFF { + return nil, 0, &AddrError{Err: "invalid port", Addr: s[i+1 : i+1+plen]} + } + return addr, p, nil +} + +func readPlan9Addr(net, filename string) (addr Addr, err error) { + var buf [128]byte + + f, err := os.Open(filename) + if err != nil { + return + } + defer f.Close() + n, err := f.Read(buf[:]) + if err != nil { + return + } + ip, port, err := parsePlan9Addr(string(buf[:n])) + if err != nil { + return + } + switch net { + case "tcp4", "udp4": + if ip.Equal(IPv6zero) { + ip = ip[:IPv4len] + } + } + switch net { + case "tcp", "tcp4", "tcp6": + addr = &TCPAddr{IP: ip, Port: port} + case "udp", "udp4", "udp6": + addr = &UDPAddr{IP: ip, Port: port} + default: + return nil, UnknownNetworkError(net) + } + return addr, nil +} + +func startPlan9(ctx context.Context, net string, addr Addr) (ctl *os.File, dest, proto, name string, err error) { + var ( + ip IP + port int + ) + switch a := addr.(type) { + case *TCPAddr: + proto = "tcp" + ip = a.IP + port = a.Port + case *UDPAddr: + proto = "udp" + ip = a.IP + port = a.Port + default: + err = UnknownNetworkError(net) + return + } + + if port > 65535 { + err = InvalidAddrError("port should be < 65536") + return + } + + clone, dest, err := queryCS1(ctx, proto, ip, port) + if err != nil { + err = handlePlan9DNSError(err, net+":"+ip.String()+":"+strconv.Itoa(port)) + return + } + f, err := os.OpenFile(clone, os.O_RDWR, 0) + if err != nil { + return + } + var buf [16]byte + n, err := f.Read(buf[:]) + if err != nil { + f.Close() + return + } + return f, dest, proto, string(buf[:n]), nil +} + +func fixErr(err error) { + oe, ok := err.(*OpError) + if !ok { + return + } + nonNilInterface := func(a Addr) bool { + switch a := a.(type) { + case *TCPAddr: + return a == nil + case *UDPAddr: + return a == nil + case *IPAddr: + return a == nil + default: + return false + } + } + if nonNilInterface(oe.Source) { + oe.Source = nil + } + if nonNilInterface(oe.Addr) { + oe.Addr = nil + } + if pe, ok := oe.Err.(*fs.PathError); ok { + if _, ok = pe.Err.(syscall.ErrorString); ok { + oe.Err = pe.Err + } + } +} + +func dialPlan9(ctx context.Context, net string, laddr, raddr Addr) (fd *netFD, err error) { + defer func() { fixErr(err) }() + type res struct { + fd *netFD + err error + } + resc := make(chan res) + go func() { + fd, err := dialPlan9Blocking(ctx, net, laddr, raddr) + select { + case resc <- res{fd, err}: + case <-ctx.Done(): + if fd != nil { + fd.Close() + } + } + }() + select { + case res := <-resc: + return res.fd, res.err + case <-ctx.Done(): + return nil, mapErr(ctx.Err()) + } +} + +func dialPlan9Blocking(ctx context.Context, net string, laddr, raddr Addr) (fd *netFD, err error) { + if isWildcard(raddr) { + raddr = toLocal(raddr, net) + } + f, dest, proto, name, err := startPlan9(ctx, net, raddr) + if err != nil { + return nil, err + } + if la := plan9LocalAddr(laddr); la == "" { + err = hangupCtlWrite(ctx, proto, f, "connect "+dest) + } else { + err = hangupCtlWrite(ctx, proto, f, "connect "+dest+" "+la) + } + if err != nil { + f.Close() + return nil, err + } + data, err := os.OpenFile(netdir+"/"+proto+"/"+name+"/data", os.O_RDWR, 0) + if err != nil { + f.Close() + return nil, err + } + laddr, err = readPlan9Addr(net, netdir+"/"+proto+"/"+name+"/local") + if err != nil { + data.Close() + f.Close() + return nil, err + } + return newFD(proto, name, nil, f, data, laddr, raddr) +} + +func listenPlan9(ctx context.Context, net string, laddr Addr) (fd *netFD, err error) { + defer func() { fixErr(err) }() + f, dest, proto, name, err := startPlan9(ctx, net, laddr) + if err != nil { + return nil, err + } + _, err = f.WriteString("announce " + dest) + if err != nil { + f.Close() + return nil, &OpError{Op: "announce", Net: net, Source: laddr, Addr: nil, Err: err} + } + laddr, err = readPlan9Addr(net, netdir+"/"+proto+"/"+name+"/local") + if err != nil { + f.Close() + return nil, err + } + return newFD(proto, name, nil, f, nil, laddr, nil) +} + +func (fd *netFD) netFD() (*netFD, error) { + return newFD(fd.net, fd.n, fd.listen, fd.ctl, fd.data, fd.laddr, fd.raddr) +} + +func (fd *netFD) acceptPlan9() (nfd *netFD, err error) { + defer func() { fixErr(err) }() + if err := fd.pfd.ReadLock(); err != nil { + return nil, err + } + defer fd.pfd.ReadUnlock() + listen, err := os.Open(fd.dir + "/listen") + if err != nil { + return nil, err + } + var buf [16]byte + n, err := listen.Read(buf[:]) + if err != nil { + listen.Close() + return nil, err + } + name := string(buf[:n]) + ctl, err := os.OpenFile(netdir+"/"+fd.net+"/"+name+"/ctl", os.O_RDWR, 0) + if err != nil { + listen.Close() + return nil, err + } + data, err := os.OpenFile(netdir+"/"+fd.net+"/"+name+"/data", os.O_RDWR, 0) + if err != nil { + listen.Close() + ctl.Close() + return nil, err + } + raddr, err := readPlan9Addr(fd.net, netdir+"/"+fd.net+"/"+name+"/remote") + if err != nil { + listen.Close() + ctl.Close() + data.Close() + return nil, err + } + return newFD(fd.net, name, listen, ctl, data, fd.laddr, raddr) +} + +func isWildcard(a Addr) bool { + var wildcard bool + switch a := a.(type) { + case *TCPAddr: + wildcard = a.isWildcard() + case *UDPAddr: + wildcard = a.isWildcard() + case *IPAddr: + wildcard = a.isWildcard() + } + return wildcard +} + +func toLocal(a Addr, net string) Addr { + switch a := a.(type) { + case *TCPAddr: + a.IP = loopbackIP(net) + case *UDPAddr: + a.IP = loopbackIP(net) + case *IPAddr: + a.IP = loopbackIP(net) + } + return a +} + +// plan9LocalAddr returns a Plan 9 local address string. +// See setladdrport at https://9p.io/sources/plan9/sys/src/9/ip/devip.c. +func plan9LocalAddr(addr Addr) string { + var ip IP + port := 0 + switch a := addr.(type) { + case *TCPAddr: + if a != nil { + ip = a.IP + port = a.Port + } + case *UDPAddr: + if a != nil { + ip = a.IP + port = a.Port + } + } + if len(ip) == 0 || ip.IsUnspecified() { + if port == 0 { + return "" + } + return strconv.Itoa(port) + } + return ip.String() + "!" + strconv.Itoa(port) +} + +func hangupCtlWrite(ctx context.Context, proto string, ctl *os.File, msg string) error { + if proto != "tcp" { + _, err := ctl.WriteString(msg) + return err + } + written := make(chan struct{}) + errc := make(chan error) + go func() { + select { + case <-ctx.Done(): + ctl.WriteString("hangup") + errc <- mapErr(ctx.Err()) + case <-written: + errc <- nil + } + }() + _, err := ctl.WriteString(msg) + close(written) + if e := <-errc; err == nil && e != nil { // we hung up + return e + } + return err +} diff --git a/go/src/net/ipsock_plan9_test.go b/go/src/net/ipsock_plan9_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e5fb9ff965dd8600d468f3e833e0b816e8e6f9b5 --- /dev/null +++ b/go/src/net/ipsock_plan9_test.go @@ -0,0 +1,29 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "testing" + +func TestTCP4ListenZero(t *testing.T) { + l, err := Listen("tcp4", "0.0.0.0:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + if a := l.Addr(); isNotIPv4(a) { + t.Errorf("address does not contain IPv4: %v", a) + } +} + +func TestUDP4ListenZero(t *testing.T) { + c, err := ListenPacket("udp4", "0.0.0.0:0") + if err != nil { + t.Fatal(err) + } + defer c.Close() + if a := c.LocalAddr(); isNotIPv4(a) { + t.Errorf("address does not contain IPv4: %v", a) + } +} diff --git a/go/src/net/ipsock_posix.go b/go/src/net/ipsock_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..1ed37d7e6eaf251968a931e6f93443b76ea833ed --- /dev/null +++ b/go/src/net/ipsock_posix.go @@ -0,0 +1,269 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 || windows + +package net + +import ( + "context" + "internal/poll" + "net/netip" + "runtime" + "syscall" + _ "unsafe" // for linkname +) + +// probe probes IPv4, IPv6 and IPv4-mapped IPv6 communication +// capabilities which are controlled by the IPV6_V6ONLY socket option +// and kernel configuration. +// +// Should we try to use the IPv4 socket interface if we're only +// dealing with IPv4 sockets? As long as the host system understands +// IPv4-mapped IPv6, it's okay to pass IPv4-mapped IPv6 addresses to +// the IPv6 interface. That simplifies our code and is most +// general. Unfortunately, we need to run on kernels built without +// IPv6 support too. So probe the kernel to figure it out. +func (p *ipStackCapabilities) probe() { + switch runtime.GOOS { + case "js", "wasip1": + // Both ipv4 and ipv6 are faked; see net_fake.go. + p.ipv4Enabled = true + p.ipv6Enabled = true + p.ipv4MappedIPv6Enabled = true + return + } + + s, err := sysSocket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) + switch err { + case syscall.EAFNOSUPPORT, syscall.EPROTONOSUPPORT: + case nil: + poll.CloseFunc(s) + p.ipv4Enabled = true + } + var probes = []struct { + laddr TCPAddr + value int + }{ + // IPv6 communication capability + {laddr: TCPAddr{IP: ParseIP("::1")}, value: 1}, + // IPv4-mapped IPv6 address communication capability + {laddr: TCPAddr{IP: IPv4(127, 0, 0, 1)}, value: 0}, + } + switch runtime.GOOS { + case "dragonfly", "openbsd": + // The latest DragonFly BSD and OpenBSD kernels don't + // support IPV6_V6ONLY=0. They always return an error + // and we don't need to probe the capability. + probes = probes[:1] + } + for i := range probes { + s, err := sysSocket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) + if err != nil { + continue + } + defer poll.CloseFunc(s) + syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, probes[i].value) + sa, err := probes[i].laddr.sockaddr(syscall.AF_INET6) + if err != nil { + continue + } + if err := syscall.Bind(s, sa); err != nil { + continue + } + if i == 0 { + p.ipv6Enabled = true + } else { + p.ipv4MappedIPv6Enabled = true + } + } +} + +// favoriteAddrFamily returns the appropriate address family for the +// given network, laddr, raddr and mode. +// +// If mode indicates "listen" and laddr is a wildcard, we assume that +// the user wants to make a passive-open connection with a wildcard +// address family, both AF_INET and AF_INET6, and a wildcard address +// like the following: +// +// - A listen for a wildcard communication domain, "tcp" or +// "udp", with a wildcard address: If the platform supports +// both IPv6 and IPv4-mapped IPv6 communication capabilities, +// or does not support IPv4, we use a dual stack, AF_INET6 and +// IPV6_V6ONLY=0, wildcard address listen. The dual stack +// wildcard address listen may fall back to an IPv6-only, +// AF_INET6 and IPV6_V6ONLY=1, wildcard address listen. +// Otherwise we prefer an IPv4-only, AF_INET, wildcard address +// listen. +// +// - A listen for a wildcard communication domain, "tcp" or +// "udp", with an IPv4 wildcard address: same as above. +// +// - A listen for a wildcard communication domain, "tcp" or +// "udp", with an IPv6 wildcard address: same as above. +// +// - A listen for an IPv4 communication domain, "tcp4" or "udp4", +// with an IPv4 wildcard address: We use an IPv4-only, AF_INET, +// wildcard address listen. +// +// - A listen for an IPv6 communication domain, "tcp6" or "udp6", +// with an IPv6 wildcard address: We use an IPv6-only, AF_INET6 +// and IPV6_V6ONLY=1, wildcard address listen. +// +// Otherwise guess: If the addresses are IPv4 then returns AF_INET, +// or else returns AF_INET6. It also returns a boolean value what +// designates IPV6_V6ONLY option. +// +// Note that the latest DragonFly BSD and OpenBSD kernels allow +// neither "net.inet6.ip6.v6only=1" change nor IPPROTO_IPV6 level +// IPV6_V6ONLY socket option setting. +// +// favoriteAddrFamily should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/database64128/tfo-go/v2 +// - github.com/metacubex/tfo-go +// - github.com/sagernet/tfo-go +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname favoriteAddrFamily +func favoriteAddrFamily(network string, laddr, raddr sockaddr, mode string) (family int, ipv6only bool) { + switch network[len(network)-1] { + case '4': + return syscall.AF_INET, false + case '6': + return syscall.AF_INET6, true + } + + if mode == "listen" && (laddr == nil || laddr.isWildcard()) { + if supportsIPv4map() || !supportsIPv4() { + return syscall.AF_INET6, false + } + if laddr == nil { + return syscall.AF_INET, false + } + return laddr.family(), false + } + + if (laddr == nil || laddr.family() == syscall.AF_INET) && + (raddr == nil || raddr.family() == syscall.AF_INET) { + return syscall.AF_INET, false + } + return syscall.AF_INET6, false +} + +func internetSocket(ctx context.Context, net string, laddr, raddr sockaddr, sotype, proto int, mode string, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) (fd *netFD, err error) { + switch runtime.GOOS { + case "aix", "windows", "openbsd", "js", "wasip1": + if mode == "dial" && raddr.isWildcard() { + raddr = raddr.toLocal(net) + } + } + family, ipv6only := favoriteAddrFamily(net, laddr, raddr, mode) + return socket(ctx, net, family, sotype, proto, ipv6only, laddr, raddr, ctrlCtxFn) +} + +func ipToSockaddrInet4(ip IP, port int) (syscall.SockaddrInet4, error) { + if len(ip) == 0 { + ip = IPv4zero + } + ip4 := ip.To4() + if ip4 == nil { + return syscall.SockaddrInet4{}, &AddrError{Err: "non-IPv4 address", Addr: ip.String()} + } + sa := syscall.SockaddrInet4{Port: port} + copy(sa.Addr[:], ip4) + return sa, nil +} + +func ipToSockaddrInet6(ip IP, port int, zone string) (syscall.SockaddrInet6, error) { + // In general, an IP wildcard address, which is either + // "0.0.0.0" or "::", means the entire IP addressing + // space. For some historical reason, it is used to + // specify "any available address" on some operations + // of IP node. + // + // When the IP node supports IPv4-mapped IPv6 address, + // we allow a listener to listen to the wildcard + // address of both IP addressing spaces by specifying + // IPv6 wildcard address. + if len(ip) == 0 || ip.Equal(IPv4zero) { + ip = IPv6zero + } + // We accept any IPv6 address including IPv4-mapped + // IPv6 address. + ip6 := ip.To16() + if ip6 == nil { + return syscall.SockaddrInet6{}, &AddrError{Err: "non-IPv6 address", Addr: ip.String()} + } + sa := syscall.SockaddrInet6{Port: port, ZoneId: uint32(zoneCache.index(zone))} + copy(sa.Addr[:], ip6) + return sa, nil +} + +// ipToSockaddr should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/database64128/tfo-go/v2 +// - github.com/metacubex/tfo-go +// - github.com/sagernet/tfo-go +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname ipToSockaddr +func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error) { + switch family { + case syscall.AF_INET: + sa, err := ipToSockaddrInet4(ip, port) + if err != nil { + return nil, err + } + return &sa, nil + case syscall.AF_INET6: + sa, err := ipToSockaddrInet6(ip, port, zone) + if err != nil { + return nil, err + } + return &sa, nil + } + return nil, &AddrError{Err: "invalid address family", Addr: ip.String()} +} + +func addrPortToSockaddrInet4(ap netip.AddrPort) (syscall.SockaddrInet4, error) { + // ipToSockaddrInet4 has special handling here for zero length slices. + // We do not, because netip has no concept of a generic zero IP address. + // + // addr is allowed to be an IPv4-mapped IPv6 address. + // As4 will unmap it to an IPv4 address. + // The error message is kept consistent with ipToSockaddrInet4. + addr := ap.Addr() + if !addr.Is4() && !addr.Is4In6() { + return syscall.SockaddrInet4{}, &AddrError{Err: "non-IPv4 address", Addr: addr.String()} + } + sa := syscall.SockaddrInet4{ + Addr: addr.As4(), + Port: int(ap.Port()), + } + return sa, nil +} + +func addrPortToSockaddrInet6(ap netip.AddrPort) (syscall.SockaddrInet6, error) { + // ipToSockaddrInet6 has special handling here for zero length slices. + // We do not, because netip has no concept of a generic zero IP address. + // + // addr is allowed to be an IPv4 address, because As16 will convert it + // to an IPv4-mapped IPv6 address. + // The error message is kept consistent with ipToSockaddrInet6. + addr := ap.Addr() + sa := syscall.SockaddrInet6{ + Addr: addr.As16(), + Port: int(ap.Port()), + ZoneId: uint32(zoneCache.index(addr.Zone())), + } + return sa, nil +} diff --git a/go/src/net/ipsock_test.go b/go/src/net/ipsock_test.go new file mode 100644 index 0000000000000000000000000000000000000000..aede354844748449039aa71d0541ac70a0225f1c --- /dev/null +++ b/go/src/net/ipsock_test.go @@ -0,0 +1,282 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "reflect" + "testing" +) + +var testInetaddr = func(ip IPAddr) Addr { return &TCPAddr{IP: ip.IP, Port: 5682, Zone: ip.Zone} } + +var addrListTests = []struct { + filter func(IPAddr) bool + ips []IPAddr + inetaddr func(IPAddr) Addr + first Addr + primaries addrList + fallbacks addrList + err error +}{ + { + nil, + []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv6loopback}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}}, + addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}}, + nil, + }, + { + nil, + []IPAddr{ + {IP: IPv6loopback}, + {IP: IPv4(127, 0, 0, 1)}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}}, + addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}}, + nil, + }, + { + nil, + []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv4(192, 168, 0, 1)}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{ + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682}, + }, + nil, + nil, + }, + { + nil, + []IPAddr{ + {IP: IPv6loopback}, + {IP: ParseIP("fe80::1"), Zone: "eth0"}, + }, + testInetaddr, + &TCPAddr{IP: IPv6loopback, Port: 5682}, + addrList{ + &TCPAddr{IP: IPv6loopback, Port: 5682}, + &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"}, + }, + nil, + nil, + }, + { + nil, + []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv4(192, 168, 0, 1)}, + {IP: IPv6loopback}, + {IP: ParseIP("fe80::1"), Zone: "eth0"}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{ + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682}, + }, + addrList{ + &TCPAddr{IP: IPv6loopback, Port: 5682}, + &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"}, + }, + nil, + }, + { + nil, + []IPAddr{ + {IP: IPv6loopback}, + {IP: ParseIP("fe80::1"), Zone: "eth0"}, + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv4(192, 168, 0, 1)}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{ + &TCPAddr{IP: IPv6loopback, Port: 5682}, + &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"}, + }, + addrList{ + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682}, + }, + nil, + }, + { + nil, + []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv6loopback}, + {IP: IPv4(192, 168, 0, 1)}, + {IP: ParseIP("fe80::1"), Zone: "eth0"}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{ + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682}, + }, + addrList{ + &TCPAddr{IP: IPv6loopback, Port: 5682}, + &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"}, + }, + nil, + }, + { + nil, + []IPAddr{ + {IP: IPv6loopback}, + {IP: IPv4(127, 0, 0, 1)}, + {IP: ParseIP("fe80::1"), Zone: "eth0"}, + {IP: IPv4(192, 168, 0, 1)}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{ + &TCPAddr{IP: IPv6loopback, Port: 5682}, + &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"}, + }, + addrList{ + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682}, + }, + nil, + }, + + { + ipv4only, + []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv6loopback}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}}, + nil, + nil, + }, + { + ipv4only, + []IPAddr{ + {IP: IPv6loopback}, + {IP: IPv4(127, 0, 0, 1)}, + }, + testInetaddr, + &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}, + addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}}, + nil, + nil, + }, + + { + ipv6only, + []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv6loopback}, + }, + testInetaddr, + &TCPAddr{IP: IPv6loopback, Port: 5682}, + addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}}, + nil, + nil, + }, + { + ipv6only, + []IPAddr{ + {IP: IPv6loopback}, + {IP: IPv4(127, 0, 0, 1)}, + }, + testInetaddr, + &TCPAddr{IP: IPv6loopback, Port: 5682}, + addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}}, + nil, + nil, + }, + + {nil, nil, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}}, + + {ipv4only, nil, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}}, + {ipv4only, []IPAddr{{IP: IPv6loopback}}, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}}, + + {ipv6only, nil, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}}, + {ipv6only, []IPAddr{{IP: IPv4(127, 0, 0, 1)}}, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}}, +} + +func TestAddrList(t *testing.T) { + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + for i, tt := range addrListTests { + addrs, err := filterAddrList(tt.filter, tt.ips, tt.inetaddr, "ADDR") + if !reflect.DeepEqual(err, tt.err) { + t.Errorf("#%v: got %v; want %v", i, err, tt.err) + } + if tt.err != nil { + if len(addrs) != 0 { + t.Errorf("#%v: got %v; want 0", i, len(addrs)) + } + continue + } + first := addrs.first(isIPv4) + if !reflect.DeepEqual(first, tt.first) { + t.Errorf("#%v: got %v; want %v", i, first, tt.first) + } + primaries, fallbacks := addrs.partition(isIPv4) + if !reflect.DeepEqual(primaries, tt.primaries) { + t.Errorf("#%v: got %v; want %v", i, primaries, tt.primaries) + } + if !reflect.DeepEqual(fallbacks, tt.fallbacks) { + t.Errorf("#%v: got %v; want %v", i, fallbacks, tt.fallbacks) + } + expectedLen := len(primaries) + len(fallbacks) + if len(addrs) != expectedLen { + t.Errorf("#%v: got %v; want %v", i, len(addrs), expectedLen) + } + } +} + +func TestAddrListPartition(t *testing.T) { + addrs := addrList{ + &IPAddr{IP: ParseIP("fe80::"), Zone: "eth0"}, + &IPAddr{IP: ParseIP("fe80::1"), Zone: "eth0"}, + &IPAddr{IP: ParseIP("fe80::2"), Zone: "eth0"}, + } + cases := []struct { + lastByte byte + primaries addrList + fallbacks addrList + }{ + {0, addrList{addrs[0]}, addrList{addrs[1], addrs[2]}}, + {1, addrList{addrs[0], addrs[2]}, addrList{addrs[1]}}, + {2, addrList{addrs[0], addrs[1]}, addrList{addrs[2]}}, + {3, addrList{addrs[0], addrs[1], addrs[2]}, nil}, + } + for i, tt := range cases { + // Inverting the function's output should not affect the outcome. + for _, invert := range []bool{false, true} { + primaries, fallbacks := addrs.partition(func(a Addr) bool { + ip := a.(*IPAddr).IP + return (ip[len(ip)-1] == tt.lastByte) != invert + }) + if !reflect.DeepEqual(primaries, tt.primaries) { + t.Errorf("#%v: got %v; want %v", i, primaries, tt.primaries) + } + if !reflect.DeepEqual(fallbacks, tt.fallbacks) { + t.Errorf("#%v: got %v; want %v", i, fallbacks, tt.fallbacks) + } + } + } +} diff --git a/go/src/net/listen_test.go b/go/src/net/listen_test.go new file mode 100644 index 0000000000000000000000000000000000000000..59c1277a97966cb9e565c16e0e5968abd7dc1bf2 --- /dev/null +++ b/go/src/net/listen_test.go @@ -0,0 +1,751 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !plan9 + +package net + +import ( + "fmt" + "internal/testenv" + "os" + "runtime" + "syscall" + "testing" + "time" +) + +func (ln *TCPListener) port() string { + _, port, err := SplitHostPort(ln.Addr().String()) + if err != nil { + return "" + } + return port +} + +func (c *UDPConn) port() string { + _, port, err := SplitHostPort(c.LocalAddr().String()) + if err != nil { + return "" + } + return port +} + +var tcpListenerTests = []struct { + network string + address string +}{ + {"tcp", ""}, + {"tcp", "0.0.0.0"}, + {"tcp", "::ffff:0.0.0.0"}, + {"tcp", "::"}, + + {"tcp", "127.0.0.1"}, + {"tcp", "::ffff:127.0.0.1"}, + {"tcp", "::1"}, + + {"tcp4", ""}, + {"tcp4", "0.0.0.0"}, + {"tcp4", "::ffff:0.0.0.0"}, + + {"tcp4", "127.0.0.1"}, + {"tcp4", "::ffff:127.0.0.1"}, + + {"tcp6", ""}, + {"tcp6", "::"}, + + {"tcp6", "::1"}, +} + +// TestTCPListener tests both single and double listen to a test +// listener with same address family, same listening address and +// same port. +func TestTCPListener(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + for _, tt := range tcpListenerTests { + if !testableListenArgs(tt.network, JoinHostPort(tt.address, "0"), "") { + t.Logf("skipping %s test", tt.network+" "+tt.address) + continue + } + + ln1, err := Listen(tt.network, JoinHostPort(tt.address, "0")) + if err != nil { + t.Fatal(err) + } + if err := checkFirstListener(tt.network, ln1); err != nil { + ln1.Close() + t.Fatal(err) + } + ln2, err := Listen(tt.network, JoinHostPort(tt.address, ln1.(*TCPListener).port())) + if err == nil { + ln2.Close() + } + if err := checkSecondListener(tt.network, tt.address, err); err != nil { + ln1.Close() + t.Fatal(err) + } + ln1.Close() + } +} + +var udpListenerTests = []struct { + network string + address string +}{ + {"udp", ""}, + {"udp", "0.0.0.0"}, + {"udp", "::ffff:0.0.0.0"}, + {"udp", "::"}, + + {"udp", "127.0.0.1"}, + {"udp", "::ffff:127.0.0.1"}, + {"udp", "::1"}, + + {"udp4", ""}, + {"udp4", "0.0.0.0"}, + {"udp4", "::ffff:0.0.0.0"}, + + {"udp4", "127.0.0.1"}, + {"udp4", "::ffff:127.0.0.1"}, + + {"udp6", ""}, + {"udp6", "::"}, + + {"udp6", "::1"}, +} + +// TestUDPListener tests both single and double listen to a test +// listener with same address family, same listening address and +// same port. +func TestUDPListener(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + for _, tt := range udpListenerTests { + if !testableListenArgs(tt.network, JoinHostPort(tt.address, "0"), "") { + t.Logf("skipping %s test", tt.network+" "+tt.address) + continue + } + + c1, err := ListenPacket(tt.network, JoinHostPort(tt.address, "0")) + if err != nil { + t.Fatal(err) + } + if err := checkFirstListener(tt.network, c1); err != nil { + c1.Close() + t.Fatal(err) + } + c2, err := ListenPacket(tt.network, JoinHostPort(tt.address, c1.(*UDPConn).port())) + if err == nil { + c2.Close() + } + if err := checkSecondListener(tt.network, tt.address, err); err != nil { + c1.Close() + t.Fatal(err) + } + c1.Close() + } +} + +var dualStackTCPListenerTests = []struct { + network1, address1 string // first listener + network2, address2 string // second listener + xerr error // expected error value, nil or other +}{ + // Test cases and expected results for the attempting 2nd listen on the same port + // 1st listen 2nd listen darwin freebsd linux openbsd + // ------------------------------------------------------------------------------------ + // "tcp" "" "tcp" "" - - - - + // "tcp" "" "tcp" "0.0.0.0" - - - - + // "tcp" "0.0.0.0" "tcp" "" - - - - + // ------------------------------------------------------------------------------------ + // "tcp" "" "tcp" "[::]" - - - ok + // "tcp" "[::]" "tcp" "" - - - ok + // "tcp" "0.0.0.0" "tcp" "[::]" - - - ok + // "tcp" "[::]" "tcp" "0.0.0.0" - - - ok + // "tcp" "[::ffff:0.0.0.0]" "tcp" "[::]" - - - ok + // "tcp" "[::]" "tcp" "[::ffff:0.0.0.0]" - - - ok + // ------------------------------------------------------------------------------------ + // "tcp4" "" "tcp6" "" ok ok ok ok + // "tcp6" "" "tcp4" "" ok ok ok ok + // "tcp4" "0.0.0.0" "tcp6" "[::]" ok ok ok ok + // "tcp6" "[::]" "tcp4" "0.0.0.0" ok ok ok ok + // ------------------------------------------------------------------------------------ + // "tcp" "127.0.0.1" "tcp" "[::1]" ok ok ok ok + // "tcp" "[::1]" "tcp" "127.0.0.1" ok ok ok ok + // "tcp4" "127.0.0.1" "tcp6" "[::1]" ok ok ok ok + // "tcp6" "[::1]" "tcp4" "127.0.0.1" ok ok ok ok + // + // Platform default configurations: + // darwin, kernel version 11.3.0 + // net.inet6.ip6.v6only=0 (overridable by sysctl or IPV6_V6ONLY option) + // freebsd, kernel version 8.2 + // net.inet6.ip6.v6only=1 (overridable by sysctl or IPV6_V6ONLY option) + // linux, kernel version 3.0.0 + // net.ipv6.bindv6only=0 (overridable by sysctl or IPV6_V6ONLY option) + // openbsd, kernel version 5.0 + // net.inet6.ip6.v6only=1 (overriding is prohibited) + + {"tcp", "", "tcp", "", syscall.EADDRINUSE}, + {"tcp", "", "tcp", "0.0.0.0", syscall.EADDRINUSE}, + {"tcp", "0.0.0.0", "tcp", "", syscall.EADDRINUSE}, + + {"tcp", "", "tcp", "::", syscall.EADDRINUSE}, + {"tcp", "::", "tcp", "", syscall.EADDRINUSE}, + {"tcp", "0.0.0.0", "tcp", "::", syscall.EADDRINUSE}, + {"tcp", "::", "tcp", "0.0.0.0", syscall.EADDRINUSE}, + {"tcp", "::ffff:0.0.0.0", "tcp", "::", syscall.EADDRINUSE}, + {"tcp", "::", "tcp", "::ffff:0.0.0.0", syscall.EADDRINUSE}, + + {"tcp4", "", "tcp6", "", nil}, + {"tcp6", "", "tcp4", "", nil}, + {"tcp4", "0.0.0.0", "tcp6", "::", nil}, + {"tcp6", "::", "tcp4", "0.0.0.0", nil}, + + {"tcp", "127.0.0.1", "tcp", "::1", nil}, + {"tcp", "::1", "tcp", "127.0.0.1", nil}, + {"tcp4", "127.0.0.1", "tcp6", "::1", nil}, + {"tcp6", "::1", "tcp4", "127.0.0.1", nil}, +} + +// TestDualStackTCPListener tests both single and double listen +// to a test listener with various address families, different +// listening address and same port. +// +// On DragonFly BSD, we expect the kernel version of node under test +// to be greater than or equal to 4.4. +func TestDualStackTCPListener(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + for _, tt := range dualStackTCPListenerTests { + if !testableListenArgs(tt.network1, JoinHostPort(tt.address1, "0"), "") { + t.Logf("skipping %s test", tt.network1+" "+tt.address1) + continue + } + + if !supportsIPv4map() && differentWildcardAddr(tt.address1, tt.address2) { + tt.xerr = nil + } + var firstErr, secondErr error + for i := 0; i < 5; i++ { + lns, err := newDualStackListener() + if err != nil { + t.Fatal(err) + } + port := lns[0].port() + for _, ln := range lns { + ln.Close() + } + var ln1 Listener + ln1, firstErr = Listen(tt.network1, JoinHostPort(tt.address1, port)) + if firstErr != nil { + continue + } + if err := checkFirstListener(tt.network1, ln1); err != nil { + ln1.Close() + t.Fatal(err) + } + ln2, err := Listen(tt.network2, JoinHostPort(tt.address2, ln1.(*TCPListener).port())) + if err == nil { + ln2.Close() + } + if secondErr = checkDualStackSecondListener(tt.network2, tt.address2, err, tt.xerr); secondErr != nil { + ln1.Close() + continue + } + ln1.Close() + break + } + if firstErr != nil { + t.Error(firstErr) + } + if secondErr != nil { + t.Error(secondErr) + } + } +} + +var dualStackUDPListenerTests = []struct { + network1, address1 string // first listener + network2, address2 string // second listener + xerr error // expected error value, nil or other +}{ + {"udp", "", "udp", "", syscall.EADDRINUSE}, + {"udp", "", "udp", "0.0.0.0", syscall.EADDRINUSE}, + {"udp", "0.0.0.0", "udp", "", syscall.EADDRINUSE}, + + {"udp", "", "udp", "::", syscall.EADDRINUSE}, + {"udp", "::", "udp", "", syscall.EADDRINUSE}, + {"udp", "0.0.0.0", "udp", "::", syscall.EADDRINUSE}, + {"udp", "::", "udp", "0.0.0.0", syscall.EADDRINUSE}, + {"udp", "::ffff:0.0.0.0", "udp", "::", syscall.EADDRINUSE}, + {"udp", "::", "udp", "::ffff:0.0.0.0", syscall.EADDRINUSE}, + + {"udp4", "", "udp6", "", nil}, + {"udp6", "", "udp4", "", nil}, + {"udp4", "0.0.0.0", "udp6", "::", nil}, + {"udp6", "::", "udp4", "0.0.0.0", nil}, + + {"udp", "127.0.0.1", "udp", "::1", nil}, + {"udp", "::1", "udp", "127.0.0.1", nil}, + {"udp4", "127.0.0.1", "udp6", "::1", nil}, + {"udp6", "::1", "udp4", "127.0.0.1", nil}, +} + +// TestDualStackUDPListener tests both single and double listen +// to a test listener with various address families, different +// listening address and same port. +// +// On DragonFly BSD, we expect the kernel version of node under test +// to be greater than or equal to 4.4. +func TestDualStackUDPListener(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + if !supportsIPv4() || !supportsIPv6() { + t.Skip("both IPv4 and IPv6 are required") + } + + for _, tt := range dualStackUDPListenerTests { + if !testableListenArgs(tt.network1, JoinHostPort(tt.address1, "0"), "") { + t.Logf("skipping %s test", tt.network1+" "+tt.address1) + continue + } + + if !supportsIPv4map() && differentWildcardAddr(tt.address1, tt.address2) { + tt.xerr = nil + } + var firstErr, secondErr error + for i := 0; i < 5; i++ { + cs, err := newDualStackPacketListener() + if err != nil { + t.Fatal(err) + } + port := cs[0].port() + for _, c := range cs { + c.Close() + } + var c1 PacketConn + c1, firstErr = ListenPacket(tt.network1, JoinHostPort(tt.address1, port)) + if firstErr != nil { + continue + } + if err := checkFirstListener(tt.network1, c1); err != nil { + c1.Close() + t.Fatal(err) + } + c2, err := ListenPacket(tt.network2, JoinHostPort(tt.address2, c1.(*UDPConn).port())) + if err == nil { + c2.Close() + } + if secondErr = checkDualStackSecondListener(tt.network2, tt.address2, err, tt.xerr); secondErr != nil { + c1.Close() + continue + } + c1.Close() + break + } + if firstErr != nil { + t.Error(firstErr) + } + if secondErr != nil { + t.Error(secondErr) + } + } +} + +func differentWildcardAddr(i, j string) bool { + if (i == "" || i == "0.0.0.0" || i == "::ffff:0.0.0.0") && (j == "" || j == "0.0.0.0" || j == "::ffff:0.0.0.0") { + return false + } + if i == "[::]" && j == "[::]" { + return false + } + return true +} + +func checkFirstListener(network string, ln any) error { + switch network { + case "tcp": + fd := ln.(*TCPListener).fd + if err := checkDualStackAddrFamily(fd); err != nil { + return err + } + case "tcp4": + fd := ln.(*TCPListener).fd + if fd.family != syscall.AF_INET { + return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET) + } + case "tcp6": + fd := ln.(*TCPListener).fd + if fd.family != syscall.AF_INET6 { + return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET6) + } + case "udp": + fd := ln.(*UDPConn).fd + if err := checkDualStackAddrFamily(fd); err != nil { + return err + } + case "udp4": + fd := ln.(*UDPConn).fd + if fd.family != syscall.AF_INET { + return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET) + } + case "udp6": + fd := ln.(*UDPConn).fd + if fd.family != syscall.AF_INET6 { + return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET6) + } + default: + return UnknownNetworkError(network) + } + return nil +} + +func checkSecondListener(network, address string, err error) error { + switch network { + case "tcp", "tcp4", "tcp6": + if err == nil { + return fmt.Errorf("%s should fail", network+" "+address) + } + case "udp", "udp4", "udp6": + if err == nil { + return fmt.Errorf("%s should fail", network+" "+address) + } + default: + return UnknownNetworkError(network) + } + return nil +} + +func checkDualStackSecondListener(network, address string, err, xerr error) error { + switch network { + case "tcp", "tcp4", "tcp6": + if xerr == nil && err != nil || xerr != nil && err == nil { + return fmt.Errorf("%s got %v; want %v", network+" "+address, err, xerr) + } + case "udp", "udp4", "udp6": + if xerr == nil && err != nil || xerr != nil && err == nil { + return fmt.Errorf("%s got %v; want %v", network+" "+address, err, xerr) + } + default: + return UnknownNetworkError(network) + } + return nil +} + +func checkDualStackAddrFamily(fd *netFD) error { + switch a := fd.laddr.(type) { + case *TCPAddr: + // If a node under test supports both IPv6 capability + // and IPv6 IPv4-mapping capability, we can assume + // that the node listens on a wildcard address with an + // AF_INET6 socket. + if supportsIPv4map() && fd.laddr.(*TCPAddr).isWildcard() { + if fd.family != syscall.AF_INET6 { + return fmt.Errorf("Listen(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, syscall.AF_INET6) + } + } else { + if fd.family != a.family() { + return fmt.Errorf("Listen(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, a.family()) + } + } + case *UDPAddr: + // If a node under test supports both IPv6 capability + // and IPv6 IPv4-mapping capability, we can assume + // that the node listens on a wildcard address with an + // AF_INET6 socket. + if supportsIPv4map() && fd.laddr.(*UDPAddr).isWildcard() { + if fd.family != syscall.AF_INET6 { + return fmt.Errorf("ListenPacket(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, syscall.AF_INET6) + } + } else { + if fd.family != a.family() { + return fmt.Errorf("ListenPacket(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, a.family()) + } + } + default: + return fmt.Errorf("unexpected protocol address type: %T", a) + } + return nil +} + +func TestWildWildcardListener(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + defer func() { + if p := recover(); p != nil { + t.Fatalf("panicked: %v", p) + } + }() + + if ln, err := Listen("tcp", ""); err == nil { + ln.Close() + } + if ln, err := ListenPacket("udp", ""); err == nil { + ln.Close() + } + if ln, err := ListenTCP("tcp", nil); err == nil { + ln.Close() + } + if ln, err := ListenUDP("udp", nil); err == nil { + ln.Close() + } + if ln, err := ListenIP("ip:icmp", nil); err == nil { + ln.Close() + } +} + +var ipv4MulticastListenerTests = []struct { + net string + gaddr *UDPAddr // see RFC 4727 +}{ + {"udp", &UDPAddr{IP: IPv4(224, 0, 0, 254), Port: 12345}}, + + {"udp4", &UDPAddr{IP: IPv4(224, 0, 0, 254), Port: 12345}}, +} + +// TestIPv4MulticastListener tests both single and double listen to a +// test listener with same address family, same group address and same +// port. +func TestIPv4MulticastListener(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + switch runtime.GOOS { + case "android", "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + if !supportsIPv4() { + t.Skip("IPv4 is not supported") + } + + closer := func(cs []*UDPConn) { + for _, c := range cs { + if c != nil { + c.Close() + } + } + } + + for _, ifi := range []*Interface{loopbackInterface(), nil} { + // Note that multicast interface assignment by system + // is not recommended because it usually relies on + // routing stuff for finding out an appropriate + // nexthop containing both network and link layer + // adjacencies. + if ifi == nil || !*testIPv4 { + continue + } + for _, tt := range ipv4MulticastListenerTests { + var err error + cs := make([]*UDPConn, 2) + if cs[0], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { + t.Fatal(err) + } + if err := checkMulticastListener(cs[0], tt.gaddr.IP); err != nil { + closer(cs) + t.Fatal(err) + } + if cs[1], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { + closer(cs) + t.Fatal(err) + } + if err := checkMulticastListener(cs[1], tt.gaddr.IP); err != nil { + closer(cs) + t.Fatal(err) + } + closer(cs) + } + } +} + +var ipv6MulticastListenerTests = []struct { + net string + gaddr *UDPAddr // see RFC 4727 +}{ + {"udp", &UDPAddr{IP: ParseIP("ff01::114"), Port: 12345}}, + {"udp", &UDPAddr{IP: ParseIP("ff02::114"), Port: 12345}}, + {"udp", &UDPAddr{IP: ParseIP("ff04::114"), Port: 12345}}, + {"udp", &UDPAddr{IP: ParseIP("ff05::114"), Port: 12345}}, + {"udp", &UDPAddr{IP: ParseIP("ff08::114"), Port: 12345}}, + {"udp", &UDPAddr{IP: ParseIP("ff0e::114"), Port: 12345}}, + + {"udp6", &UDPAddr{IP: ParseIP("ff01::114"), Port: 12345}}, + {"udp6", &UDPAddr{IP: ParseIP("ff02::114"), Port: 12345}}, + {"udp6", &UDPAddr{IP: ParseIP("ff04::114"), Port: 12345}}, + {"udp6", &UDPAddr{IP: ParseIP("ff05::114"), Port: 12345}}, + {"udp6", &UDPAddr{IP: ParseIP("ff08::114"), Port: 12345}}, + {"udp6", &UDPAddr{IP: ParseIP("ff0e::114"), Port: 12345}}, +} + +// TestIPv6MulticastListener tests both single and double listen to a +// test listener with same address family, same group address and same +// port. +func TestIPv6MulticastListener(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + if !supportsIPv6() { + t.Skip("IPv6 is not supported") + } + // On Windows, the test can be run by non-admin users. + if runtime.GOOS != "windows" && os.Getuid() != 0 { + t.Skip("must be root") + } + + closer := func(cs []*UDPConn) { + for _, c := range cs { + if c != nil { + c.Close() + } + } + } + + for _, ifi := range []*Interface{loopbackInterface(), nil} { + // Note that multicast interface assignment by system + // is not recommended because it usually relies on + // routing stuff for finding out an appropriate + // nexthop containing both network and link layer + // adjacencies. + if ifi == nil && !*testIPv6 { + continue + } + for _, tt := range ipv6MulticastListenerTests { + var err error + cs := make([]*UDPConn, 2) + if cs[0], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { + t.Fatal(err) + } + if err := checkMulticastListener(cs[0], tt.gaddr.IP); err != nil { + closer(cs) + t.Fatal(err) + } + if cs[1], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { + closer(cs) + t.Fatal(err) + } + if err := checkMulticastListener(cs[1], tt.gaddr.IP); err != nil { + closer(cs) + t.Fatal(err) + } + closer(cs) + } + } +} + +func checkMulticastListener(c *UDPConn, ip IP) error { + if ok, err := multicastRIBContains(ip); err != nil { + return err + } else if !ok { + return fmt.Errorf("%s not found in multicast rib", ip.String()) + } + la := c.LocalAddr() + if la, ok := la.(*UDPAddr); !ok || la.Port == 0 { + return fmt.Errorf("got %v; want a proper address with non-zero port number", la) + } + return nil +} + +func multicastRIBContains(ip IP) (bool, error) { + switch runtime.GOOS { + case "aix", "dragonfly", "netbsd", "openbsd", "plan9", "solaris", "illumos": + return true, nil // not implemented yet + case "linux": + if runtime.GOARCH == "arm" || runtime.GOARCH == "alpha" { + return true, nil // not implemented yet + } + } + ift, err := Interfaces() + if err != nil { + return false, err + } + for _, ifi := range ift { + ifmat, err := ifi.MulticastAddrs() + if err != nil { + return false, err + } + for _, ifma := range ifmat { + if ifma.(*IPAddr).IP.Equal(ip) { + return true, nil + } + } + } + return false, nil +} + +// Issue 21856. +func TestClosingListener(t *testing.T) { + ln := newLocalListener(t, "tcp") + addr := ln.Addr() + + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + c.Close() + } + }() + + // Let the goroutine start. We don't sleep long: if the + // goroutine doesn't start, the test will pass without really + // testing anything, which is OK. + time.Sleep(time.Millisecond) + + ln.Close() + + ln2, err := Listen("tcp", addr.String()) + if err != nil { + t.Fatal(err) + } + ln2.Close() +} + +func TestListenConfigControl(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + t.Run("StreamListen", func(t *testing.T) { + for _, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} { + if !testableNetwork(network) { + continue + } + ln := newLocalListener(t, network, &ListenConfig{Control: controlOnConnSetup}) + ln.Close() + } + }) + t.Run("PacketListen", func(t *testing.T) { + for _, network := range []string{"udp", "udp4", "udp6", "unixgram"} { + if !testableNetwork(network) { + continue + } + c := newLocalPacketListener(t, network, &ListenConfig{Control: controlOnConnSetup}) + c.Close() + } + }) +} diff --git a/go/src/net/lookup.go b/go/src/net/lookup.go new file mode 100644 index 0000000000000000000000000000000000000000..d4be8eaa0e10c3786fd99a4358daa0b71f94c504 --- /dev/null +++ b/go/src/net/lookup.go @@ -0,0 +1,917 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "errors" + "internal/nettrace" + "internal/singleflight" + "internal/stringslite" + "net/netip" + "sync" + + "golang.org/x/net/dns/dnsmessage" +) + +// protocols contains minimal mappings between internet protocol +// names and numbers for platforms that don't have a complete list of +// protocol numbers. +// +// See https://www.iana.org/assignments/protocol-numbers +// +// On Unix, this map is augmented by readProtocols via lookupProtocol. +var protocols = map[string]int{ + "icmp": 1, + "igmp": 2, + "tcp": 6, + "udp": 17, + "ipv6-icmp": 58, +} + +// services contains minimal mappings between services names and port +// numbers for platforms that don't have a complete list of port numbers. +// +// See https://www.iana.org/assignments/service-names-port-numbers +// +// On Unix, this map is augmented by readServices via goLookupPort. +var services = map[string]map[string]int{ + "udp": { + "domain": 53, + }, + "tcp": { + "ftp": 21, + "ftps": 990, + "gopher": 70, // ʕ◔ϖ◔ʔ + "http": 80, + "https": 443, + "imap2": 143, + "imap3": 220, + "imaps": 993, + "pop3": 110, + "pop3s": 995, + "smtp": 25, + "submissions": 465, + "ssh": 22, + "telnet": 23, + }, +} + +// dnsWaitGroup can be used by tests to wait for all DNS goroutines to +// complete. This avoids races on the test hooks. +var dnsWaitGroup sync.WaitGroup + +const maxProtoLength = len("RSVP-E2E-IGNORE") + 10 // with room to grow + +func lookupProtocolMap(name string) (int, error) { + var lowerProtocol [maxProtoLength]byte + n := copy(lowerProtocol[:], name) + lowerASCIIBytes(lowerProtocol[:n]) + proto, found := protocols[string(lowerProtocol[:n])] + if !found || n != len(name) { + return 0, &AddrError{Err: "unknown IP protocol specified", Addr: name} + } + return proto, nil +} + +// maxPortBufSize is the longest reasonable name of a service +// (non-numeric port). +// Currently the longest known IANA-unregistered name is +// "mobility-header", so we use that length, plus some slop in case +// something longer is added in the future. +const maxPortBufSize = len("mobility-header") + 10 + +func lookupPortMap(network, service string) (port int, error error) { + switch network { + case "ip": // no hints + if p, err := lookupPortMapWithNetwork("tcp", "ip", service); err == nil { + return p, nil + } + return lookupPortMapWithNetwork("udp", "ip", service) + case "tcp", "tcp4", "tcp6": + return lookupPortMapWithNetwork("tcp", "tcp", service) + case "udp", "udp4", "udp6": + return lookupPortMapWithNetwork("udp", "udp", service) + } + return 0, &DNSError{Err: "unknown network", Name: network + "/" + service} +} + +func lookupPortMapWithNetwork(network, errNetwork, service string) (port int, error error) { + if m, ok := services[network]; ok { + var lowerService [maxPortBufSize]byte + n := copy(lowerService[:], service) + lowerASCIIBytes(lowerService[:n]) + if port, ok := m[string(lowerService[:n])]; ok && n == len(service) { + return port, nil + } + return 0, newDNSError(errUnknownPort, errNetwork+"/"+service, "") + } + return 0, &DNSError{Err: "unknown network", Name: errNetwork + "/" + service} +} + +// ipVersion returns the provided network's IP version: '4', '6' or 0 +// if network does not end in a '4' or '6' byte. +func ipVersion(network string) byte { + if network == "" { + return 0 + } + n := network[len(network)-1] + if n != '4' && n != '6' { + n = 0 + } + return n +} + +// DefaultResolver is the resolver used by the package-level Lookup +// functions and by Dialers without a specified Resolver. +var DefaultResolver = &Resolver{} + +// A Resolver looks up names and numbers. +// +// A nil *Resolver is equivalent to a zero Resolver. +type Resolver struct { + // PreferGo controls whether Go's built-in DNS resolver is preferred + // on platforms where it's available. It is equivalent to setting + // GODEBUG=netdns=go, but scoped to just this resolver. + PreferGo bool + + // StrictErrors controls the behavior of temporary errors + // (including timeout, socket errors, and SERVFAIL) when using + // Go's built-in resolver. For a query composed of multiple + // sub-queries (such as an A+AAAA address lookup, or walking the + // DNS search list), this option causes such errors to abort the + // whole query instead of returning a partial result. This is + // not enabled by default because it may affect compatibility + // with resolvers that process AAAA queries incorrectly. + StrictErrors bool + + // Dial optionally specifies an alternate dialer for use by + // Go's built-in DNS resolver to make TCP and UDP connections + // to DNS services. The host in the address parameter will + // always be a literal IP address and not a host name, and the + // port in the address parameter will be a literal port number + // and not a service name. + // If the Conn returned is also a PacketConn, sent and received DNS + // messages must adhere to RFC 1035 section 4.2.1, "UDP usage". + // Otherwise, DNS messages transmitted over Conn must adhere + // to RFC 7766 section 5, "Transport Protocol Selection". + // If nil, the default dialer is used. + Dial func(ctx context.Context, network, address string) (Conn, error) + + // lookupGroup merges LookupIPAddr calls together for lookups for the same + // host. The lookupGroup key is the LookupIPAddr.host argument. + // The return values are ([]IPAddr, error). + lookupGroup singleflight.Group + + // TODO(bradfitz): optional interface impl override hook + // TODO(bradfitz): Timeout time.Duration? +} + +func (r *Resolver) preferGo() bool { return r != nil && r.PreferGo } +func (r *Resolver) strictErrors() bool { return r != nil && r.StrictErrors } + +func (r *Resolver) getLookupGroup() *singleflight.Group { + if r == nil { + return &DefaultResolver.lookupGroup + } + return &r.lookupGroup +} + +// LookupHost looks up the given host using the local resolver. +// It returns a slice of that host's addresses. +// +// LookupHost uses [context.Background] internally; to specify the context, use +// [Resolver.LookupHost]. +func LookupHost(host string) (addrs []string, err error) { + return DefaultResolver.LookupHost(context.Background(), host) +} + +// LookupHost looks up the given host using the local resolver. +// It returns a slice of that host's addresses. +func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error) { + // Make sure that no matter what we do later, host=="" is rejected. + if host == "" { + return nil, newDNSError(errNoSuchHost, host, "") + } + if _, err := netip.ParseAddr(host); err == nil { + return []string{host}, nil + } + return r.lookupHost(ctx, host) +} + +// LookupIP looks up host using the local resolver. +// It returns a slice of that host's IPv4 and IPv6 addresses. +func LookupIP(host string) ([]IP, error) { + addrs, err := DefaultResolver.LookupIPAddr(context.Background(), host) + if err != nil { + return nil, err + } + ips := make([]IP, len(addrs)) + for i, ia := range addrs { + ips[i] = ia.IP + } + return ips, nil +} + +// LookupIPAddr looks up host using the local resolver. +// It returns a slice of that host's IPv4 and IPv6 addresses. +func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error) { + return r.lookupIPAddr(ctx, "ip", host) +} + +// LookupIP looks up host for the given network using the local resolver. +// It returns a slice of that host's IP addresses of the type specified by +// network. +// network must be one of "ip", "ip4" or "ip6". +func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error) { + afnet, _, err := parseNetwork(ctx, network, false) + if err != nil { + return nil, err + } + switch afnet { + case "ip", "ip4", "ip6": + default: + return nil, UnknownNetworkError(network) + } + + if host == "" { + return nil, newDNSError(errNoSuchHost, host, "") + } + addrs, err := r.internetAddrList(ctx, afnet, host) + if err != nil { + return nil, err + } + + ips := make([]IP, 0, len(addrs)) + for _, addr := range addrs { + ips = append(ips, addr.(*IPAddr).IP) + } + return ips, nil +} + +// LookupNetIP looks up host using the local resolver. +// It returns a slice of that host's IP addresses of the type specified by +// network. +// The network must be one of "ip", "ip4" or "ip6". +func (r *Resolver) LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error) { + // TODO(bradfitz): make this efficient, making the internal net package + // type throughout be netip.Addr and only converting to the net.IP slice + // version at the edge. But for now (2021-10-20), this is a wrapper around + // the old way. + ips, err := r.LookupIP(ctx, network, host) + if err != nil { + return nil, err + } + ret := make([]netip.Addr, 0, len(ips)) + for _, ip := range ips { + if a, ok := netip.AddrFromSlice(ip); ok { + ret = append(ret, a) + } + } + return ret, nil +} + +// onlyValuesCtx is a context that uses an underlying context +// for value lookup if the underlying context hasn't yet expired. +type onlyValuesCtx struct { + context.Context + lookupValues context.Context +} + +var _ context.Context = (*onlyValuesCtx)(nil) + +// Value performs a lookup if the original context hasn't expired. +func (ovc *onlyValuesCtx) Value(key any) any { + select { + case <-ovc.lookupValues.Done(): + return nil + default: + return ovc.lookupValues.Value(key) + } +} + +// withUnexpiredValuesPreserved returns a context.Context that only uses lookupCtx +// for its values, otherwise it is never canceled and has no deadline. +// If the lookup context expires, any looked up values will return nil. +// See Issue 28600. +func withUnexpiredValuesPreserved(lookupCtx context.Context) context.Context { + return &onlyValuesCtx{Context: context.Background(), lookupValues: lookupCtx} +} + +// lookupIPAddr looks up host using the local resolver and particular network. +// It returns a slice of that host's IPv4 and IPv6 addresses. +func (r *Resolver) lookupIPAddr(ctx context.Context, network, host string) ([]IPAddr, error) { + // Make sure that no matter what we do later, host=="" is rejected. + if host == "" { + return nil, newDNSError(errNoSuchHost, host, "") + } + if ip, err := netip.ParseAddr(host); err == nil { + return []IPAddr{{IP: IP(ip.AsSlice()).To16(), Zone: ip.Zone()}}, nil + } + trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace) + if trace != nil && trace.DNSStart != nil { + trace.DNSStart(host) + } + // The underlying resolver func is lookupIP by default but it + // can be overridden by tests. This is needed by net/http, so it + // uses a context key instead of unexported variables. + resolverFunc := r.lookupIP + if alt, _ := ctx.Value(nettrace.LookupIPAltResolverKey{}).(func(context.Context, string, string) ([]IPAddr, error)); alt != nil { + resolverFunc = alt + } + + // We don't want a cancellation of ctx to affect the + // lookupGroup operation. Otherwise if our context gets + // canceled it might cause an error to be returned to a lookup + // using a completely different context. However we need to preserve + // only the values in context. See Issue 28600. + lookupGroupCtx, lookupGroupCancel := context.WithCancel(withUnexpiredValuesPreserved(ctx)) + + lookupKey := network + "\000" + host + dnsWaitGroup.Add(1) + ch := r.getLookupGroup().DoChan(lookupKey, func() (any, error) { + return testHookLookupIP(lookupGroupCtx, resolverFunc, network, host) + }) + + dnsWaitGroupDone := func(ch <-chan singleflight.Result, cancelFn context.CancelFunc) { + <-ch + dnsWaitGroup.Done() + cancelFn() + } + select { + case <-ctx.Done(): + // Our context was canceled. If we are the only + // goroutine looking up this key, then drop the key + // from the lookupGroup and cancel the lookup. + // If there are other goroutines looking up this key, + // let the lookup continue uncanceled, and let later + // lookups with the same key share the result. + // See issues 8602, 20703, 22724. + if r.getLookupGroup().ForgetUnshared(lookupKey) { + lookupGroupCancel() + go dnsWaitGroupDone(ch, func() {}) + } else { + go dnsWaitGroupDone(ch, lookupGroupCancel) + } + err := newDNSError(mapErr(ctx.Err()), host, "") + if trace != nil && trace.DNSDone != nil { + trace.DNSDone(nil, false, err) + } + return nil, err + case r := <-ch: + dnsWaitGroup.Done() + lookupGroupCancel() + err := r.Err + if err != nil { + if _, ok := err.(*DNSError); !ok { + err = newDNSError(mapErr(err), host, "") + } + } + if trace != nil && trace.DNSDone != nil { + addrs, _ := r.Val.([]IPAddr) + trace.DNSDone(ipAddrsEface(addrs), r.Shared, err) + } + return lookupIPReturn(r.Val, err, r.Shared) + } +} + +// lookupIPReturn turns the return values from singleflight.Do into +// the return values from LookupIP. +func lookupIPReturn(addrsi any, err error, shared bool) ([]IPAddr, error) { + if err != nil { + return nil, err + } + addrs := addrsi.([]IPAddr) + if shared { + clone := make([]IPAddr, len(addrs)) + copy(clone, addrs) + addrs = clone + } + return addrs, nil +} + +// ipAddrsEface returns an empty interface slice of addrs. +func ipAddrsEface(addrs []IPAddr) []any { + s := make([]any, len(addrs)) + for i, v := range addrs { + s[i] = v + } + return s +} + +// LookupPort looks up the port for the given network and service. +// +// LookupPort uses [context.Background] internally; to specify the context, use +// [Resolver.LookupPort]. +func LookupPort(network, service string) (port int, err error) { + return DefaultResolver.LookupPort(context.Background(), network, service) +} + +// LookupPort looks up the port for the given network and service. +// +// The network must be one of "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6" or "ip". +func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error) { + port, needsLookup := parsePort(service) + if needsLookup { + switch network { + case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "ip": + case "": // a hint wildcard for Go 1.0 undocumented behavior + network = "ip" + default: + return 0, &AddrError{Err: "unknown network", Addr: network} + } + port, err = r.lookupPort(ctx, network, service) + if err != nil { + return 0, err + } + } + if 0 > port || port > 65535 { + return 0, &AddrError{Err: "invalid port", Addr: service} + } + return port, nil +} + +// LookupCNAME returns the canonical name for the given host. +// 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. +// +// A canonical name is the final name after following zero +// or more CNAME records. +// LookupCNAME does not return an error if host does not +// contain DNS "CNAME" records, as long as host resolves to +// address records. +// +// The returned canonical name is validated to be a properly +// formatted presentation-format domain name. +// +// LookupCNAME uses [context.Background] internally; to specify the context, use +// [Resolver.LookupCNAME]. +func LookupCNAME(host string) (cname string, err error) { + return DefaultResolver.LookupCNAME(context.Background(), host) +} + +// LookupCNAME returns the canonical name for the given host. +// 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. +// +// A canonical name is the final name after following zero +// or more CNAME records. +// LookupCNAME does not return an error if host does not +// contain DNS "CNAME" records, as long as host resolves to +// address records. +// +// The returned canonical name is validated to be a properly +// formatted presentation-format domain name. +func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error) { + cname, err := r.lookupCNAME(ctx, host) + if err != nil { + return "", err + } + if !isDomainName(cname) { + return "", &DNSError{Err: errMalformedDNSRecordsDetail, Name: host} + } + return cname, nil +} + +// LookupSRV tries to resolve an [SRV] query of the given service, +// protocol, and domain name. The proto is "tcp" or "udp". +// The returned records are sorted by priority and randomized +// by weight within a priority. +// +// LookupSRV constructs the DNS name to look up following RFC 2782. +// 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. +// +// The returned service names are validated to be properly +// formatted presentation-format domain names. If the response contains +// invalid names, those records are filtered out and an error +// will be returned alongside the remaining results, if any. +func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) { + return DefaultResolver.LookupSRV(context.Background(), service, proto, name) +} + +// LookupSRV tries to resolve an [SRV] query of the given service, +// protocol, and domain name. The proto is "tcp" or "udp". +// The returned records are sorted by priority and randomized +// by weight within a priority. +// +// LookupSRV constructs the DNS name to look up following RFC 2782. +// 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. +// +// The returned service names are validated to be properly +// formatted presentation-format domain names. If the response contains +// invalid names, those records are filtered out and an error +// will be returned alongside the remaining results, if any. +func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) { + cname, addrs, err := r.lookupSRV(ctx, service, proto, name) + if err != nil { + return "", nil, err + } + if cname != "" && !isDomainName(cname) { + return "", nil, &DNSError{Err: "SRV header name is invalid", Name: name} + } + filteredAddrs := make([]*SRV, 0, len(addrs)) + for _, addr := range addrs { + if addr == nil { + continue + } + if !isDomainName(addr.Target) { + continue + } + filteredAddrs = append(filteredAddrs, addr) + } + if len(addrs) != len(filteredAddrs) { + return cname, filteredAddrs, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name} + } + return cname, filteredAddrs, nil +} + +// LookupMX returns the DNS MX records for the given domain name sorted by preference. +// +// The returned mail server names are validated to be properly +// formatted presentation-format domain names, or numeric IP addresses. +// If the response contains invalid names, those records are filtered out +// and an error will be returned alongside the remaining results, if any. +// +// LookupMX uses [context.Background] internally; to specify the context, use +// [Resolver.LookupMX]. +func LookupMX(name string) ([]*MX, error) { + return DefaultResolver.LookupMX(context.Background(), name) +} + +// LookupMX returns the DNS MX records for the given domain name sorted by preference. +// +// The returned mail server names are validated to be properly +// formatted presentation-format domain names, or numeric IP addresses. +// If the response contains invalid names, those records are filtered out +// and an error will be returned alongside the remaining results, if any. +func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error) { + records, err := r.lookupMX(ctx, name) + if err != nil { + return nil, err + } + filteredMX := make([]*MX, 0, len(records)) + for _, mx := range records { + if mx == nil { + continue + } + if !isDomainName(mx.Host) { + // Check for IP address. In practice we observe + // these with a trailing dot, so strip that. + ip, err := netip.ParseAddr(stringslite.TrimSuffix(mx.Host, ".")) + if err != nil || ip.Zone() != "" { + continue + } + } + filteredMX = append(filteredMX, mx) + } + if len(records) != len(filteredMX) { + return filteredMX, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name} + } + return filteredMX, nil +} + +// LookupNS returns the DNS NS records for the given domain name. +// +// The returned name server names are validated to be properly +// formatted presentation-format domain names. If the response contains +// invalid names, those records are filtered out and an error +// will be returned alongside the remaining results, if any. +// +// LookupNS uses [context.Background] internally; to specify the context, use +// [Resolver.LookupNS]. +func LookupNS(name string) ([]*NS, error) { + return DefaultResolver.LookupNS(context.Background(), name) +} + +// LookupNS returns the DNS NS records for the given domain name. +// +// The returned name server names are validated to be properly +// formatted presentation-format domain names. If the response contains +// invalid names, those records are filtered out and an error +// will be returned alongside the remaining results, if any. +func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error) { + records, err := r.lookupNS(ctx, name) + if err != nil { + return nil, err + } + filteredNS := make([]*NS, 0, len(records)) + for _, ns := range records { + if ns == nil { + continue + } + if !isDomainName(ns.Host) { + continue + } + filteredNS = append(filteredNS, ns) + } + if len(records) != len(filteredNS) { + return filteredNS, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name} + } + return filteredNS, nil +} + +// LookupTXT returns the DNS TXT records for the given domain name. +// +// If a DNS TXT record holds multiple strings, they are concatenated as a +// single string. +// +// LookupTXT uses [context.Background] internally; to specify the context, use +// [Resolver.LookupTXT]. +func LookupTXT(name string) ([]string, error) { + return DefaultResolver.lookupTXT(context.Background(), name) +} + +// LookupTXT returns the DNS TXT records for the given domain name. +// +// If a DNS TXT record holds multiple strings, they are concatenated as a +// single string. +func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error) { + return r.lookupTXT(ctx, name) +} + +// LookupAddr performs a reverse lookup for the given address, returning a list +// of names mapping to that address. +// +// The returned names are validated to be properly formatted presentation-format +// domain names. If the response contains invalid names, those records are filtered +// out and an error will be returned alongside the remaining results, if any. +// +// When using the host C library resolver, at most one result will be +// returned. To bypass the host resolver, use a custom [Resolver]. +// +// LookupAddr uses [context.Background] internally; to specify the context, use +// [Resolver.LookupAddr]. +func LookupAddr(addr string) (names []string, err error) { + return DefaultResolver.LookupAddr(context.Background(), addr) +} + +// LookupAddr performs a reverse lookup for the given address, returning a list +// of names mapping to that address. +// +// The returned names are validated to be properly formatted presentation-format +// domain names. If the response contains invalid names, those records are filtered +// out and an error will be returned alongside the remaining results, if any. +func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, error) { + names, err := r.lookupAddr(ctx, addr) + if err != nil { + return nil, err + } + filteredNames := make([]string, 0, len(names)) + for _, name := range names { + if isDomainName(name) { + filteredNames = append(filteredNames, name) + } + } + if len(names) != len(filteredNames) { + return filteredNames, &DNSError{Err: errMalformedDNSRecordsDetail, Name: addr} + } + return filteredNames, nil +} + +// errMalformedDNSRecordsDetail is the DNSError detail which is returned when a Resolver.Lookup... +// method receives DNS records which contain invalid DNS names. This may be returned alongside +// results which have had the malformed records filtered out. +var errMalformedDNSRecordsDetail = "DNS response contained records which contain invalid names" + +// dial makes a new connection to the provided server (which must be +// an IP address) with the provided network type, using either r.Dial +// (if both r and r.Dial are non-nil) or else Dialer.DialContext. +func (r *Resolver) dial(ctx context.Context, network, server string) (Conn, error) { + // Calling Dial here is scary -- we have to be sure not to + // dial a name that will require a DNS lookup, or Dial will + // call back here to translate it. The DNS config parser has + // already checked that all the cfg.servers are IP + // addresses, which Dial will use without a DNS lookup. + var c Conn + var err error + if r != nil && r.Dial != nil { + c, err = r.Dial(ctx, network, server) + } else { + var d Dialer + c, err = d.DialContext(ctx, network, server) + } + if err != nil { + return nil, mapErr(err) + } + return c, nil +} + +// goLookupSRV returns the SRV records for a target name, built either +// from its component service ("sip"), protocol ("tcp"), and name +// ("example.com."), or from name directly (if service and proto are +// both empty). +// +// In either case, the returned target name ("_sip._tcp.example.com.") +// is also returned on success. +// +// The records are sorted by weight. +func (r *Resolver) goLookupSRV(ctx context.Context, service, proto, name string) (target string, srvs []*SRV, err error) { + if service == "" && proto == "" { + target = name + } else { + target = "_" + service + "._" + proto + "." + name + } + p, server, err := r.lookup(ctx, target, dnsmessage.TypeSRV, nil) + if err != nil { + return "", nil, err + } + var cname dnsmessage.Name + for { + h, err := p.AnswerHeader() + if err == dnsmessage.ErrSectionDone { + break + } + if err != nil { + return "", nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + if h.Type != dnsmessage.TypeSRV { + if err := p.SkipAnswer(); err != nil { + return "", nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + continue + } + if cname.Length == 0 && h.Name.Length != 0 { + cname = h.Name + } + srv, err := p.SRVResource() + if err != nil { + return "", nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + srvs = append(srvs, &SRV{Target: srv.Target.String(), Port: srv.Port, Priority: srv.Priority, Weight: srv.Weight}) + } + byPriorityWeight(srvs).sort() + return cname.String(), srvs, nil +} + +// goLookupMX returns the MX records for name. +func (r *Resolver) goLookupMX(ctx context.Context, name string) ([]*MX, error) { + p, server, err := r.lookup(ctx, name, dnsmessage.TypeMX, nil) + if err != nil { + return nil, err + } + var mxs []*MX + for { + h, err := p.AnswerHeader() + if err == dnsmessage.ErrSectionDone { + break + } + if err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + if h.Type != dnsmessage.TypeMX { + if err := p.SkipAnswer(); err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + continue + } + mx, err := p.MXResource() + if err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + mxs = append(mxs, &MX{Host: mx.MX.String(), Pref: mx.Pref}) + + } + byPref(mxs).sort() + return mxs, nil +} + +// goLookupNS returns the NS records for name. +func (r *Resolver) goLookupNS(ctx context.Context, name string) ([]*NS, error) { + p, server, err := r.lookup(ctx, name, dnsmessage.TypeNS, nil) + if err != nil { + return nil, err + } + var nss []*NS + for { + h, err := p.AnswerHeader() + if err == dnsmessage.ErrSectionDone { + break + } + if err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + if h.Type != dnsmessage.TypeNS { + if err := p.SkipAnswer(); err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + continue + } + ns, err := p.NSResource() + if err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + nss = append(nss, &NS{Host: ns.NS.String()}) + } + return nss, nil +} + +// goLookupTXT returns the TXT records from name. +func (r *Resolver) goLookupTXT(ctx context.Context, name string) ([]string, error) { + p, server, err := r.lookup(ctx, name, dnsmessage.TypeTXT, nil) + if err != nil { + return nil, err + } + var txts []string + for { + h, err := p.AnswerHeader() + if err == dnsmessage.ErrSectionDone { + break + } + if err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + if h.Type != dnsmessage.TypeTXT { + if err := p.SkipAnswer(); err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + continue + } + txt, err := p.TXTResource() + if err != nil { + return nil, &DNSError{ + Err: "cannot unmarshal DNS message", + Name: name, + Server: server, + } + } + // Multiple strings in one TXT record need to be + // concatenated without separator to be consistent + // with previous Go resolver. + n := 0 + for _, s := range txt.TXT { + n += len(s) + } + txtJoin := make([]byte, 0, n) + for _, s := range txt.TXT { + txtJoin = append(txtJoin, s...) + } + if len(txts) == 0 { + txts = make([]string, 0, 1) + } + txts = append(txts, string(txtJoin)) + } + return txts, nil +} + +func parseCNAMEFromResources(resources []dnsmessage.Resource) (string, error) { + if len(resources) == 0 { + return "", errors.New("no CNAME record received") + } + c, ok := resources[0].Body.(*dnsmessage.CNAMEResource) + if !ok { + return "", errors.New("could not parse CNAME record") + } + return c.CNAME.String(), nil +} diff --git a/go/src/net/lookup_plan9.go b/go/src/net/lookup_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..836beb3b17158b06e454a8848e4f842d0a7c28a2 --- /dev/null +++ b/go/src/net/lookup_plan9.go @@ -0,0 +1,384 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "errors" + "internal/bytealg" + "internal/strconv" + "internal/stringslite" + "io" + "os" +) + +// cgoAvailable set to true to indicate that the cgo resolver +// is available on Plan 9. Note that on Plan 9 the cgo resolver +// does not actually use cgo. +const cgoAvailable = true + +func query(ctx context.Context, filename, query string, bufSize int) (addrs []string, err error) { + queryAddrs := func() (addrs []string, err error) { + file, err := os.OpenFile(filename, os.O_RDWR, 0) + if err != nil { + return nil, err + } + defer file.Close() + + _, err = file.Seek(0, io.SeekStart) + if err != nil { + return nil, err + } + _, err = file.WriteString(query) + if err != nil { + return nil, err + } + _, err = file.Seek(0, io.SeekStart) + if err != nil { + return nil, err + } + buf := make([]byte, bufSize) + for { + n, _ := file.Read(buf) + if n <= 0 { + break + } + addrs = append(addrs, string(buf[:n])) + } + return addrs, nil + } + + type ret struct { + addrs []string + err error + } + + ch := make(chan ret, 1) + go func() { + addrs, err := queryAddrs() + ch <- ret{addrs: addrs, err: err} + }() + + select { + case r := <-ch: + return r.addrs, r.err + case <-ctx.Done(): + return nil, mapErr(ctx.Err()) + } +} + +func queryCS(ctx context.Context, net, host, service string) (res []string, err error) { + switch net { + case "tcp4", "tcp6": + net = "tcp" + case "udp4", "udp6": + net = "udp" + } + if host == "" { + host = "*" + } + return query(ctx, netdir+"/cs", net+"!"+host+"!"+service, 128) +} + +func queryCS1(ctx context.Context, net string, ip IP, port int) (clone, dest string, err error) { + ips := "*" + if len(ip) != 0 && !ip.IsUnspecified() { + ips = ip.String() + } + lines, err := queryCS(ctx, net, ips, strconv.Itoa(port)) + if err != nil { + return + } + f := getFields(lines[0]) + if len(f) < 2 { + return "", "", errors.New("bad response from ndb/cs") + } + clone, dest = f[0], f[1] + return +} + +func queryDNS(ctx context.Context, addr string, typ string) (res []string, err error) { + return query(ctx, netdir+"/dns", addr+" "+typ, 1024) +} + +func handlePlan9DNSError(err error, name string) error { + if stringslite.HasSuffix(err.Error(), "dns: name does not exist") || + stringslite.HasSuffix(err.Error(), "dns: resource does not exist; negrcode 0") || + stringslite.HasSuffix(err.Error(), "dns: resource does not exist; negrcode") || + stringslite.HasSuffix(err.Error(), "dns failure") { + err = errNoSuchHost + } + return newDNSError(err, name, "") +} + +// toLower returns a lower-case version of in. Restricting us to +// ASCII is sufficient to handle the IP protocol names and allow +// us to not depend on the strings and unicode packages. +func toLower(in string) string { + for _, c := range in { + if 'A' <= c && c <= 'Z' { + // Has upper case; need to fix. + out := []byte(in) + for i := 0; i < len(in); i++ { + c := in[i] + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + out[i] = c + } + return string(out) + } + } + return in +} + +// lookupProtocol looks up IP protocol name and returns +// the corresponding protocol number. +func lookupProtocol(ctx context.Context, name string) (proto int, err error) { + lines, err := query(ctx, netdir+"/cs", "!protocol="+toLower(name), 128) + if err != nil { + return 0, newDNSError(err, name, "") + } + if len(lines) == 0 { + return 0, UnknownNetworkError(name) + } + f := getFields(lines[0]) + if len(f) < 2 { + return 0, UnknownNetworkError(name) + } + s := f[1] + if n, _, ok := dtoi(s[bytealg.IndexByteString(s, '=')+1:]); ok { + return n, nil + } + return 0, UnknownNetworkError(name) +} + +func (*Resolver) lookupHost(ctx context.Context, host string) (addrs []string, err error) { + // Use netdir/cs instead of netdir/dns because cs knows about + // host names in local network (e.g. from /lib/ndb/local) + lines, err := queryCS(ctx, "net", host, "1") + if err != nil { + return nil, handlePlan9DNSError(err, host) + } +loop: + for _, line := range lines { + f := getFields(line) + if len(f) < 2 { + continue + } + addr := f[1] + if i := bytealg.IndexByteString(addr, '!'); i >= 0 { + addr = addr[:i] // remove port + } + if ParseIP(addr) == nil { + continue + } + // only return unique addresses + for _, a := range addrs { + if a == addr { + continue loop + } + } + addrs = append(addrs, addr) + } + return +} + +func (r *Resolver) lookupIP(ctx context.Context, network, host string) (addrs []IPAddr, err error) { + if order, conf := systemConf().hostLookupOrder(r, host); order != hostLookupCgo { + return r.goLookupIP(ctx, network, host, order, conf) + } + + lits, err := r.lookupHost(ctx, host) + if err != nil { + return + } + for _, lit := range lits { + host, zone := splitHostZone(lit) + if ip := ParseIP(host); ip != nil { + addr := IPAddr{IP: ip, Zone: zone} + addrs = append(addrs, addr) + } + } + return +} + +func (r *Resolver) lookupPort(ctx context.Context, network, service string) (port int, err error) { + switch network { + case "ip": // no hints + if p, err := r.lookupPortWithNetwork(ctx, "tcp", "ip", service); err == nil { + return p, nil + } + return r.lookupPortWithNetwork(ctx, "udp", "ip", service) + case "tcp", "tcp4", "tcp6": + return r.lookupPortWithNetwork(ctx, "tcp", "tcp", service) + case "udp", "udp4", "udp6": + return r.lookupPortWithNetwork(ctx, "udp", "udp", service) + default: + return 0, &DNSError{Err: "unknown network", Name: network + "/" + service} + } +} + +func (*Resolver) lookupPortWithNetwork(ctx context.Context, network, errNetwork, service string) (port int, err error) { + lines, err := queryCS(ctx, network, "127.0.0.1", toLower(service)) + if err != nil { + if stringslite.HasSuffix(err.Error(), "can't translate service") { + return 0, newDNSError(errUnknownPort, errNetwork+"/"+service, "") + } + return 0, newDNSError(err, errNetwork+"/"+service, "") + } + if len(lines) == 0 { + return 0, newDNSError(errUnknownPort, errNetwork+"/"+service, "") + } + f := getFields(lines[0]) + if len(f) < 2 { + return 0, newDNSError(errUnknownPort, errNetwork+"/"+service, "") + } + s := f[1] + if i := bytealg.IndexByteString(s, '!'); i >= 0 { + s = s[i+1:] // remove address + } + if n, _, ok := dtoi(s); ok { + return n, nil + } + return 0, newDNSError(errUnknownPort, errNetwork+"/"+service, "") +} + +func (r *Resolver) lookupCNAME(ctx context.Context, name string) (cname string, err error) { + if order, conf := systemConf().hostLookupOrder(r, name); order != hostLookupCgo { + return r.goLookupCNAME(ctx, name, order, conf) + } + + lines, err := queryDNS(ctx, name, "cname") + if err != nil { + if stringslite.HasSuffix(err.Error(), "dns failure") || + stringslite.HasSuffix(err.Error(), "resource does not exist; negrcode 0") || + stringslite.HasSuffix(err.Error(), "resource does not exist; negrcode") { + return absDomainName(name), nil + } + return "", handlePlan9DNSError(err, cname) + } + if len(lines) > 0 { + if f := getFields(lines[0]); len(f) >= 3 { + return f[2] + ".", nil + } + } + return "", &DNSError{Err: "bad response from ndb/dns", Name: name} +} + +func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*SRV, err error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupSRV(ctx, service, proto, name) + } + var target string + if service == "" && proto == "" { + target = name + } else { + target = "_" + service + "._" + proto + "." + name + } + lines, err := queryDNS(ctx, target, "srv") + if err != nil { + return "", nil, handlePlan9DNSError(err, name) + } + for _, line := range lines { + f := getFields(line) + if len(f) < 6 { + continue + } + port, _, portOk := dtoi(f[4]) + priority, _, priorityOk := dtoi(f[3]) + weight, _, weightOk := dtoi(f[2]) + if !(portOk && priorityOk && weightOk) { + continue + } + addrs = append(addrs, &SRV{absDomainName(f[5]), uint16(port), uint16(priority), uint16(weight)}) + cname = absDomainName(f[0]) + } + byPriorityWeight(addrs).sort() + return +} + +func (r *Resolver) lookupMX(ctx context.Context, name string) (mx []*MX, err error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupMX(ctx, name) + } + lines, err := queryDNS(ctx, name, "mx") + if err != nil { + return nil, handlePlan9DNSError(err, name) + } + for _, line := range lines { + f := getFields(line) + if len(f) < 4 { + continue + } + if pref, _, ok := dtoi(f[2]); ok { + mx = append(mx, &MX{absDomainName(f[3]), uint16(pref)}) + } + } + byPref(mx).sort() + return +} + +func (r *Resolver) lookupNS(ctx context.Context, name string) (ns []*NS, err error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupNS(ctx, name) + } + lines, err := queryDNS(ctx, name, "ns") + if err != nil { + return nil, handlePlan9DNSError(err, name) + } + for _, line := range lines { + f := getFields(line) + if len(f) < 3 { + continue + } + ns = append(ns, &NS{absDomainName(f[2])}) + } + return +} + +func (r *Resolver) lookupTXT(ctx context.Context, name string) (txt []string, err error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupTXT(ctx, name) + } + lines, err := queryDNS(ctx, name, "txt") + if err != nil { + return nil, handlePlan9DNSError(err, name) + } + for _, line := range lines { + if i := bytealg.IndexByteString(line, '\t'); i >= 0 { + txt = append(txt, line[i+1:]) + } + } + return +} + +func (r *Resolver) lookupAddr(ctx context.Context, addr string) (name []string, err error) { + if order, conf := systemConf().addrLookupOrder(r, addr); order != hostLookupCgo { + return r.goLookupPTR(ctx, addr, order, conf) + } + arpa, err := reverseaddr(addr) + if err != nil { + return + } + lines, err := queryDNS(ctx, arpa, "ptr") + if err != nil { + return nil, handlePlan9DNSError(err, addr) + } + for _, line := range lines { + f := getFields(line) + if len(f) < 3 { + continue + } + name = append(name, absDomainName(f[2])) + } + return +} + +// concurrentThreadsLimit returns the number of threads we permit to +// run concurrently doing DNS lookups. +func concurrentThreadsLimit() int { + return 500 +} diff --git a/go/src/net/lookup_test.go b/go/src/net/lookup_test.go new file mode 100644 index 0000000000000000000000000000000000000000..42211ed099ed1e7fe9d96c4da7328465dfd89e58 --- /dev/null +++ b/go/src/net/lookup_test.go @@ -0,0 +1,1652 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "errors" + "fmt" + "internal/testenv" + "net/netip" + "reflect" + "runtime" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +var goResolver = Resolver{PreferGo: true} + +func hasSuffixFold(s, suffix string) bool { + return strings.HasSuffix(strings.ToLower(s), strings.ToLower(suffix)) +} + +func lookupLocalhost(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + switch host { + case "localhost": + return []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv6loopback}, + }, nil + default: + return fn(ctx, network, host) + } +} + +// The Lookup APIs use various sources such as local database, DNS or +// mDNS, and may use platform-dependent DNS stub resolver if possible. +// The APIs accept any of forms for a query; host name in various +// encodings, UTF-8 encoded net name, domain name, FQDN or absolute +// FQDN, but the result would be one of the forms and it depends on +// the circumstances. + +var lookupGoogleSRVTests = []struct { + service, proto, name string + cname, target string +}{ + { + "ldap", "tcp", "google.com", + "google.com.", "google.com.", + }, + { + "ldap", "tcp", "google.com.", + "google.com.", "google.com.", + }, + + // non-standard back door + { + "", "", "_ldap._tcp.google.com", + "google.com.", "google.com.", + }, + { + "", "", "_ldap._tcp.google.com.", + "google.com.", "google.com.", + }, +} + +var backoffDuration = [...]time.Duration{time.Second, 5 * time.Second, 30 * time.Second} + +func TestLookupGoogleSRV(t *testing.T) { + t.Parallel() + mustHaveExternalNetwork(t) + + if runtime.GOOS == "ios" { + t.Skip("no resolv.conf on iOS") + } + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + attempts := 0 + for i := 0; i < len(lookupGoogleSRVTests); i++ { + tt := lookupGoogleSRVTests[i] + cname, srvs, err := LookupSRV(tt.service, tt.proto, tt.name) + if err != nil { + testenv.SkipFlakyNet(t) + if attempts < len(backoffDuration) { + dur := backoffDuration[attempts] + t.Logf("backoff %v after failure %v\n", dur, err) + time.Sleep(dur) + attempts++ + i-- + continue + } + t.Fatal(err) + } + if len(srvs) == 0 { + t.Error("got no record") + } + if !hasSuffixFold(cname, tt.cname) { + t.Errorf("got %s; want %s", cname, tt.cname) + } + for _, srv := range srvs { + if !hasSuffixFold(srv.Target, tt.target) { + t.Errorf("got %v; want a record containing %s", srv, tt.target) + } + } + } +} + +var lookupGmailMXTests = []struct { + name, host string +}{ + {"gmail.com", "google.com."}, + {"gmail.com.", "google.com."}, +} + +func TestLookupGmailMX(t *testing.T) { + t.Parallel() + mustHaveExternalNetwork(t) + + if runtime.GOOS == "ios" { + t.Skip("no resolv.conf on iOS") + } + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + attempts := 0 + for i := 0; i < len(lookupGmailMXTests); i++ { + tt := lookupGmailMXTests[i] + mxs, err := LookupMX(tt.name) + if err != nil { + testenv.SkipFlakyNet(t) + if attempts < len(backoffDuration) { + dur := backoffDuration[attempts] + t.Logf("backoff %v after failure %v\n", dur, err) + time.Sleep(dur) + attempts++ + i-- + continue + } + t.Fatal(err) + } + if len(mxs) == 0 { + t.Error("got no record") + } + for _, mx := range mxs { + if !hasSuffixFold(mx.Host, tt.host) { + t.Errorf("got %v; want a record containing %s", mx, tt.host) + } + } + } +} + +var lookupGmailNSTests = []struct { + name, host string +}{ + {"gmail.com", "google.com."}, + {"gmail.com.", "google.com."}, +} + +func TestLookupGmailNS(t *testing.T) { + t.Parallel() + mustHaveExternalNetwork(t) + + if runtime.GOOS == "ios" { + t.Skip("no resolv.conf on iOS") + } + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + attempts := 0 + for i := 0; i < len(lookupGmailNSTests); i++ { + tt := lookupGmailNSTests[i] + nss, err := LookupNS(tt.name) + if err != nil { + testenv.SkipFlakyNet(t) + if attempts < len(backoffDuration) { + dur := backoffDuration[attempts] + t.Logf("backoff %v after failure %v\n", dur, err) + time.Sleep(dur) + attempts++ + i-- + continue + } + t.Fatal(err) + } + if len(nss) == 0 { + t.Error("got no record") + } + for _, ns := range nss { + if !hasSuffixFold(ns.Host, tt.host) { + t.Errorf("got %v; want a record containing %s", ns, tt.host) + } + } + } +} + +var lookupGmailTXTTests = []struct { + name, txt, host string +}{ + {"gmail.com", "spf", "google.com"}, + {"gmail.com.", "spf", "google.com"}, +} + +func TestLookupGmailTXT(t *testing.T) { + if runtime.GOOS == "plan9" { + t.Skip("skipping on plan9; see https://golang.org/issue/29722") + } + t.Parallel() + mustHaveExternalNetwork(t) + + if runtime.GOOS == "ios" { + t.Skip("no resolv.conf on iOS") + } + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + attempts := 0 + for i := 0; i < len(lookupGmailTXTTests); i++ { + tt := lookupGmailTXTTests[i] + txts, err := LookupTXT(tt.name) + if err != nil { + testenv.SkipFlakyNet(t) + if attempts < len(backoffDuration) { + dur := backoffDuration[attempts] + t.Logf("backoff %v after failure %v\n", dur, err) + time.Sleep(dur) + attempts++ + i-- + continue + } + t.Fatal(err) + } + if len(txts) == 0 { + t.Error("got no record") + } + + if !slices.ContainsFunc(txts, func(txt string) bool { + return strings.Contains(txt, tt.txt) && (strings.HasSuffix(txt, tt.host) || strings.HasSuffix(txt, tt.host+".")) + }) { + t.Errorf("got %v; want a record containing %s, %s", txts, tt.txt, tt.host) + } + } +} + +var lookupGooglePublicDNSAddrTests = []string{ + "8.8.8.8", + "8.8.4.4", + "2001:4860:4860::8888", + "2001:4860:4860::8844", +} + +func TestLookupGooglePublicDNSAddr(t *testing.T) { + mustHaveExternalNetwork(t) + + if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 { + t.Skip("both IPv4 and IPv6 are required") + } + + defer dnsWaitGroup.Wait() + + for _, ip := range lookupGooglePublicDNSAddrTests { + names, err := LookupAddr(ip) + if err != nil { + t.Fatal(err) + } + if len(names) == 0 { + t.Error("got no record") + } + for _, name := range names { + if !hasSuffixFold(name, ".google.com.") && !hasSuffixFold(name, ".google.") { + t.Errorf("got %q; want a record ending in .google.com. or .google.", name) + } + } + } +} + +func TestLookupIPv6LinkLocalAddr(t *testing.T) { + if !supportsIPv6() || !*testIPv6 { + t.Skip("IPv6 is required") + } + + defer dnsWaitGroup.Wait() + + addrs, err := LookupHost("localhost") + if err != nil { + t.Fatal(err) + } + if !slices.Contains(addrs, "fe80::1%lo0") { + t.Skipf("not supported on %s", runtime.GOOS) + } + if _, err := LookupAddr("fe80::1%lo0"); err != nil { + t.Error(err) + } +} + +func TestLookupIPv6LinkLocalAddrWithZone(t *testing.T) { + if !supportsIPv6() || !*testIPv6 { + t.Skip("IPv6 is required") + } + + ipaddrs, err := DefaultResolver.LookupIPAddr(context.Background(), "fe80::1%lo0") + if err != nil { + t.Error(err) + } + for _, addr := range ipaddrs { + if e, a := "lo0", addr.Zone; e != a { + t.Errorf("wrong zone: want %q, got %q", e, a) + } + } + + addrs, err := DefaultResolver.LookupHost(context.Background(), "fe80::1%lo0") + if err != nil { + t.Error(err) + } + for _, addr := range addrs { + if e, a := "fe80::1%lo0", addr; e != a { + t.Errorf("wrong host: want %q got %q", e, a) + } + } +} + +var lookupCNAMETests = []struct { + name, cname string +}{ + {"www.iana.org", "icann.org."}, + {"www.iana.org.", "icann.org."}, + {"www.google.com", "google.com."}, + {"google.com", "google.com."}, + {"cname-to-txt.go4.org", "test-txt-record.go4.org."}, +} + +func TestLookupCNAME(t *testing.T) { + mustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + defer dnsWaitGroup.Wait() + + attempts := 0 + for i := 0; i < len(lookupCNAMETests); i++ { + tt := lookupCNAMETests[i] + cname, err := LookupCNAME(tt.name) + if err != nil { + testenv.SkipFlakyNet(t) + if attempts < len(backoffDuration) { + dur := backoffDuration[attempts] + t.Logf("backoff %v after failure %v\n", dur, err) + time.Sleep(dur) + attempts++ + i-- + continue + } + t.Fatal(err) + } + if !hasSuffixFold(cname, tt.cname) { + t.Errorf("got %s; want a record containing %s", cname, tt.cname) + } + } +} + +var lookupGoogleHostTests = []struct { + name string +}{ + {"google.com"}, + {"google.com."}, +} + +func TestLookupGoogleHost(t *testing.T) { + mustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + defer dnsWaitGroup.Wait() + + for _, tt := range lookupGoogleHostTests { + addrs, err := LookupHost(tt.name) + if err != nil { + t.Fatal(err) + } + if len(addrs) == 0 { + t.Error("got no record") + } + for _, addr := range addrs { + if ParseIP(addr) == nil { + t.Errorf("got %q; want a literal IP address", addr) + } + } + } +} + +func TestLookupLongTXT(t *testing.T) { + testenv.SkipFlaky(t, 22857) + mustHaveExternalNetwork(t) + + defer dnsWaitGroup.Wait() + + txts, err := LookupTXT("golang.rsc.io") + if err != nil { + t.Fatal(err) + } + slices.Sort(txts) + want := []string{ + strings.Repeat("abcdefghijklmnopqrstuvwxyABCDEFGHJIKLMNOPQRSTUVWXY", 10), + "gophers rule", + } + if !slices.Equal(txts, want) { + t.Fatalf("LookupTXT golang.rsc.io incorrect\nhave %q\nwant %q", txts, want) + } +} + +var lookupGoogleIPTests = []struct { + name string +}{ + {"google.com"}, + {"google.com."}, +} + +func TestLookupGoogleIP(t *testing.T) { + mustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + defer dnsWaitGroup.Wait() + + for _, tt := range lookupGoogleIPTests { + ips, err := LookupIP(tt.name) + if err != nil { + t.Fatal(err) + } + if len(ips) == 0 { + t.Error("got no record") + } + for _, ip := range ips { + if ip.To4() == nil && ip.To16() == nil { + t.Errorf("got %v; want an IP address", ip) + } + } + } +} + +var revAddrTests = []struct { + Addr string + Reverse string + ErrPrefix string +}{ + {"1.2.3.4", "4.3.2.1.in-addr.arpa.", ""}, + {"245.110.36.114", "114.36.110.245.in-addr.arpa.", ""}, + {"::ffff:12.34.56.78", "78.56.34.12.in-addr.arpa.", ""}, + {"::1", "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.", ""}, + {"1::", "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.0.ip6.arpa.", ""}, + {"1234:567::89a:bcde", "e.d.c.b.a.9.8.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.7.6.5.0.4.3.2.1.ip6.arpa.", ""}, + {"1234:567:fefe:bcbc:adad:9e4a:89a:bcde", "e.d.c.b.a.9.8.0.a.4.e.9.d.a.d.a.c.b.c.b.e.f.e.f.7.6.5.0.4.3.2.1.ip6.arpa.", ""}, + {"1.2.3", "", "unrecognized address"}, + {"1.2.3.4.5", "", "unrecognized address"}, + {"1234:567:bcbca::89a:bcde", "", "unrecognized address"}, + {"1234:567::bcbc:adad::89a:bcde", "", "unrecognized address"}, +} + +func TestReverseAddress(t *testing.T) { + defer dnsWaitGroup.Wait() + for i, tt := range revAddrTests { + a, err := reverseaddr(tt.Addr) + if len(tt.ErrPrefix) > 0 && err == nil { + t.Errorf("#%d: expected %q, got (error)", i, tt.ErrPrefix) + continue + } + if len(tt.ErrPrefix) == 0 && err != nil { + t.Errorf("#%d: expected , got %q (error)", i, err) + } + if err != nil && err.(*DNSError).Err != tt.ErrPrefix { + t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, err.(*DNSError).Err) + } + if a != tt.Reverse { + t.Errorf("#%d: expected %q, got %q (reverse address)", i, tt.Reverse, a) + } + } +} + +func TestDNSFlood(t *testing.T) { + if !*testDNSFlood { + t.Skip("test disabled; use -dnsflood to enable") + } + + defer dnsWaitGroup.Wait() + + var N = 5000 + if runtime.GOOS == "darwin" || runtime.GOOS == "ios" { + // On Darwin this test consumes kernel threads much + // than other platforms for some reason. + // When we monitor the number of allocated Ms by + // observing on runtime.newm calls, we can see that it + // easily reaches the per process ceiling + // kern.num_threads when CGO_ENABLED=1 and + // GODEBUG=netdns=go. + N = 500 + } + + const timeout = 3 * time.Second + ctxHalfTimeout, cancel := context.WithTimeout(context.Background(), timeout/2) + defer cancel() + ctxTimeout, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + c := make(chan error, 2*N) + for i := 0; i < N; i++ { + name := fmt.Sprintf("%d.net-test.golang.org", i) + go func() { + _, err := DefaultResolver.LookupIPAddr(ctxHalfTimeout, name) + c <- err + }() + go func() { + _, err := DefaultResolver.LookupIPAddr(ctxTimeout, name) + c <- err + }() + } + qstats := struct { + succeeded, failed int + timeout, temporary, other int + unknown int + }{} + deadline := time.After(timeout + time.Second) + for i := 0; i < 2*N; i++ { + select { + case <-deadline: + t.Fatal("deadline exceeded") + case err := <-c: + switch err := err.(type) { + case nil: + qstats.succeeded++ + case Error: + qstats.failed++ + if err.Timeout() { + qstats.timeout++ + } + if err.Temporary() { + qstats.temporary++ + } + if !err.Timeout() && !err.Temporary() { + qstats.other++ + } + default: + qstats.failed++ + qstats.unknown++ + } + } + } + + // A high volume of DNS queries for sub-domain of golang.org + // would be coordinated by authoritative or recursive server, + // or stub resolver which implements query-response rate + // limitation, so we can expect some query successes and more + // failures including timeout, temporary and other here. + // As a rule, unknown must not be shown but it might possibly + // happen due to issue 4856 for now. + t.Logf("%v succeeded, %v failed (%v timeout, %v temporary, %v other, %v unknown)", qstats.succeeded, qstats.failed, qstats.timeout, qstats.temporary, qstats.other, qstats.unknown) +} + +func TestLookupDotsWithLocalSource(t *testing.T) { + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + mustHaveExternalNetwork(t) + + defer dnsWaitGroup.Wait() + + for i, fn := range []func() func(){forceGoDNS, forceCgoDNS} { + fixup := fn() + if fixup == nil { + continue + } + names, err := LookupAddr("127.0.0.1") + fixup() + if err != nil { + t.Logf("#%d: %v", i, err) + continue + } + mode := "netgo" + if i == 1 { + mode = "netcgo" + } + loop: + for i, name := range names { + if strings.Index(name, ".") == len(name)-1 { // "localhost" not "localhost." + for j := range names { + if j == i { + continue + } + if names[j] == name[:len(name)-1] { + // It's OK if we find the name without the dot, + // as some systems say 127.0.0.1 localhost localhost. + continue loop + } + } + t.Errorf("%s: got %s; want %s", mode, name, name[:len(name)-1]) + } else if strings.Contains(name, ".") && !strings.HasSuffix(name, ".") { // "localhost.localdomain." not "localhost.localdomain" + t.Errorf("%s: got %s; want name ending with trailing dot", mode, name) + } + } + } +} + +func TestLookupDotsWithRemoteSource(t *testing.T) { + if runtime.GOOS == "darwin" || runtime.GOOS == "ios" { + testenv.SkipFlaky(t, 27992) + } + mustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + + if !supportsIPv4() || !*testIPv4 { + t.Skip("IPv4 is required") + } + + if runtime.GOOS == "ios" { + t.Skip("no resolv.conf on iOS") + } + + defer dnsWaitGroup.Wait() + + if fixup := forceGoDNS(); fixup != nil { + testDots(t, "go") + fixup() + } + if fixup := forceCgoDNS(); fixup != nil { + testDots(t, "cgo") + fixup() + } +} + +func testDots(t *testing.T, mode string) { + names, err := LookupAddr("8.8.8.8") // Google dns server + if err != nil { + t.Errorf("LookupAddr(8.8.8.8): %v (mode=%v)", err, mode) + } else { + for _, name := range names { + if !hasSuffixFold(name, ".google.com.") && !hasSuffixFold(name, ".google.") { + t.Errorf("LookupAddr(8.8.8.8) = %v, want names ending in .google.com or .google with trailing dot (mode=%v)", names, mode) + break + } + } + } + + cname, err := LookupCNAME("www.mit.edu") + if err != nil { + t.Errorf("LookupCNAME(www.mit.edu, mode=%v): %v", mode, err) + } else if !strings.HasSuffix(cname, ".") { + t.Errorf("LookupCNAME(www.mit.edu) = %v, want cname ending in . with trailing dot (mode=%v)", cname, mode) + } + + mxs, err := LookupMX("google.com") + if err != nil { + t.Errorf("LookupMX(google.com): %v (mode=%v)", err, mode) + } else { + for _, mx := range mxs { + if !hasSuffixFold(mx.Host, ".google.com.") { + t.Errorf("LookupMX(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", mxString(mxs), mode) + break + } + } + } + + nss, err := LookupNS("google.com") + if err != nil { + t.Errorf("LookupNS(google.com): %v (mode=%v)", err, mode) + } else { + for _, ns := range nss { + if !hasSuffixFold(ns.Host, ".google.com.") { + t.Errorf("LookupNS(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", nsString(nss), mode) + break + } + } + } + + cname, srvs, err := LookupSRV("ldap", "tcp", "google.com") + if err != nil { + t.Errorf("LookupSRV(ldap, tcp, google.com): %v (mode=%v)", err, mode) + } else { + if !hasSuffixFold(cname, ".google.com.") { + t.Errorf("LookupSRV(ldap, tcp, google.com) returned cname=%v, want name ending in .google.com. with trailing dot (mode=%v)", cname, mode) + } + for _, srv := range srvs { + if !hasSuffixFold(srv.Target, ".google.com.") { + t.Errorf("LookupSRV(ldap, tcp, google.com) returned addrs=%v, want names ending in .google.com. with trailing dot (mode=%v)", srvString(srvs), mode) + break + } + } + } +} + +func mxString(mxs []*MX) string { + var buf strings.Builder + sep := "" + fmt.Fprintf(&buf, "[") + for _, mx := range mxs { + fmt.Fprintf(&buf, "%s%s:%d", sep, mx.Host, mx.Pref) + sep = " " + } + fmt.Fprintf(&buf, "]") + return buf.String() +} + +func nsString(nss []*NS) string { + var buf strings.Builder + sep := "" + fmt.Fprintf(&buf, "[") + for _, ns := range nss { + fmt.Fprintf(&buf, "%s%s", sep, ns.Host) + sep = " " + } + fmt.Fprintf(&buf, "]") + return buf.String() +} + +func srvString(srvs []*SRV) string { + var buf strings.Builder + sep := "" + fmt.Fprintf(&buf, "[") + for _, srv := range srvs { + fmt.Fprintf(&buf, "%s%s:%d:%d:%d", sep, srv.Target, srv.Port, srv.Priority, srv.Weight) + sep = " " + } + fmt.Fprintf(&buf, "]") + return buf.String() +} + +func TestLookupPort(t *testing.T) { + // See https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml + // + // Please be careful about adding new test cases. + // There are platforms which have incomplete mappings for + // restricted resource access and security reasons. + type test struct { + network string + name string + port int + ok bool + } + var tests = []test{ + {"tcp", "0", 0, true}, + {"udp", "0", 0, true}, + {"udp", "domain", 53, true}, + + {"--badnet--", "zzz", 0, false}, + {"tcp", "--badport--", 0, false}, + {"tcp", "-1", 0, false}, + {"tcp", "65536", 0, false}, + {"udp", "-1", 0, false}, + {"udp", "65536", 0, false}, + {"tcp", "123456789", 0, false}, + {"tcp", "bad\x00port", 0, false}, + + // Issue 13610: LookupPort("tcp", "") + {"tcp", "", 0, true}, + {"tcp4", "", 0, true}, + {"tcp6", "", 0, true}, + {"udp", "", 0, true}, + {"udp4", "", 0, true}, + {"udp6", "", 0, true}, + } + + switch runtime.GOOS { + case "android": + if netGoBuildTag { + t.Skipf("not supported on %s without cgo; see golang.org/issues/14576", runtime.GOOS) + } + default: + tests = append(tests, test{"tcp", "http", 80, true}) + } + + for _, tt := range tests { + port, err := LookupPort(tt.network, tt.name) + if port != tt.port || (err == nil) != tt.ok { + t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=%t", tt.network, tt.name, port, err, tt.port, !tt.ok) + } + if err != nil { + if perr := parseLookupPortError(err); perr != nil { + t.Error(perr) + } + } + } +} + +// Like TestLookupPort but with minimal tests that should always pass +// because the answers are baked-in to the net package. +func TestLookupPort_Minimal(t *testing.T) { + type test struct { + network string + name string + port int + } + var tests = []test{ + {"tcp", "http", 80}, + {"tcp", "HTTP", 80}, // case shouldn't matter + {"tcp", "https", 443}, + {"tcp", "ssh", 22}, + {"tcp", "gopher", 70}, + {"tcp4", "http", 80}, + {"tcp6", "http", 80}, + } + + for _, tt := range tests { + port, err := LookupPort(tt.network, tt.name) + if port != tt.port || err != nil { + t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=nil", tt.network, tt.name, port, err, tt.port) + } + } +} + +func TestLookupProtocol_Minimal(t *testing.T) { + type test struct { + name string + want int + } + var tests = []test{ + {"tcp", 6}, + {"TcP", 6}, // case shouldn't matter + {"icmp", 1}, + {"igmp", 2}, + {"udp", 17}, + {"ipv6-icmp", 58}, + } + + for _, tt := range tests { + got, err := lookupProtocol(context.Background(), tt.name) + if got != tt.want || err != nil { + t.Errorf("LookupProtocol(%q) = %d, %v; want %d, error=nil", tt.name, got, err, tt.want) + } + } + +} + +func TestLookupNonLDH(t *testing.T) { + defer dnsWaitGroup.Wait() + + if fixup := forceGoDNS(); fixup != nil { + defer fixup() + } + + // "LDH" stands for letters, digits, and hyphens and is the usual + // description of standard DNS names. + // This test is checking that other kinds of names are reported + // as not found, not reported as invalid names. + addrs, err := LookupHost("!!!.###.bogus..domain.") + if err == nil { + t.Fatalf("lookup succeeded: %v", addrs) + } + if !strings.HasSuffix(err.Error(), errNoSuchHost.Error()) { + t.Fatalf("lookup error = %v, want %v", err, errNoSuchHost) + } + if !err.(*DNSError).IsNotFound { + t.Fatalf("lookup error = %v, want true", err.(*DNSError).IsNotFound) + } +} + +func TestLookupContextCancel(t *testing.T) { + mustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + + origTestHookLookupIP := testHookLookupIP + defer func() { + dnsWaitGroup.Wait() + testHookLookupIP = origTestHookLookupIP + }() + + lookupCtx, cancelLookup := context.WithCancel(context.Background()) + unblockLookup := make(chan struct{}) + + // Set testHookLookupIP to start a new, concurrent call to LookupIPAddr + // and cancel the original one, then block until the canceled call has returned + // (ensuring that it has performed any synchronous cleanup). + testHookLookupIP = func( + ctx context.Context, + fn func(context.Context, string, string) ([]IPAddr, error), + network string, + host string, + ) ([]IPAddr, error) { + select { + case <-unblockLookup: + default: + // Start a concurrent LookupIPAddr for the same host while the caller is + // still blocked, and sleep a little to give it time to be deduplicated + // before we cancel (and unblock) the caller. + // (If the timing doesn't quite work out, we'll end up testing sequential + // calls instead of concurrent ones, but the test should still pass.) + t.Logf("starting concurrent LookupIPAddr") + dnsWaitGroup.Add(1) + go func() { + defer dnsWaitGroup.Done() + _, err := DefaultResolver.LookupIPAddr(context.Background(), host) + if err != nil { + t.Error(err) + } + }() + time.Sleep(1 * time.Millisecond) + } + + cancelLookup() + <-unblockLookup + // If the concurrent lookup above is deduplicated to this one + // (as we expect to happen most of the time), it is important + // that the original call does not cancel the shared Context. + // (See https://go.dev/issue/22724.) Explicitly check for + // cancellation now, just in case fn itself doesn't notice it. + if err := ctx.Err(); err != nil { + t.Logf("testHookLookupIP canceled") + return nil, err + } + t.Logf("testHookLookupIP performing lookup") + return fn(ctx, network, host) + } + + _, err := DefaultResolver.LookupIPAddr(lookupCtx, "google.com") + if dnsErr, ok := err.(*DNSError); !ok || dnsErr.Err != errCanceled.Error() { + t.Errorf("unexpected error from canceled, blocked LookupIPAddr: %v", err) + } + close(unblockLookup) +} + +// Issue 24330: treat the nil *Resolver like a zero value. Verify nothing +// crashes if nil is used. +func TestNilResolverLookup(t *testing.T) { + mustHaveExternalNetwork(t) + var r *Resolver = nil + ctx := context.Background() + + // Don't care about the results, just that nothing panics: + r.LookupAddr(ctx, "8.8.8.8") + r.LookupCNAME(ctx, "google.com") + r.LookupHost(ctx, "google.com") + r.LookupIPAddr(ctx, "google.com") + r.LookupIP(ctx, "ip", "google.com") + r.LookupMX(ctx, "gmail.com") + r.LookupNS(ctx, "google.com") + r.LookupPort(ctx, "tcp", "smtp") + r.LookupSRV(ctx, "service", "proto", "name") + r.LookupTXT(ctx, "gmail.com") +} + +// TestLookupHostCancel verifies that lookup works even after many +// canceled lookups (see golang.org/issue/24178 for details). +func TestLookupHostCancel(t *testing.T) { + mustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + t.Parallel() // Executes 600ms worth of sequential sleeps. + + const ( + google = "www.google.com" + invalidDomain = "invalid.invalid" // RFC 2606 reserves .invalid + n = 600 // this needs to be larger than threadLimit size + ) + + _, err := LookupHost(google) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + for i := 0; i < n; i++ { + addr, err := DefaultResolver.LookupHost(ctx, invalidDomain) + if err == nil { + t.Fatalf("LookupHost(%q): returns %v, but should fail", invalidDomain, addr) + } + + // Don't verify what the actual error is. + // We know that it must be non-nil because the domain is invalid, + // but we don't have any guarantee that LookupHost actually bothers + // to check for cancellation on the fast path. + // (For example, it could use a local cache to avoid blocking entirely.) + + // The lookup may deduplicate in-flight requests, so give it time to settle + // in between. + time.Sleep(time.Millisecond * 1) + } + + _, err = LookupHost(google) + if err != nil { + t.Fatal(err) + } +} + +type lookupCustomResolver struct { + *Resolver + mu sync.RWMutex + dialed bool +} + +func (lcr *lookupCustomResolver) dial() func(ctx context.Context, network, address string) (Conn, error) { + return func(ctx context.Context, network, address string) (Conn, error) { + lcr.mu.Lock() + lcr.dialed = true + lcr.mu.Unlock() + return Dial(network, address) + } +} + +// TestConcurrentPreferGoResolversDial tests that multiple resolvers with the +// PreferGo option used concurrently are all dialed properly. +func TestConcurrentPreferGoResolversDial(t *testing.T) { + switch runtime.GOOS { + case "plan9": + // TODO: plan9 implementation of the resolver uses the Dial function since + // https://go.dev/cl/409234, this test could probably be reenabled. + t.Skipf("skip on %v", runtime.GOOS) + } + + testenv.MustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + + defer dnsWaitGroup.Wait() + + resolvers := make([]*lookupCustomResolver, 2) + for i := range resolvers { + cs := lookupCustomResolver{Resolver: &Resolver{PreferGo: true}} + cs.Dial = cs.dial() + resolvers[i] = &cs + } + + var wg sync.WaitGroup + wg.Add(len(resolvers)) + for i, resolver := range resolvers { + go func(r *Resolver, index int) { + defer wg.Done() + _, err := r.LookupIPAddr(context.Background(), "google.com") + if err != nil { + t.Errorf("lookup failed for resolver %d: %q", index, err) + } + }(resolver.Resolver, i) + } + wg.Wait() + + if t.Failed() { + t.FailNow() + } + + for i, resolver := range resolvers { + if !resolver.dialed { + t.Errorf("custom resolver %d not dialed during lookup", i) + } + } +} + +var ipVersionTests = []struct { + network string + version byte +}{ + {"tcp", 0}, + {"tcp4", '4'}, + {"tcp6", '6'}, + {"udp", 0}, + {"udp4", '4'}, + {"udp6", '6'}, + {"ip", 0}, + {"ip4", '4'}, + {"ip6", '6'}, + {"ip7", 0}, + {"", 0}, +} + +func TestIPVersion(t *testing.T) { + for _, tt := range ipVersionTests { + if version := ipVersion(tt.network); version != tt.version { + t.Errorf("Family for: %s. Expected: %s, Got: %s", tt.network, + string(tt.version), string(version)) + } + } +} + +// Issue 28600: The context that is used to lookup ips should always +// preserve the values from the context that was passed into LookupIPAddr. +func TestLookupIPAddrPreservesContextValues(t *testing.T) { + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + + keyValues := []struct { + key, value any + }{ + {"key-1", 12}, + {384, "value2"}, + {new(float64), 137}, + } + ctx := context.Background() + for _, kv := range keyValues { + ctx = context.WithValue(ctx, kv.key, kv.value) + } + + wantIPs := []IPAddr{ + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv6loopback}, + } + + checkCtxValues := func(ctx_ context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + for _, kv := range keyValues { + g, w := ctx_.Value(kv.key), kv.value + if !reflect.DeepEqual(g, w) { + t.Errorf("Value lookup:\n\tGot: %v\n\tWant: %v", g, w) + } + } + return wantIPs, nil + } + testHookLookupIP = checkCtxValues + + resolvers := []*Resolver{ + nil, + new(Resolver), + } + + for i, resolver := range resolvers { + gotIPs, err := resolver.LookupIPAddr(ctx, "golang.org") + if err != nil { + t.Errorf("Resolver #%d: unexpected error: %v", i, err) + } + if !reflect.DeepEqual(gotIPs, wantIPs) { + t.Errorf("#%d: mismatched IPAddr results\n\tGot: %v\n\tWant: %v", i, gotIPs, wantIPs) + } + } +} + +// Issue 30521: The lookup group should call the resolver for each network. +func TestLookupIPAddrConcurrentCallsForNetworks(t *testing.T) { + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + + queries := [][]string{ + {"udp", "golang.org"}, + {"udp4", "golang.org"}, + {"udp6", "golang.org"}, + {"udp", "golang.org"}, + {"udp", "golang.org"}, + } + results := map[[2]string][]IPAddr{ + {"udp", "golang.org"}: { + {IP: IPv4(127, 0, 0, 1)}, + {IP: IPv6loopback}, + }, + {"udp4", "golang.org"}: { + {IP: IPv4(127, 0, 0, 1)}, + }, + {"udp6", "golang.org"}: { + {IP: IPv6loopback}, + }, + } + calls := int32(0) + waitCh := make(chan struct{}) + testHookLookupIP = func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + // We'll block until this is called one time for each different + // expected result. This will ensure that the lookup group would wait + // for the existing call if it was to be reused. + if atomic.AddInt32(&calls, 1) == int32(len(results)) { + close(waitCh) + } + select { + case <-waitCh: + case <-ctx.Done(): + return nil, ctx.Err() + } + return results[[2]string{network, host}], nil + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + wg := sync.WaitGroup{} + for _, q := range queries { + network := q[0] + host := q[1] + wg.Add(1) + go func() { + defer wg.Done() + gotIPs, err := DefaultResolver.lookupIPAddr(ctx, network, host) + if err != nil { + t.Errorf("lookupIPAddr(%v, %v): unexpected error: %v", network, host, err) + } + wantIPs := results[[2]string{network, host}] + if !reflect.DeepEqual(gotIPs, wantIPs) { + t.Errorf("lookupIPAddr(%v, %v): mismatched IPAddr results\n\tGot: %v\n\tWant: %v", network, host, gotIPs, wantIPs) + } + }() + } + wg.Wait() +} + +// Issue 53995: Resolver.LookupIP should return error for empty host name. +func TestResolverLookupIPWithEmptyHost(t *testing.T) { + _, err := DefaultResolver.LookupIP(context.Background(), "ip", "") + if err == nil { + t.Fatal("DefaultResolver.LookupIP for empty host success, want no host error") + } + if !strings.HasSuffix(err.Error(), errNoSuchHost.Error()) { + t.Fatalf("lookup error = %v, want %v", err, errNoSuchHost) + } +} + +func TestWithUnexpiredValuesPreserved(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + + // Insert a value into it. + key, value := "key-1", 2 + ctx = context.WithValue(ctx, key, value) + + // Now use the "values preserving context" like + // we would for LookupIPAddr. See Issue 28600. + ctx = withUnexpiredValuesPreserved(ctx) + + // Lookup before expiry. + if g, w := ctx.Value(key), value; g != w { + t.Errorf("Lookup before expiry: Got %v Want %v", g, w) + } + + // Cancel the context. + cancel() + + // Lookup after expiry should return nil + if g := ctx.Value(key); g != nil { + t.Errorf("Lookup after expiry: Got %v want nil", g) + } +} + +// Issue 31597: don't panic on null byte in name +func TestLookupNullByte(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + testenv.SkipFlakyNet(t) + LookupHost("foo\x00bar") // check that it doesn't panic; it used to on Windows +} + +func TestResolverLookupIP(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + v4Ok := supportsIPv4() && *testIPv4 + v6Ok := supportsIPv6() && *testIPv6 + + defer dnsWaitGroup.Wait() + + for _, impl := range []struct { + name string + fn func() func() + }{ + {"go", forceGoDNS}, + {"cgo", forceCgoDNS}, + } { + t.Run("implementation: "+impl.name, func(t *testing.T) { + fixup := impl.fn() + if fixup == nil { + t.Skip("not supported") + } + defer fixup() + + for _, network := range []string{"ip", "ip4", "ip6"} { + t.Run("network: "+network, func(t *testing.T) { + switch { + case network == "ip4" && !v4Ok: + t.Skip("IPv4 is not supported") + case network == "ip6" && !v6Ok: + t.Skip("IPv6 is not supported") + } + + // google.com has both A and AAAA records. + const host = "google.com" + ips, err := DefaultResolver.LookupIP(context.Background(), network, host) + if err != nil { + testenv.SkipFlakyNet(t) + t.Fatalf("DefaultResolver.LookupIP(%q, %q): failed with unexpected error: %v", network, host, err) + } + + var v4Addrs []netip.Addr + var v6Addrs []netip.Addr + for _, ip := range ips { + if addr, ok := netip.AddrFromSlice(ip); ok { + if addr.Is4() { + v4Addrs = append(v4Addrs, addr) + } else { + v6Addrs = append(v6Addrs, addr) + } + } else { + t.Fatalf("IP=%q is neither IPv4 nor IPv6", ip) + } + } + + // Check that we got the expected addresses. + if network == "ip4" || network == "ip" && v4Ok { + if len(v4Addrs) == 0 { + t.Errorf("DefaultResolver.LookupIP(%q, %q): no IPv4 addresses", network, host) + } + } + if network == "ip6" || network == "ip" && v6Ok { + if len(v6Addrs) == 0 { + t.Errorf("DefaultResolver.LookupIP(%q, %q): no IPv6 addresses", network, host) + } + } + + // Check that we didn't get any unexpected addresses. + if network == "ip6" && len(v4Addrs) > 0 { + t.Errorf("DefaultResolver.LookupIP(%q, %q): unexpected IPv4 addresses: %v", network, host, v4Addrs) + } + if network == "ip4" && len(v6Addrs) > 0 { + t.Errorf("DefaultResolver.LookupIP(%q, %q): unexpected IPv6 or IPv4-mapped IPv6 addresses: %v", network, host, v6Addrs) + } + }) + } + }) + } +} + +// A context timeout should still return a DNSError. +func TestDNSTimeout(t *testing.T) { + origTestHookLookupIP := testHookLookupIP + defer func() { testHookLookupIP = origTestHookLookupIP }() + defer dnsWaitGroup.Wait() + + timeoutHookGo := make(chan bool, 1) + timeoutHook := func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) { + <-timeoutHookGo + return nil, context.DeadlineExceeded + } + testHookLookupIP = timeoutHook + + checkErr := func(err error) { + t.Helper() + if err == nil { + t.Error("expected an error") + } else if dnserr, ok := err.(*DNSError); !ok { + t.Errorf("got error type %T, want %T", err, (*DNSError)(nil)) + } else if !dnserr.IsTimeout { + t.Errorf("got error %#v, want IsTimeout == true", dnserr) + } else if isTimeout := dnserr.Timeout(); !isTimeout { + t.Errorf("got err.Timeout() == %t, want true", isTimeout) + } + } + + // Single lookup. + timeoutHookGo <- true + _, err := LookupIP("golang.org") + checkErr(err) + + // Double lookup. + var err1, err2 error + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + _, err1 = LookupIP("golang1.org") + }() + go func() { + defer wg.Done() + _, err2 = LookupIP("golang1.org") + }() + close(timeoutHookGo) + wg.Wait() + checkErr(err1) + checkErr(err2) + + // Double lookup with context. + timeoutHookGo = make(chan bool) + ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) + wg.Add(2) + go func() { + defer wg.Done() + _, err1 = DefaultResolver.LookupIPAddr(ctx, "golang2.org") + }() + go func() { + defer wg.Done() + _, err2 = DefaultResolver.LookupIPAddr(ctx, "golang2.org") + }() + time.Sleep(10 * time.Nanosecond) + close(timeoutHookGo) + wg.Wait() + checkErr(err1) + checkErr(err2) + cancel() +} + +func TestLookupNoData(t *testing.T) { + if runtime.GOOS == "plan9" { + t.Skip("not supported on plan9") + } + + mustHaveExternalNetwork(t) + + testLookupNoData(t, "default resolver") + + func() { + defer forceGoDNS()() + testLookupNoData(t, "forced go resolver") + }() + + func() { + defer forceCgoDNS()() + testLookupNoData(t, "forced cgo resolver") + }() +} + +func testLookupNoData(t *testing.T, prefix string) { + attempts := 0 + for { + // Domain that doesn't have any A/AAAA RRs, but has different one (in this case a TXT), + // so that it returns an empty response without any error codes (NXDOMAIN). + _, err := LookupHost("golang.rsc.io.") + if err == nil { + t.Errorf("%v: unexpected success", prefix) + return + } + + dnsErr, ok := errors.AsType[*DNSError](err) + if ok { + succeeded := true + if !dnsErr.IsNotFound { + succeeded = false + t.Logf("%v: IsNotFound is set to false", prefix) + } + + if dnsErr.Err != errNoSuchHost.Error() { + succeeded = false + t.Logf("%v: error message is not equal to: %v", prefix, errNoSuchHost.Error()) + } + + if succeeded { + return + } + } + + testenv.SkipFlakyNet(t) + if attempts < len(backoffDuration) { + dur := backoffDuration[attempts] + t.Logf("%v: backoff %v after failure %v\n", prefix, dur, err) + time.Sleep(dur) + attempts++ + continue + } + + t.Errorf("%v: unexpected error: %v", prefix, err) + return + } +} + +func TestLookupPortNotFound(t *testing.T) { + allResolvers(t, func(t *testing.T) { + _, err := LookupPort("udp", "_-unknown-service-") + if dnsErr, ok := errors.AsType[*DNSError](err); !ok || !dnsErr.IsNotFound { + t.Fatalf("unexpected error: %v", err) + } + }) +} + +// submissions service is only available through a tcp network, see: +// https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=submissions +var tcpOnlyService = func() string { + // plan9 does not have submissions service defined in the service database. + if runtime.GOOS == "plan9" { + return "https" + } + return "submissions" +}() + +func TestLookupPortDifferentNetwork(t *testing.T) { + allResolvers(t, func(t *testing.T) { + _, err := LookupPort("udp", tcpOnlyService) + if dnsErr, ok := errors.AsType[*DNSError](err); !ok || !dnsErr.IsNotFound { + t.Fatalf("unexpected error: %v", err) + } + }) +} + +func TestLookupPortEmptyNetworkString(t *testing.T) { + allResolvers(t, func(t *testing.T) { + _, err := LookupPort("", tcpOnlyService) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) +} + +func TestLookupPortIPNetworkString(t *testing.T) { + allResolvers(t, func(t *testing.T) { + _, err := LookupPort("ip", tcpOnlyService) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) +} + +func TestLookupNoSuchHost(t *testing.T) { + mustHaveExternalNetwork(t) + + const testNXDOMAIN = "invalid.invalid." + const testNODATA = "_ldap._tcp.google.com." + + tests := []struct { + name string + query func() error + }{ + { + name: "LookupCNAME NXDOMAIN", + query: func() error { + _, err := LookupCNAME(testNXDOMAIN) + return err + }, + }, + { + name: "LookupHost NXDOMAIN", + query: func() error { + _, err := LookupHost(testNXDOMAIN) + return err + }, + }, + { + name: "LookupHost NODATA", + query: func() error { + _, err := LookupHost(testNODATA) + return err + }, + }, + { + name: "LookupMX NXDOMAIN", + query: func() error { + _, err := LookupMX(testNXDOMAIN) + return err + }, + }, + { + name: "LookupMX NODATA", + query: func() error { + _, err := LookupMX(testNODATA) + return err + }, + }, + { + name: "LookupNS NXDOMAIN", + query: func() error { + _, err := LookupNS(testNXDOMAIN) + return err + }, + }, + { + name: "LookupNS NODATA", + query: func() error { + _, err := LookupNS(testNODATA) + return err + }, + }, + { + name: "LookupSRV NXDOMAIN", + query: func() error { + _, _, err := LookupSRV("unknown", "tcp", testNXDOMAIN) + return err + }, + }, + { + name: "LookupTXT NXDOMAIN", + query: func() error { + _, err := LookupTXT(testNXDOMAIN) + return err + }, + }, + { + name: "LookupTXT NODATA", + query: func() error { + _, err := LookupTXT(testNODATA) + return err + }, + }, + } + + for _, v := range tests { + t.Run(v.name, func(t *testing.T) { + allResolvers(t, func(t *testing.T) { + attempts := 0 + for { + err := v.query() + if err == nil { + t.Errorf("unexpected success") + return + } + if dnsErr, ok := err.(*DNSError); ok { + succeeded := true + if !dnsErr.IsNotFound { + succeeded = false + t.Log("IsNotFound is set to false") + } + if dnsErr.Err != errNoSuchHost.Error() { + succeeded = false + t.Logf("error message is not equal to: %v", errNoSuchHost.Error()) + } + if succeeded { + return + } + } + testenv.SkipFlakyNet(t) + if attempts < len(backoffDuration) { + dur := backoffDuration[attempts] + t.Logf("backoff %v after failure %v\n", dur, err) + time.Sleep(dur) + attempts++ + continue + } + t.Errorf("unexpected error: %v", err) + return + } + }) + }) + } +} + +func TestDNSErrorUnwrap(t *testing.T) { + if runtime.GOOS == "plan9" { + // The Plan 9 implementation of the resolver doesn't use the Dial function yet. See https://go.dev/cl/409234 + t.Skip("skipping on plan9") + } + rDeadlineExcceeded := &Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (Conn, error) { + return nil, context.DeadlineExceeded + }} + rCancelled := &Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (Conn, error) { + return nil, context.Canceled + }} + + _, err := rDeadlineExcceeded.LookupHost(context.Background(), "test.go.dev") + if !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("errors.Is(err, context.DeadlineExceeded) = false; want = true") + } + + _, err = rCancelled.LookupHost(context.Background(), "test.go.dev") + if !errors.Is(err, context.Canceled) { + t.Errorf("errors.Is(err, context.Canceled) = false; want = true") + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err = goResolver.LookupHost(ctx, "text.go.dev") + if !errors.Is(err, context.Canceled) { + t.Errorf("errors.Is(err, context.Canceled) = false; want = true") + } +} diff --git a/go/src/net/lookup_unix.go b/go/src/net/lookup_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..86108939cd03d61dc5a52fb212dcc4508e7f89f6 --- /dev/null +++ b/go/src/net/lookup_unix.go @@ -0,0 +1,119 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 + +package net + +import ( + "context" + "internal/bytealg" + "sync" +) + +// readProtocolsOnce loads contents of /etc/protocols into protocols map +// for quick access. +var readProtocolsOnce = sync.OnceFunc(func() { + file, err := open("/etc/protocols") + if err != nil { + return + } + defer file.close() + + for line, ok := file.readLine(); ok; line, ok = file.readLine() { + // tcp 6 TCP # transmission control protocol + if i := bytealg.IndexByteString(line, '#'); i >= 0 { + line = line[0:i] + } + f := getFields(line) + if len(f) < 2 { + continue + } + if proto, _, ok := dtoi(f[1]); ok { + if _, ok := protocols[f[0]]; !ok { + protocols[f[0]] = proto + } + for _, alias := range f[2:] { + if _, ok := protocols[alias]; !ok { + protocols[alias] = proto + } + } + } + } +}) + +// lookupProtocol looks up IP protocol name in /etc/protocols and +// returns correspondent protocol number. +func lookupProtocol(_ context.Context, name string) (int, error) { + readProtocolsOnce() + return lookupProtocolMap(name) +} + +func (r *Resolver) lookupHost(ctx context.Context, host string) (addrs []string, err error) { + order, conf := systemConf().hostLookupOrder(r, host) + if order == hostLookupCgo { + return cgoLookupHost(ctx, host) + } + return r.goLookupHostOrder(ctx, host, order, conf) +} + +func (r *Resolver) lookupIP(ctx context.Context, network, host string) (addrs []IPAddr, err error) { + order, conf := systemConf().hostLookupOrder(r, host) + if order == hostLookupCgo { + return cgoLookupIP(ctx, network, host) + } + ips, _, err := r.goLookupIPCNAMEOrder(ctx, network, host, order, conf) + return ips, err +} + +func (r *Resolver) lookupPort(ctx context.Context, network, service string) (int, error) { + // Port lookup is not a DNS operation. + // Prefer the cgo resolver if possible. + if !systemConf().mustUseGoResolver(r) { + port, err := cgoLookupPort(ctx, network, service) + if err != nil { + // Issue 18213: if cgo fails, first check to see whether we + // have the answer baked-in to the net package. + if port, err := goLookupPort(network, service); err == nil { + return port, nil + } + } + return port, err + } + return goLookupPort(network, service) +} + +func (r *Resolver) lookupCNAME(ctx context.Context, name string) (string, error) { + order, conf := systemConf().hostLookupOrder(r, name) + if order == hostLookupCgo { + if cname, err := cgoLookupCNAME(ctx, name); err == nil { + return cname, nil + } + } + return r.goLookupCNAME(ctx, name, order, conf) +} + +func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) { + return r.goLookupSRV(ctx, service, proto, name) +} + +func (r *Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error) { + return r.goLookupMX(ctx, name) +} + +func (r *Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error) { + return r.goLookupNS(ctx, name) +} + +func (r *Resolver) lookupTXT(ctx context.Context, name string) ([]string, error) { + return r.goLookupTXT(ctx, name) +} + +func (r *Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error) { + order, conf := systemConf().addrLookupOrder(r, addr) + if order == hostLookupCgo { + return cgoLookupPTR(ctx, addr) + } + return r.goLookupPTR(ctx, addr, order, conf) +} diff --git a/go/src/net/lookup_windows.go b/go/src/net/lookup_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..9af20bbb2bc1b008fb84b04e70fbfc4b23062b88 --- /dev/null +++ b/go/src/net/lookup_windows.go @@ -0,0 +1,479 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "internal/syscall/windows" + "os" + "runtime" + "syscall" + "time" + "unsafe" +) + +// cgoAvailable set to true to indicate that the cgo resolver +// is available on Windows. Note that on Windows the cgo resolver +// does not actually use cgo. +const cgoAvailable = true + +const ( + _DNS_ERROR_RCODE_NAME_ERROR = syscall.Errno(9003) + _DNS_INFO_NO_RECORDS = syscall.Errno(9501) + + _WSAHOST_NOT_FOUND = syscall.Errno(11001) + _WSATRY_AGAIN = syscall.Errno(11002) + _WSATYPE_NOT_FOUND = syscall.Errno(10109) +) + +func winError(call string, err error) error { + switch err { + case _WSAHOST_NOT_FOUND, _DNS_ERROR_RCODE_NAME_ERROR, _DNS_INFO_NO_RECORDS: + return errNoSuchHost + } + return os.NewSyscallError(call, err) +} + +func getprotobyname(name string) (proto int, err error) { + p, err := syscall.GetProtoByName(name) + if err != nil { + return 0, winError("getprotobyname", err) + } + return int(p.Proto), nil +} + +// lookupProtocol looks up IP protocol name and returns correspondent protocol number. +func lookupProtocol(ctx context.Context, name string) (int, error) { + // GetProtoByName return value is stored in thread local storage. + // Start new os thread before the call to prevent races. + type result struct { + proto int + err error + } + ch := make(chan result, 1) // buffer so that next goroutine never blocks + go func() { + if err := acquireThread(ctx); err != nil { + ch <- result{err: mapErr(err)} + return + } + defer releaseThread() + runtime.LockOSThread() + defer runtime.UnlockOSThread() + proto, err := getprotobyname(name) + ch <- result{proto: proto, err: err} + }() + select { + case r := <-ch: + if r.err != nil { + if proto, err := lookupProtocolMap(name); err == nil { + return proto, nil + } + r.err = newDNSError(r.err, name, "") + } + return r.proto, r.err + case <-ctx.Done(): + return 0, newDNSError(mapErr(ctx.Err()), name, "") + } +} + +func (r *Resolver) lookupHost(ctx context.Context, name string) ([]string, error) { + ips, err := r.lookupIP(ctx, "ip", name) + if err != nil { + return nil, err + } + addrs := make([]string, 0, len(ips)) + for _, ip := range ips { + addrs = append(addrs, ip.String()) + } + return addrs, nil +} + +func (r *Resolver) lookupIP(ctx context.Context, network, name string) ([]IPAddr, error) { + if order, conf := systemConf().hostLookupOrder(r, name); order != hostLookupCgo { + return r.goLookupIP(ctx, network, name, order, conf) + } + + // TODO(bradfitz,brainman): use ctx more. See TODO below. + + var family int32 = syscall.AF_UNSPEC + switch ipVersion(network) { + case '4': + family = syscall.AF_INET + case '6': + family = syscall.AF_INET6 + } + + getaddr := func() ([]IPAddr, error) { + if err := acquireThread(ctx); err != nil { + return nil, newDNSError(mapErr(err), name, "") + } + defer releaseThread() + hints := syscall.AddrinfoW{ + Family: family, + Socktype: syscall.SOCK_STREAM, + Protocol: syscall.IPPROTO_IP, + } + var result *syscall.AddrinfoW + name16p, err := syscall.UTF16PtrFromString(name) + if err != nil { + return nil, newDNSError(err, name, "") + } + + dnsConf := getSystemDNSConfig() + start := time.Now() + + var e error + for i := 0; i < dnsConf.attempts; i++ { + e = syscall.GetAddrInfoW(name16p, nil, &hints, &result) + if e == nil || e != _WSATRY_AGAIN || time.Since(start) > dnsConf.timeout { + break + } + } + if e != nil { + return nil, newDNSError(winError("getaddrinfow", e), name, "") + } + defer syscall.FreeAddrInfoW(result) + addrs := make([]IPAddr, 0, 5) + for ; result != nil; result = result.Next { + addr := unsafe.Pointer(result.Addr) + switch result.Family { + case syscall.AF_INET: + a := (*syscall.RawSockaddrInet4)(addr).Addr + addrs = append(addrs, IPAddr{IP: copyIP(a[:])}) + case syscall.AF_INET6: + a := (*syscall.RawSockaddrInet6)(addr).Addr + zone := zoneCache.name(int((*syscall.RawSockaddrInet6)(addr).Scope_id)) + addrs = append(addrs, IPAddr{IP: copyIP(a[:]), Zone: zone}) + default: + return nil, newDNSError(syscall.EWINDOWS, name, "") + } + } + return addrs, nil + } + + type ret struct { + addrs []IPAddr + err error + } + + var ch chan ret + if ctx.Err() == nil { + ch = make(chan ret, 1) + go func() { + addr, err := getaddr() + ch <- ret{addrs: addr, err: err} + }() + } + + select { + case r := <-ch: + return r.addrs, r.err + case <-ctx.Done(): + // TODO(bradfitz,brainman): cancel the ongoing + // GetAddrInfoW? It would require conditionally using + // GetAddrInfoEx with lpOverlapped, which requires + // Windows 8 or newer. I guess we'll need oldLookupIP, + // newLookupIP, and newerLookUP. + // + // For now we just let it finish and write to the + // buffered channel. + return nil, newDNSError(mapErr(ctx.Err()), name, "") + } +} + +func (r *Resolver) lookupPort(ctx context.Context, network, service string) (int, error) { + if systemConf().mustUseGoResolver(r) { + return lookupPortMap(network, service) + } + + // TODO(bradfitz): finish ctx plumbing + if err := acquireThread(ctx); err != nil { + return 0, newDNSError(mapErr(err), network+"/"+service, "") + } + defer releaseThread() + + var hints syscall.AddrinfoW + + switch network { + case "ip": // no hints + case "tcp", "tcp4", "tcp6": + hints.Socktype = syscall.SOCK_STREAM + hints.Protocol = syscall.IPPROTO_TCP + case "udp", "udp4", "udp6": + hints.Socktype = syscall.SOCK_DGRAM + hints.Protocol = syscall.IPPROTO_UDP + default: + return 0, &DNSError{Err: "unknown network", Name: network + "/" + service} + } + + switch ipVersion(network) { + case '4': + hints.Family = syscall.AF_INET + case '6': + hints.Family = syscall.AF_INET6 + } + + servicep, err := syscall.UTF16PtrFromString(service) + if err != nil { + return 0, newDNSError(err, network+"/"+service, "") + } + + var result *syscall.AddrinfoW + e := syscall.GetAddrInfoW(nil, servicep, &hints, &result) + if e != nil { + if port, err := lookupPortMap(network, service); err == nil { + return port, nil + } + + // The _WSATYPE_NOT_FOUND error is returned by GetAddrInfoW + // when the service name is unknown. We are also checking + // for _WSAHOST_NOT_FOUND here to match the cgo (unix) version + // cgo_unix.go (cgoLookupServicePort). + if e == _WSATYPE_NOT_FOUND || e == _WSAHOST_NOT_FOUND { + return 0, newDNSError(errUnknownPort, network+"/"+service, "") + } + return 0, newDNSError(winError("getaddrinfow", e), network+"/"+service, "") + } + defer syscall.FreeAddrInfoW(result) + if result == nil { + return 0, newDNSError(syscall.EINVAL, network+"/"+service, "") + } + addr := unsafe.Pointer(result.Addr) + switch result.Family { + case syscall.AF_INET: + a := (*syscall.RawSockaddrInet4)(addr) + return int(syscall.Ntohs(a.Port)), nil + case syscall.AF_INET6: + a := (*syscall.RawSockaddrInet6)(addr) + return int(syscall.Ntohs(a.Port)), nil + } + return 0, newDNSError(syscall.EINVAL, network+"/"+service, "") +} + +func (r *Resolver) lookupCNAME(ctx context.Context, name string) (string, error) { + if order, conf := systemConf().hostLookupOrder(r, name); order != hostLookupCgo { + return r.goLookupCNAME(ctx, name, order, conf) + } + + // TODO(bradfitz): finish ctx plumbing + if err := acquireThread(ctx); err != nil { + return "", newDNSError(mapErr(err), name, "") + } + defer releaseThread() + var rec *syscall.DNSRecord + e := syscall.DnsQuery(name, syscall.DNS_TYPE_CNAME, 0, nil, &rec, nil) + // windows returns DNS_INFO_NO_RECORDS if there are no CNAME-s + if errno, ok := e.(syscall.Errno); ok && errno == syscall.DNS_INFO_NO_RECORDS { + // if there are no aliases, the canonical name is the input name + return absDomainName(name), nil + } + if e != nil { + return "", newDNSError(winError("dnsquery", e), name, "") + } + defer syscall.DnsRecordListFree(rec, 1) + + namep, err := syscall.UTF16PtrFromString(name) + if err != nil { + return "", newDNSError(err, name, "") + } + + resolved := resolveCNAME(namep, rec) + cname := windows.UTF16PtrToString(resolved) + return absDomainName(cname), nil +} + +func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupSRV(ctx, service, proto, name) + } + // TODO(bradfitz): finish ctx plumbing + if err := acquireThread(ctx); err != nil { + return "", nil, newDNSError(mapErr(err), name, "") + } + defer releaseThread() + var target string + if service == "" && proto == "" { + target = name + } else { + target = "_" + service + "._" + proto + "." + name + } + var rec *syscall.DNSRecord + e := syscall.DnsQuery(target, syscall.DNS_TYPE_SRV, 0, nil, &rec, nil) + if e != nil { + return "", nil, newDNSError(winError("dnsquery", e), name, "") + } + defer syscall.DnsRecordListFree(rec, 1) + + srvs := make([]*SRV, 0, 10) + for _, p := range validRecs(rec, syscall.DNS_TYPE_SRV, target) { + v := (*syscall.DNSSRVData)(unsafe.Pointer(&p.Data[0])) + srvs = append(srvs, &SRV{absDomainName(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.Target))[:])), v.Port, v.Priority, v.Weight}) + } + byPriorityWeight(srvs).sort() + return absDomainName(target), srvs, nil +} + +func (r *Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupMX(ctx, name) + } + // TODO(bradfitz): finish ctx plumbing. + if err := acquireThread(ctx); err != nil { + return nil, newDNSError(mapErr(err), name, "") + } + defer releaseThread() + var rec *syscall.DNSRecord + e := syscall.DnsQuery(name, syscall.DNS_TYPE_MX, 0, nil, &rec, nil) + if e != nil { + return nil, newDNSError(winError("dnsquery", e), name, "") + } + defer syscall.DnsRecordListFree(rec, 1) + + mxs := make([]*MX, 0, 10) + for _, p := range validRecs(rec, syscall.DNS_TYPE_MX, name) { + v := (*syscall.DNSMXData)(unsafe.Pointer(&p.Data[0])) + mxs = append(mxs, &MX{absDomainName(windows.UTF16PtrToString(v.NameExchange)), v.Preference}) + } + byPref(mxs).sort() + return mxs, nil +} + +func (r *Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupNS(ctx, name) + } + // TODO(bradfitz): finish ctx plumbing. + if err := acquireThread(ctx); err != nil { + return nil, newDNSError(mapErr(err), name, "") + } + defer releaseThread() + var rec *syscall.DNSRecord + e := syscall.DnsQuery(name, syscall.DNS_TYPE_NS, 0, nil, &rec, nil) + if e != nil { + return nil, newDNSError(winError("dnsquery", e), name, "") + } + defer syscall.DnsRecordListFree(rec, 1) + + nss := make([]*NS, 0, 10) + for _, p := range validRecs(rec, syscall.DNS_TYPE_NS, name) { + v := (*syscall.DNSPTRData)(unsafe.Pointer(&p.Data[0])) + nss = append(nss, &NS{absDomainName(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.Host))[:]))}) + } + return nss, nil +} + +func (r *Resolver) lookupTXT(ctx context.Context, name string) ([]string, error) { + if systemConf().mustUseGoResolver(r) { + return r.goLookupTXT(ctx, name) + } + // TODO(bradfitz): finish ctx plumbing. + if err := acquireThread(ctx); err != nil { + return nil, newDNSError(mapErr(err), name, "") + } + defer releaseThread() + var rec *syscall.DNSRecord + e := syscall.DnsQuery(name, syscall.DNS_TYPE_TEXT, 0, nil, &rec, nil) + if e != nil { + return nil, newDNSError(winError("dnsquery", e), name, "") + } + defer syscall.DnsRecordListFree(rec, 1) + + txts := make([]string, 0, 10) + for _, p := range validRecs(rec, syscall.DNS_TYPE_TEXT, name) { + d := (*syscall.DNSTXTData)(unsafe.Pointer(&p.Data[0])) + s := "" + for _, v := range (*[1 << 10]*uint16)(unsafe.Pointer(&(d.StringArray[0])))[:d.StringCount:d.StringCount] { + s += windows.UTF16PtrToString(v) + } + txts = append(txts, s) + } + return txts, nil +} + +func (r *Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error) { + if order, conf := systemConf().addrLookupOrder(r, addr); order != hostLookupCgo { + return r.goLookupPTR(ctx, addr, order, conf) + } + + // TODO(bradfitz): finish ctx plumbing. + if err := acquireThread(ctx); err != nil { + return nil, newDNSError(mapErr(err), addr, "") + } + defer releaseThread() + arpa, err := reverseaddr(addr) + if err != nil { + return nil, err + } + var rec *syscall.DNSRecord + e := syscall.DnsQuery(arpa, syscall.DNS_TYPE_PTR, 0, nil, &rec, nil) + if e != nil { + return nil, newDNSError(winError("dnsquery", e), addr, "") + } + defer syscall.DnsRecordListFree(rec, 1) + + ptrs := make([]string, 0, 10) + for _, p := range validRecs(rec, syscall.DNS_TYPE_PTR, arpa) { + v := (*syscall.DNSPTRData)(unsafe.Pointer(&p.Data[0])) + ptrs = append(ptrs, absDomainName(windows.UTF16PtrToString(v.Host))) + } + return ptrs, nil +} + +const dnsSectionMask = 0x0003 + +// returns only results applicable to name and resolves CNAME entries. +func validRecs(r *syscall.DNSRecord, dnstype uint16, name string) []*syscall.DNSRecord { + cname, err := syscall.UTF16PtrFromString(name) + if err != nil { + return nil + } + if dnstype != syscall.DNS_TYPE_CNAME { + cname = resolveCNAME(cname, r) + } + rec := make([]*syscall.DNSRecord, 0, 10) + for p := r; p != nil; p = p.Next { + // in case of a local machine, DNS records are returned with DNSREC_QUESTION flag instead of DNS_ANSWER + if p.Dw&dnsSectionMask != syscall.DnsSectionAnswer && p.Dw&dnsSectionMask != syscall.DnsSectionQuestion { + continue + } + if p.Type != dnstype { + continue + } + if !syscall.DnsNameCompare(cname, p.Name) { + continue + } + rec = append(rec, p) + } + return rec +} + +// returns the last CNAME in chain. +func resolveCNAME(name *uint16, r *syscall.DNSRecord) *uint16 { + // limit cname resolving to 10 in case of an infinite CNAME loop +Cname: + for cnameloop := 0; cnameloop < 10; cnameloop++ { + for p := r; p != nil; p = p.Next { + if p.Dw&dnsSectionMask != syscall.DnsSectionAnswer { + continue + } + if p.Type != syscall.DNS_TYPE_CNAME { + continue + } + if !syscall.DnsNameCompare(name, p.Name) { + continue + } + name = (*syscall.DNSPTRData)(unsafe.Pointer(&r.Data[0])).Host + continue Cname + } + break + } + return name +} + +// concurrentThreadsLimit returns the number of threads we permit to +// run concurrently doing DNS lookups. +func concurrentThreadsLimit() int { + return 500 +} diff --git a/go/src/net/lookup_windows_test.go b/go/src/net/lookup_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..bee1a6150c30d479867401c813574eab082ee6dc --- /dev/null +++ b/go/src/net/lookup_windows_test.go @@ -0,0 +1,331 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "internal/testenv" + "os/exec" + "reflect" + "regexp" + "slices" + "strings" + "syscall" + "testing" +) + +var nslookupTestServers = []string{"mail.golang.com", "gmail.com"} +var lookupTestIPs = []string{"8.8.8.8", "1.1.1.1"} + +func toJson(v any) string { + data, _ := json.Marshal(v) + return string(data) +} + +func testLookup(t *testing.T, fn func(*testing.T, *Resolver, string)) { + for _, def := range []bool{true, false} { + for _, server := range nslookupTestServers { + var name string + if def { + name = "default/" + } else { + name = "go/" + } + t.Run(name+server, func(t *testing.T) { + t.Parallel() + r := DefaultResolver + if !def { + r = &Resolver{PreferGo: true} + } + fn(t, r, server) + }) + } + } +} + +func TestNSLookupMX(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + testLookup(t, func(t *testing.T, r *Resolver, server string) { + mx, err := r.LookupMX(context.Background(), server) + if err != nil { + t.Fatal(err) + } + if len(mx) == 0 { + t.Fatal("no results") + } + expected, err := nslookupMX(server) + if err != nil { + t.Skipf("skipping failed nslookup %s test: %s", server, err) + } + byPrefAndHost := func(a, b *MX) int { + if r := cmp.Compare(a.Pref, b.Pref); r != 0 { + return r + } + return strings.Compare(a.Host, b.Host) + } + slices.SortFunc(expected, byPrefAndHost) + slices.SortFunc(mx, byPrefAndHost) + if !reflect.DeepEqual(expected, mx) { + t.Errorf("different results %s:\texp:%v\tgot:%v", server, toJson(expected), toJson(mx)) + } + }) +} + +func TestNSLookupCNAME(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + testLookup(t, func(t *testing.T, r *Resolver, server string) { + cname, err := r.LookupCNAME(context.Background(), server) + if err != nil { + t.Fatalf("failed %s: %s", server, err) + } + if cname == "" { + t.Fatalf("no result %s", server) + } + expected, err := nslookupCNAME(server) + if err != nil { + t.Skipf("skipping failed nslookup %s test: %s", server, err) + } + if expected != cname { + t.Errorf("different results %s:\texp:%v\tgot:%v", server, expected, cname) + } + }) +} + +func TestNSLookupNS(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + testLookup(t, func(t *testing.T, r *Resolver, server string) { + ns, err := r.LookupNS(context.Background(), server) + if err != nil { + t.Fatalf("failed %s: %s", server, err) + } + if len(ns) == 0 { + t.Fatal("no results") + } + expected, err := nslookupNS(server) + if err != nil { + t.Skipf("skipping failed nslookup %s test: %s", server, err) + } + byHost := func(a, b *NS) int { + return strings.Compare(a.Host, b.Host) + } + slices.SortFunc(expected, byHost) + slices.SortFunc(ns, byHost) + if !reflect.DeepEqual(expected, ns) { + t.Errorf("different results %s:\texp:%v\tgot:%v", toJson(server), toJson(expected), ns) + } + }) +} + +func TestNSLookupTXT(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + testLookup(t, func(t *testing.T, r *Resolver, server string) { + txt, err := r.LookupTXT(context.Background(), server) + if err != nil { + t.Fatalf("failed %s: %s", server, err) + } + if len(txt) == 0 { + t.Fatalf("no results") + } + expected, err := nslookupTXT(server) + if err != nil { + t.Skipf("skipping failed nslookup %s test: %s", server, err) + } + slices.Sort(expected) + slices.Sort(txt) + if !slices.Equal(expected, txt) { + t.Errorf("different results %s:\texp:%v\tgot:%v", server, toJson(expected), toJson(txt)) + } + }) +} + +func TestLookupLocalPTR(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + addr, err := localIP() + if err != nil { + t.Errorf("failed to get local ip: %s", err) + } + names, err := LookupAddr(addr.String()) + if err != nil { + t.Errorf("failed %s: %s", addr, err) + } + if len(names) == 0 { + t.Errorf("no results") + } + expected, err := lookupPTR(addr.String()) + if err != nil { + t.Skipf("skipping failed lookup %s test: %s", addr.String(), err) + } + slices.Sort(expected) + slices.Sort(names) + if !slices.Equal(expected, names) { + t.Errorf("different results %s:\texp:%v\tgot:%v", addr, toJson(expected), toJson(names)) + } +} + +func TestLookupPTR(t *testing.T) { + testenv.MustHaveExternalNetwork(t) + + for _, addr := range lookupTestIPs { + names, err := LookupAddr(addr) + if err != nil { + // The DNSError type stores the error as a string, so it cannot wrap the + // original error code and we cannot check for it here. However, we can at + // least use its error string to identify the correct localized text for + // the error to skip. + var DNS_ERROR_RCODE_SERVER_FAILURE syscall.Errno = 9002 + if strings.HasSuffix(err.Error(), DNS_ERROR_RCODE_SERVER_FAILURE.Error()) { + testenv.SkipFlaky(t, 38111) + } + t.Errorf("failed %s: %s", addr, err) + } + if len(names) == 0 { + t.Errorf("no results") + } + expected, err := lookupPTR(addr) + if err != nil { + t.Logf("skipping failed lookup %s test: %s", addr, err) + continue + } + slices.Sort(expected) + slices.Sort(names) + if !slices.Equal(expected, names) { + t.Errorf("different results %s:\texp:%v\tgot:%v", addr, toJson(expected), toJson(names)) + } + } +} + +func nslookup(qtype, name string) (string, error) { + var out strings.Builder + var err strings.Builder + cmd := exec.Command("nslookup", "-querytype="+qtype, name) + cmd.Stdout = &out + cmd.Stderr = &err + if err := cmd.Run(); err != nil { + return "", err + } + r := strings.ReplaceAll(out.String(), "\r\n", "\n") + // nslookup stderr output contains also debug information such as + // "Non-authoritative answer" and it doesn't return the correct errcode + if strings.Contains(err.String(), "can't find") { + return r, errors.New(err.String()) + } + return r, nil +} + +func nslookupMX(name string) (mx []*MX, err error) { + var r string + if r, err = nslookup("mx", name); err != nil { + return + } + mx = make([]*MX, 0, 10) + // linux nslookup syntax + // golang.org mail exchanger = 2 alt1.aspmx.l.google.com. + rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+mail exchanger\s*=\s*([0-9]+)\s*([a-z0-9.\-]+)$`) + for _, ans := range rx.FindAllStringSubmatch(r, -1) { + pref, _, _ := dtoi(ans[2]) + mx = append(mx, &MX{absDomainName(ans[3]), uint16(pref)}) + } + // windows nslookup syntax + // gmail.com MX preference = 30, mail exchanger = alt3.gmail-smtp-in.l.google.com + rx = regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+MX preference\s*=\s*([0-9]+)\s*,\s*mail exchanger\s*=\s*([a-z0-9.\-]+)$`) + for _, ans := range rx.FindAllStringSubmatch(r, -1) { + pref, _, _ := dtoi(ans[2]) + mx = append(mx, &MX{absDomainName(ans[3]), uint16(pref)}) + } + return +} + +func nslookupNS(name string) (ns []*NS, err error) { + var r string + if r, err = nslookup("ns", name); err != nil { + return + } + ns = make([]*NS, 0, 10) + // golang.org nameserver = ns1.google.com. + rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+nameserver\s*=\s*([a-z0-9.\-]+)$`) + for _, ans := range rx.FindAllStringSubmatch(r, -1) { + ns = append(ns, &NS{absDomainName(ans[2])}) + } + return +} + +func nslookupCNAME(name string) (cname string, err error) { + var r string + if r, err = nslookup("cname", name); err != nil { + return + } + // mail.golang.com canonical name = golang.org. + rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+canonical name\s*=\s*([a-z0-9.\-]+)$`) + // assumes the last CNAME is the correct one + last := name + for _, ans := range rx.FindAllStringSubmatch(r, -1) { + last = ans[2] + } + return absDomainName(last), nil +} + +func nslookupTXT(name string) (txt []string, err error) { + var r string + if r, err = nslookup("txt", name); err != nil { + return + } + txt = make([]string, 0, 10) + // linux + // golang.org text = "v=spf1 redirect=_spf.google.com" + + // windows + // golang.org text = + // + // "v=spf1 redirect=_spf.google.com" + rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+text\s*=\s*"(.*)"$`) + for _, ans := range rx.FindAllStringSubmatch(r, -1) { + txt = append(txt, ans[2]) + } + return +} + +func ping(name string) (string, error) { + cmd := exec.Command("ping", "-n", "1", "-a", name) + stdoutStderr, err := cmd.CombinedOutput() + if err != nil { + return "", fmt.Errorf("%v: %v", err, string(stdoutStderr)) + } + r := strings.ReplaceAll(string(stdoutStderr), "\r\n", "\n") + return r, nil +} + +func lookupPTR(name string) (ptr []string, err error) { + var r string + if r, err = ping(name); err != nil { + return + } + ptr = make([]string, 0, 10) + rx := regexp.MustCompile(`(?m)^Pinging\s+([a-zA-Z0-9.\-]+)\s+\[.*$`) + for _, ans := range rx.FindAllStringSubmatch(r, -1) { + ptr = append(ptr, absDomainName(ans[1])) + } + return +} + +func localIP() (ip IP, err error) { + conn, err := Dial("udp", "golang.org:80") + if err != nil { + return nil, err + } + defer conn.Close() + + localAddr := conn.LocalAddr().(*UDPAddr) + + return localAddr.IP, nil +} diff --git a/go/src/net/mac.go b/go/src/net/mac.go new file mode 100644 index 0000000000000000000000000000000000000000..b69a42d40b949d450bf1bc2c3b68c38f5ff00be7 --- /dev/null +++ b/go/src/net/mac.go @@ -0,0 +1,103 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +const hexDigit = "0123456789abcdef" + +// A HardwareAddr represents a physical hardware address. +type HardwareAddr []byte + +func (a HardwareAddr) String() string { + if len(a) == 0 { + return "" + } + buf := make([]byte, 0, len(a)*3-1) + for i, b := range a { + if i > 0 { + buf = append(buf, ':') + } + buf = append(buf, hexDigit[b>>4]) + buf = append(buf, hexDigit[b&0xF]) + } + return string(buf) +} + +// ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet +// IP over InfiniBand link-layer address using one of the following formats: +// +// 00:00:5e:00:53:01 +// 02:00:5e:10:00:00:00:01 +// 00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01 +// 00-00-5e-00-53-01 +// 02-00-5e-10-00-00-00-01 +// 00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01 +// 0000.5e00.5301 +// 0200.5e10.0000.0001 +// 0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001 +// 00005e005301 +func ParseMAC(s string) (hw HardwareAddr, err error) { + if len(s) < 12 { + goto error + } + + if s[2] == ':' || s[2] == '-' { + if (len(s)+1)%3 != 0 { + goto error + } + n := (len(s) + 1) / 3 + if n != 6 && n != 8 && n != 20 { + goto error + } + hw = make(HardwareAddr, n) + for x, i := 0, 0; i < n; i++ { + var ok bool + if hw[i], ok = xtoi2(s[x:], s[2]); !ok { + goto error + } + x += 3 + } + } else if s[4] == '.' { + if (len(s)+1)%5 != 0 { + goto error + } + n := 2 * (len(s) + 1) / 5 + if n != 6 && n != 8 && n != 20 { + goto error + } + hw = make(HardwareAddr, n) + for x, i := 0, 0; i < n; i += 2 { + var ok bool + if hw[i], ok = xtoi2(s[x:x+2], 0); !ok { + goto error + } + if hw[i+1], ok = xtoi2(s[x+2:], s[4]); !ok { + goto error + } + x += 5 + } + } else { + if len(s)%2 != 0 { + goto error + } + + n := len(s) / 2 + if n != 6 && n != 8 && n != 20 { + goto error + } + + hw = make(HardwareAddr, len(s)/2) + for x, i := 0, 0; i < n; i++ { + var ok bool + if hw[i], ok = xtoi2(s[x:x+2], 0); !ok { + goto error + } + x += 2 + } + } + return hw, nil + +error: + return nil, &AddrError{Err: "invalid MAC address", Addr: s} +} diff --git a/go/src/net/mac_test.go b/go/src/net/mac_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9bfad4f12e806f0c003b6192a67859c09d930a72 --- /dev/null +++ b/go/src/net/mac_test.go @@ -0,0 +1,121 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "reflect" + "strings" + "testing" +) + +var parseMACTests = []struct { + in string + out HardwareAddr + err string +}{ + // See RFC 7042, Section 2.1.1. + {"00:00:5e:00:53:01", HardwareAddr{0x00, 0x00, 0x5e, 0x00, 0x53, 0x01}, ""}, + {"00-00-5e-00-53-01", HardwareAddr{0x00, 0x00, 0x5e, 0x00, 0x53, 0x01}, ""}, + {"0000.5e00.5301", HardwareAddr{0x00, 0x00, 0x5e, 0x00, 0x53, 0x01}, ""}, + {"00005e005301", HardwareAddr{0x00, 0x00, 0x5e, 0x00, 0x53, 0x01}, ""}, + + // See RFC 7042, Section 2.2.2. + {"02:00:5e:10:00:00:00:01", HardwareAddr{0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01}, ""}, + {"02-00-5e-10-00-00-00-01", HardwareAddr{0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01}, ""}, + {"0200.5e10.0000.0001", HardwareAddr{0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01}, ""}, + {"02005e1000000001", HardwareAddr{0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01}, ""}, + + // See RFC 4391, Section 9.1.1. + { + "00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01", + HardwareAddr{ + 0x00, 0x00, 0x00, 0x00, + 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01, + }, + "", + }, + { + "00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01", + HardwareAddr{ + 0x00, 0x00, 0x00, 0x00, + 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01, + }, + "", + }, + { + "0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001", + HardwareAddr{ + 0x00, 0x00, 0x00, 0x00, + 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01, + }, + "", + }, + { + "00000000fe8000000000000002005e1000000001", + HardwareAddr{ + 0x00, 0x00, 0x00, 0x00, + 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01, + }, + "", + }, + + {"ab:cd:ef:AB:CD:EF", HardwareAddr{0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef}, ""}, + {"ab:cd:ef:AB:CD:EF:ab:cd", HardwareAddr{0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd}, ""}, + { + "ab:cd:ef:AB:CD:EF:ab:cd:ef:AB:CD:EF:ab:cd:ef:AB:CD:EF:ab:cd", + HardwareAddr{ + 0xab, 0xcd, 0xef, 0xab, + 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, + 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd, + }, + "", + }, + + {"01.02.03.04.05.06", nil, "invalid MAC address"}, + {"01:02:03:04:05:06:", nil, "invalid MAC address"}, + {"x1:02:03:04:05:06", nil, "invalid MAC address"}, + {"01002:03:04:05:06", nil, "invalid MAC address"}, + {"01:02003:04:05:06", nil, "invalid MAC address"}, + {"01:02:03004:05:06", nil, "invalid MAC address"}, + {"01:02:03:04005:06", nil, "invalid MAC address"}, + {"01:02:03:04:05006", nil, "invalid MAC address"}, + {"01-02:03:04:05:06", nil, "invalid MAC address"}, + {"01:02-03-04-05-06", nil, "invalid MAC address"}, + {"0123:4567:89AF", nil, "invalid MAC address"}, + {"0123-4567-89AF", nil, "invalid MAC address"}, + {"0123456789AF0", nil, "invalid MAC address"}, +} + +func TestParseMAC(t *testing.T) { + match := func(err error, s string) bool { + if s == "" { + return err == nil + } + return err != nil && strings.Contains(err.Error(), s) + } + + for i, tt := range parseMACTests { + out, err := ParseMAC(tt.in) + if !reflect.DeepEqual(out, tt.out) || !match(err, tt.err) { + t.Errorf("ParseMAC(%q) = %v, %v, want %v, %v", tt.in, out, err, tt.out, tt.err) + } + if tt.err == "" { + // Verify that serialization works too, and that it round-trips. + s := out.String() + out2, err := ParseMAC(s) + if err != nil { + t.Errorf("%d. ParseMAC(%q) = %v", i, s, err) + continue + } + if !reflect.DeepEqual(out2, out) { + t.Errorf("%d. ParseMAC(%q) = %v, want %v", i, s, out2, out) + } + } + } +} diff --git a/go/src/net/main_cloexec_test.go b/go/src/net/main_cloexec_test.go new file mode 100644 index 0000000000000000000000000000000000000000..6ea99ad6469cc954b8e4489554b37fdd269a3b2f --- /dev/null +++ b/go/src/net/main_cloexec_test.go @@ -0,0 +1,27 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build dragonfly || freebsd || linux || netbsd || openbsd || solaris + +package net + +import "internal/poll" + +func init() { + extraTestHookInstallers = append(extraTestHookInstallers, installAccept4TestHook) + extraTestHookUninstallers = append(extraTestHookUninstallers, uninstallAccept4TestHook) +} + +var ( + // Placeholders for saving original socket system calls. + origAccept4 = poll.Accept4Func +) + +func installAccept4TestHook() { + poll.Accept4Func = sw.Accept4 +} + +func uninstallAccept4TestHook() { + poll.Accept4Func = origAccept4 +} diff --git a/go/src/net/main_conf_test.go b/go/src/net/main_conf_test.go new file mode 100644 index 0000000000000000000000000000000000000000..bb140240ed92c4fb813e54bbe2343e5462d9f05c --- /dev/null +++ b/go/src/net/main_conf_test.go @@ -0,0 +1,97 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "runtime" + "testing" +) + +func allResolvers(t *testing.T, f func(t *testing.T)) { + t.Run("default resolver", f) + t.Run("forced go resolver", func(t *testing.T) { + // On plan9 the forceGoDNS might not force the go resolver, currently + // it is only forced when the Resolver.Dial field is populated. + // See conf.go mustUseGoResolver. + defer forceGoDNS()() + f(t) + }) + t.Run("forced cgo resolver", func(t *testing.T) { + defer forceCgoDNS()() + f(t) + }) +} + +// forceGoDNS forces the resolver configuration to use the pure Go resolver +// and returns a fixup function to restore the old settings. +func forceGoDNS() func() { + c := systemConf() + oldGo := c.netGo + oldCgo := c.netCgo + fixup := func() { + c.netGo = oldGo + c.netCgo = oldCgo + } + c.netGo = true + c.netCgo = false + return fixup +} + +// forceCgoDNS forces the resolver configuration to use the cgo resolver +// and returns a fixup function to restore the old settings. +func forceCgoDNS() func() { + c := systemConf() + oldGo := c.netGo + oldCgo := c.netCgo + fixup := func() { + c.netGo = oldGo + c.netCgo = oldCgo + } + c.netGo = false + c.netCgo = true + return fixup +} + +func TestForceCgoDNS(t *testing.T) { + if !cgoAvailable { + t.Skip("cgo resolver not available") + } + defer forceCgoDNS()() + order, _ := systemConf().hostLookupOrder(nil, "go.dev") + if order != hostLookupCgo { + t.Fatalf("hostLookupOrder returned: %v, want cgo", order) + } + order, _ = systemConf().addrLookupOrder(nil, "192.0.2.1") + if order != hostLookupCgo { + t.Fatalf("addrLookupOrder returned: %v, want cgo", order) + } + if systemConf().mustUseGoResolver(nil) { + t.Fatal("mustUseGoResolver = true, want false") + } +} + +func TestForceGoDNS(t *testing.T) { + var resolver *Resolver + if runtime.GOOS == "plan9" { + resolver = &Resolver{ + Dial: func(_ context.Context, _, _ string) (Conn, error) { + panic("unreachable") + }, + } + } + defer forceGoDNS()() + order, _ := systemConf().hostLookupOrder(resolver, "go.dev") + if order == hostLookupCgo { + t.Fatalf("hostLookupOrder returned: %v, want go resolver order", order) + } + order, _ = systemConf().addrLookupOrder(resolver, "192.0.2.1") + if order == hostLookupCgo { + t.Fatalf("addrLookupOrder returned: %v, want go resolver order", order) + } + if !systemConf().mustUseGoResolver(resolver) { + t.Fatal("mustUseGoResolver = false, want true") + } +} diff --git a/go/src/net/main_plan9_test.go b/go/src/net/main_plan9_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ca5f19adc149ac026fcc48f9c4e848991bfed822 --- /dev/null +++ b/go/src/net/main_plan9_test.go @@ -0,0 +1,20 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "os/exec" + +func installTestHooks() {} + +func uninstallTestHooks() {} + +// forceCloseSockets must be called only from TestMain. +func forceCloseSockets() {} + +func enableSocketConnect() {} + +func disableSocketConnect(network string) {} + +func addCmdInheritedHandle(cmd *exec.Cmd, fd uintptr) {} diff --git a/go/src/net/main_posix_test.go b/go/src/net/main_posix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..24a2a556605f738a6dd91705123a68832df49ac8 --- /dev/null +++ b/go/src/net/main_posix_test.go @@ -0,0 +1,50 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !plan9 + +package net + +import ( + "net/internal/socktest" + "strings" + "syscall" +) + +func enableSocketConnect() { + sw.Set(socktest.FilterConnect, nil) +} + +func disableSocketConnect(network string) { + net, _, _ := strings.Cut(network, ":") + sw.Set(socktest.FilterConnect, func(so *socktest.Status) (socktest.AfterFilter, error) { + switch net { + case "tcp4": + if so.Cookie.Family() == syscall.AF_INET && so.Cookie.Type() == syscall.SOCK_STREAM { + return nil, syscall.EHOSTUNREACH + } + case "udp4": + if so.Cookie.Family() == syscall.AF_INET && so.Cookie.Type() == syscall.SOCK_DGRAM { + return nil, syscall.EHOSTUNREACH + } + case "ip4": + if so.Cookie.Family() == syscall.AF_INET && so.Cookie.Type() == syscall.SOCK_RAW { + return nil, syscall.EHOSTUNREACH + } + case "tcp6": + if so.Cookie.Family() == syscall.AF_INET6 && so.Cookie.Type() == syscall.SOCK_STREAM { + return nil, syscall.EHOSTUNREACH + } + case "udp6": + if so.Cookie.Family() == syscall.AF_INET6 && so.Cookie.Type() == syscall.SOCK_DGRAM { + return nil, syscall.EHOSTUNREACH + } + case "ip6": + if so.Cookie.Family() == syscall.AF_INET6 && so.Cookie.Type() == syscall.SOCK_RAW { + return nil, syscall.EHOSTUNREACH + } + } + return nil, nil + }) +} diff --git a/go/src/net/main_test.go b/go/src/net/main_test.go new file mode 100644 index 0000000000000000000000000000000000000000..66735962f103737846f6460cb8c89a9b3951f51c --- /dev/null +++ b/go/src/net/main_test.go @@ -0,0 +1,222 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "flag" + "fmt" + "net/internal/socktest" + "os" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" +) + +var ( + sw socktest.Switch + + // uninstallTestHooks runs just before a run of benchmarks. + testHookUninstaller sync.Once +) + +var ( + testTCPBig = flag.Bool("tcpbig", false, "whether to test massive size of data per read or write call on TCP connection") + + testDNSFlood = flag.Bool("dnsflood", false, "whether to test DNS query flooding") + + // If external IPv4 connectivity exists, we can try dialing + // non-node/interface local scope IPv4 addresses. + // On Windows, Lookup APIs may not return IPv4-related + // resource records when a node has no external IPv4 + // connectivity. + testIPv4 = flag.Bool("ipv4", true, "assume external IPv4 connectivity exists") + + // If external IPv6 connectivity exists, we can try dialing + // non-node/interface local scope IPv6 addresses. + // On Windows, Lookup APIs may not return IPv6-related + // resource records when a node has no external IPv6 + // connectivity. + testIPv6 = flag.Bool("ipv6", false, "assume external IPv6 connectivity exists") +) + +func TestMain(m *testing.M) { + setupTestData() + installTestHooks() + + st := m.Run() + + testHookUninstaller.Do(uninstallTestHooks) + if testing.Verbose() { + printRunningGoroutines() + printInflightSockets() + printSocketStats() + } + forceCloseSockets() + os.Exit(st) +} + +// mustSetDeadline calls the bound method m to set a deadline on a Conn. +// If the call fails, mustSetDeadline skips t if the current GOOS is believed +// not to support deadlines, or fails the test otherwise. +func mustSetDeadline(t testing.TB, m func(time.Time) error, d time.Duration) { + err := m(time.Now().Add(d)) + if err != nil { + t.Helper() + if runtime.GOOS == "plan9" { + t.Skipf("skipping: %s does not support deadlines", runtime.GOOS) + } + t.Fatal(err) + } +} + +type ipv6LinkLocalUnicastTest struct { + network, address string + nameLookup bool +} + +var ( + ipv6LinkLocalUnicastTCPTests []ipv6LinkLocalUnicastTest + ipv6LinkLocalUnicastUDPTests []ipv6LinkLocalUnicastTest +) + +func setupTestData() { + if supportsIPv4() { + resolveTCPAddrTests = append(resolveTCPAddrTests, []resolveTCPAddrTest{ + {"tcp", "localhost:1", &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 1}, nil}, + {"tcp4", "localhost:2", &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 2}, nil}, + }...) + resolveUDPAddrTests = append(resolveUDPAddrTests, []resolveUDPAddrTest{ + {"udp", "localhost:1", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 1}, nil}, + {"udp4", "localhost:2", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 2}, nil}, + }...) + resolveIPAddrTests = append(resolveIPAddrTests, []resolveIPAddrTest{ + {"ip", "localhost", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, + {"ip4", "localhost", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, + }...) + } + + if supportsIPv6() { + resolveTCPAddrTests = append(resolveTCPAddrTests, resolveTCPAddrTest{"tcp6", "localhost:3", &TCPAddr{IP: IPv6loopback, Port: 3}, nil}) + resolveUDPAddrTests = append(resolveUDPAddrTests, resolveUDPAddrTest{"udp6", "localhost:3", &UDPAddr{IP: IPv6loopback, Port: 3}, nil}) + resolveIPAddrTests = append(resolveIPAddrTests, resolveIPAddrTest{"ip6", "localhost", &IPAddr{IP: IPv6loopback}, nil}) + + // Issue 20911: don't return IPv4 addresses for + // Resolve*Addr calls of the IPv6 unspecified address. + resolveTCPAddrTests = append(resolveTCPAddrTests, resolveTCPAddrTest{"tcp", "[::]:4", &TCPAddr{IP: IPv6unspecified, Port: 4}, nil}) + resolveUDPAddrTests = append(resolveUDPAddrTests, resolveUDPAddrTest{"udp", "[::]:4", &UDPAddr{IP: IPv6unspecified, Port: 4}, nil}) + resolveIPAddrTests = append(resolveIPAddrTests, resolveIPAddrTest{"ip", "::", &IPAddr{IP: IPv6unspecified}, nil}) + } + + ifi := loopbackInterface() + if ifi != nil { + index := fmt.Sprintf("%v", ifi.Index) + resolveTCPAddrTests = append(resolveTCPAddrTests, []resolveTCPAddrTest{ + {"tcp6", "[fe80::1%" + ifi.Name + "]:1", &TCPAddr{IP: ParseIP("fe80::1"), Port: 1, Zone: zoneCache.name(ifi.Index)}, nil}, + {"tcp6", "[fe80::1%" + index + "]:2", &TCPAddr{IP: ParseIP("fe80::1"), Port: 2, Zone: index}, nil}, + }...) + resolveUDPAddrTests = append(resolveUDPAddrTests, []resolveUDPAddrTest{ + {"udp6", "[fe80::1%" + ifi.Name + "]:1", &UDPAddr{IP: ParseIP("fe80::1"), Port: 1, Zone: zoneCache.name(ifi.Index)}, nil}, + {"udp6", "[fe80::1%" + index + "]:2", &UDPAddr{IP: ParseIP("fe80::1"), Port: 2, Zone: index}, nil}, + }...) + resolveIPAddrTests = append(resolveIPAddrTests, []resolveIPAddrTest{ + {"ip6", "fe80::1%" + ifi.Name, &IPAddr{IP: ParseIP("fe80::1"), Zone: zoneCache.name(ifi.Index)}, nil}, + {"ip6", "fe80::1%" + index, &IPAddr{IP: ParseIP("fe80::1"), Zone: index}, nil}, + }...) + } + + addr := ipv6LinkLocalUnicastAddr(ifi) + if addr != "" { + if runtime.GOOS != "dragonfly" { + ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ + {"tcp", "[" + addr + "%" + ifi.Name + "]:0", false}, + }...) + ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ + {"udp", "[" + addr + "%" + ifi.Name + "]:0", false}, + }...) + } + ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ + {"tcp6", "[" + addr + "%" + ifi.Name + "]:0", false}, + }...) + ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ + {"udp6", "[" + addr + "%" + ifi.Name + "]:0", false}, + }...) + switch runtime.GOOS { + case "darwin", "ios", "dragonfly", "freebsd", "openbsd", "netbsd": + ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ + {"tcp", "[localhost%" + ifi.Name + "]:0", true}, + {"tcp6", "[localhost%" + ifi.Name + "]:0", true}, + }...) + ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ + {"udp", "[localhost%" + ifi.Name + "]:0", true}, + {"udp6", "[localhost%" + ifi.Name + "]:0", true}, + }...) + case "linux": + ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ + {"tcp", "[ip6-localhost%" + ifi.Name + "]:0", true}, + {"tcp6", "[ip6-localhost%" + ifi.Name + "]:0", true}, + }...) + ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ + {"udp", "[ip6-localhost%" + ifi.Name + "]:0", true}, + {"udp6", "[ip6-localhost%" + ifi.Name + "]:0", true}, + }...) + } + } +} + +func printRunningGoroutines() { + gss := runningGoroutines() + if len(gss) == 0 { + return + } + fmt.Fprintf(os.Stderr, "Running goroutines:\n") + for _, gs := range gss { + fmt.Fprintf(os.Stderr, "%v\n", gs) + } + fmt.Fprintf(os.Stderr, "\n") +} + +// runningGoroutines returns a list of remaining goroutines. +func runningGoroutines() []string { + var gss []string + b := make([]byte, 2<<20) + b = b[:runtime.Stack(b, true)] + for s := range strings.SplitSeq(string(b), "\n\n") { + _, stack, _ := strings.Cut(s, "\n") + stack = strings.TrimSpace(stack) + if !strings.Contains(stack, "created by net") { + continue + } + gss = append(gss, stack) + } + slices.Sort(gss) + return gss +} + +func printInflightSockets() { + sos := sw.Sockets() + if len(sos) == 0 { + return + } + fmt.Fprintf(os.Stderr, "Inflight sockets:\n") + for s, so := range sos { + fmt.Fprintf(os.Stderr, "%v: %v\n", s, so) + } + fmt.Fprintf(os.Stderr, "\n") +} + +func printSocketStats() { + sts := sw.Stats() + if len(sts) == 0 { + return + } + fmt.Fprintf(os.Stderr, "Socket statistical information:\n") + for _, st := range sts { + fmt.Fprintf(os.Stderr, "%v\n", st) + } + fmt.Fprintf(os.Stderr, "\n") +} diff --git a/go/src/net/main_unix_test.go b/go/src/net/main_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..49d15b963e26301886211a10cab0212003735282 --- /dev/null +++ b/go/src/net/main_unix_test.go @@ -0,0 +1,60 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "internal/poll" + "os/exec" +) + +var ( + // Placeholders for saving original socket system calls. + origSocket = socketFunc + origClose = poll.CloseFunc + origConnect = connectFunc + origListen = listenFunc + origAccept = poll.AcceptFunc + origGetsockoptInt = getsockoptIntFunc + + extraTestHookInstallers []func() + extraTestHookUninstallers []func() +) + +func installTestHooks() { + socketFunc = sw.Socket + poll.CloseFunc = sw.Close + connectFunc = sw.Connect + listenFunc = sw.Listen + poll.AcceptFunc = sw.Accept + getsockoptIntFunc = sw.GetsockoptInt + + for _, fn := range extraTestHookInstallers { + fn() + } +} + +func uninstallTestHooks() { + socketFunc = origSocket + poll.CloseFunc = origClose + connectFunc = origConnect + listenFunc = origListen + poll.AcceptFunc = origAccept + getsockoptIntFunc = origGetsockoptInt + + for _, fn := range extraTestHookUninstallers { + fn() + } +} + +// forceCloseSockets must be called only from TestMain. +func forceCloseSockets() { + for s := range sw.Sockets() { + poll.CloseFunc(s) + } +} + +func addCmdInheritedHandle(cmd *exec.Cmd, fd uintptr) {} diff --git a/go/src/net/main_wasm_test.go b/go/src/net/main_wasm_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2dcfdabb3b444bc520b35cf79ef11389dc47eb52 --- /dev/null +++ b/go/src/net/main_wasm_test.go @@ -0,0 +1,17 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build wasip1 || js + +package net + +import "os/exec" + +func installTestHooks() {} + +func uninstallTestHooks() {} + +func forceCloseSockets() {} + +func addCmdInheritedHandle(cmd *exec.Cmd, fd uintptr) {} diff --git a/go/src/net/main_windows_test.go b/go/src/net/main_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..425030133535ca90c007e40c87f41ee496f2ad3f --- /dev/null +++ b/go/src/net/main_windows_test.go @@ -0,0 +1,57 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/poll" + "os/exec" + "syscall" +) + +var ( + // Placeholders for saving original socket system calls. + origWSASocket = wsaSocketFunc + origClosesocket = poll.CloseFunc + origConnect = connectFunc + origConnectEx = poll.ConnectExFunc + origListen = listenFunc + origAccept = poll.AcceptFunc +) + +func installTestHooks() { + wsaSocketFunc = sw.WSASocket + poll.CloseFunc = sw.Closesocket + connectFunc = sw.Connect + poll.ConnectExFunc = sw.ConnectEx + listenFunc = sw.Listen + poll.AcceptFunc = sw.AcceptEx +} + +func uninstallTestHooks() { + wsaSocketFunc = origWSASocket + poll.CloseFunc = origClosesocket + connectFunc = origConnect + poll.ConnectExFunc = origConnectEx + listenFunc = origListen + poll.AcceptFunc = origAccept +} + +// forceCloseSockets must be called only from TestMain. +func forceCloseSockets() { + for s := range sw.Sockets() { + poll.CloseFunc(s) + } +} + +func addCmdInheritedHandle(cmd *exec.Cmd, fd uintptr) { + // Inherited handles are not inherited by default in Windows. + // We need to set the handle inheritance flag explicitly. + // See https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa#parameters + // for more details. + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = &syscall.SysProcAttr{} + } + cmd.SysProcAttr.AdditionalInheritedHandles = append(cmd.SysProcAttr.AdditionalInheritedHandles, syscall.Handle(fd)) +} diff --git a/go/src/net/mockserver_test.go b/go/src/net/mockserver_test.go new file mode 100644 index 0000000000000000000000000000000000000000..66b8cbe40da5369c9722040446c5c63c03b83972 --- /dev/null +++ b/go/src/net/mockserver_test.go @@ -0,0 +1,645 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "errors" + "fmt" + "internal/testenv" + "log" + "os" + "path/filepath" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +// testUnixAddr uses os.MkdirTemp to get a name that is unique. +func testUnixAddr(t testing.TB) string { + // Pass an empty pattern to get a directory name that is as short as possible. + // If we end up with a name longer than the sun_path field in the sockaddr_un + // struct, we won't be able to make the syscall to open the socket. + d, err := os.MkdirTemp("", "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := os.RemoveAll(d); err != nil { + t.Error(err) + } + }) + return filepath.Join(d, "sock") +} + +func newLocalListener(t testing.TB, network string, lcOpt ...*ListenConfig) Listener { + var lc *ListenConfig + switch len(lcOpt) { + case 0: + lc = new(ListenConfig) + case 1: + lc = lcOpt[0] + default: + t.Helper() + t.Fatal("too many ListenConfigs passed to newLocalListener: want 0 or 1") + } + + listen := func(net, addr string) Listener { + ln, err := lc.Listen(context.Background(), net, addr) + if err != nil { + t.Helper() + t.Fatal(err) + } + return ln + } + + switch network { + case "tcp": + if supportsIPv4() { + return listen("tcp4", "127.0.0.1:0") + } + if supportsIPv6() { + return listen("tcp6", "[::1]:0") + } + case "tcp4": + if supportsIPv4() { + return listen("tcp4", "127.0.0.1:0") + } + case "tcp6": + if supportsIPv6() { + return listen("tcp6", "[::1]:0") + } + case "unix", "unixpacket": + return listen(network, testUnixAddr(t)) + } + + t.Helper() + t.Fatalf("%s is not supported", network) + return nil +} + +func newDualStackListener() (lns []*TCPListener, err error) { + var args = []struct { + network string + TCPAddr + }{ + {"tcp4", TCPAddr{IP: IPv4(127, 0, 0, 1)}}, + {"tcp6", TCPAddr{IP: IPv6loopback}}, + } + for i := 0; i < 64; i++ { + var port int + var lns []*TCPListener + for _, arg := range args { + arg.TCPAddr.Port = port + ln, err := ListenTCP(arg.network, &arg.TCPAddr) + if err != nil { + continue + } + port = ln.Addr().(*TCPAddr).Port + lns = append(lns, ln) + } + if len(lns) != len(args) { + for _, ln := range lns { + ln.Close() + } + continue + } + return lns, nil + } + return nil, errors.New("no dualstack port available") +} + +type localServer struct { + lnmu sync.RWMutex + Listener + done chan bool // signal that indicates server stopped + cl []Conn // accepted connection list +} + +func (ls *localServer) buildup(handler func(*localServer, Listener)) error { + go func() { + handler(ls, ls.Listener) + close(ls.done) + }() + return nil +} + +func (ls *localServer) teardown() error { + ls.lnmu.Lock() + defer ls.lnmu.Unlock() + if ls.Listener != nil { + network := ls.Listener.Addr().Network() + address := ls.Listener.Addr().String() + ls.Listener.Close() + for _, c := range ls.cl { + if err := c.Close(); err != nil { + return err + } + } + <-ls.done + ls.Listener = nil + switch network { + case "unix", "unixpacket": + os.Remove(address) + } + } + return nil +} + +func newLocalServer(t testing.TB, network string) *localServer { + t.Helper() + ln := newLocalListener(t, network) + return &localServer{Listener: ln, done: make(chan bool)} +} + +type streamListener struct { + network, address string + Listener + done chan bool // signal that indicates server stopped +} + +func (sl *streamListener) newLocalServer() *localServer { + return &localServer{Listener: sl.Listener, done: make(chan bool)} +} + +type dualStackServer struct { + lnmu sync.RWMutex + lns []streamListener + port string + + cmu sync.RWMutex + cs []Conn // established connections at the passive open side +} + +func (dss *dualStackServer) buildup(handler func(*dualStackServer, Listener)) error { + for i := range dss.lns { + go func(i int) { + handler(dss, dss.lns[i].Listener) + close(dss.lns[i].done) + }(i) + } + return nil +} + +func (dss *dualStackServer) teardownNetwork(network string) error { + dss.lnmu.Lock() + for i := range dss.lns { + if network == dss.lns[i].network && dss.lns[i].Listener != nil { + dss.lns[i].Listener.Close() + <-dss.lns[i].done + dss.lns[i].Listener = nil + } + } + dss.lnmu.Unlock() + return nil +} + +func (dss *dualStackServer) teardown() error { + dss.lnmu.Lock() + for i := range dss.lns { + if dss.lns[i].Listener != nil { + dss.lns[i].Listener.Close() + <-dss.lns[i].done + } + } + dss.lns = dss.lns[:0] + dss.lnmu.Unlock() + dss.cmu.Lock() + for _, c := range dss.cs { + c.Close() + } + dss.cs = dss.cs[:0] + dss.cmu.Unlock() + return nil +} + +func newDualStackServer() (*dualStackServer, error) { + lns, err := newDualStackListener() + if err != nil { + return nil, err + } + _, port, err := SplitHostPort(lns[0].Addr().String()) + if err != nil { + lns[0].Close() + lns[1].Close() + return nil, err + } + return &dualStackServer{ + lns: []streamListener{ + {network: "tcp4", address: lns[0].Addr().String(), Listener: lns[0], done: make(chan bool)}, + {network: "tcp6", address: lns[1].Addr().String(), Listener: lns[1], done: make(chan bool)}, + }, + port: port, + }, nil +} + +func (ls *localServer) transponder(ln Listener, ch chan<- error) { + defer close(ch) + + switch ln := ln.(type) { + case *TCPListener: + ln.SetDeadline(time.Now().Add(someTimeout)) + case *UnixListener: + ln.SetDeadline(time.Now().Add(someTimeout)) + } + c, err := ln.Accept() + if err != nil { + if perr := parseAcceptError(err); perr != nil { + ch <- perr + } + ch <- err + return + } + ls.cl = append(ls.cl, c) + + network := ln.Addr().Network() + if c.LocalAddr().Network() != network || c.RemoteAddr().Network() != network { + ch <- fmt.Errorf("got %v->%v; expected %v->%v", c.LocalAddr().Network(), c.RemoteAddr().Network(), network, network) + return + } + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + + b := make([]byte, 256) + n, err := c.Read(b) + if err != nil { + if perr := parseReadError(err); perr != nil { + ch <- perr + } + ch <- err + return + } + if _, err := c.Write(b[:n]); err != nil { + if perr := parseWriteError(err); perr != nil { + ch <- perr + } + ch <- err + return + } +} + +func transceiver(c Conn, wb []byte, ch chan<- error) { + defer close(ch) + + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + + n, err := c.Write(wb) + if err != nil { + if perr := parseWriteError(err); perr != nil { + ch <- perr + } + ch <- err + return + } + if n != len(wb) { + ch <- fmt.Errorf("wrote %d; want %d", n, len(wb)) + } + rb := make([]byte, len(wb)) + n, err = c.Read(rb) + if err != nil { + if perr := parseReadError(err); perr != nil { + ch <- perr + } + ch <- err + return + } + if n != len(wb) { + ch <- fmt.Errorf("read %d; want %d", n, len(wb)) + } +} + +func newLocalPacketListener(t testing.TB, network string, lcOpt ...*ListenConfig) PacketConn { + var lc *ListenConfig + switch len(lcOpt) { + case 0: + lc = new(ListenConfig) + case 1: + lc = lcOpt[0] + default: + t.Helper() + t.Fatal("too many ListenConfigs passed to newLocalListener: want 0 or 1") + } + + listenPacket := func(net, addr string) PacketConn { + c, err := lc.ListenPacket(context.Background(), net, addr) + if err != nil { + t.Helper() + t.Fatal(err) + } + return c + } + + t.Helper() + switch network { + case "udp": + if supportsIPv4() { + return listenPacket("udp4", "127.0.0.1:0") + } + if supportsIPv6() { + return listenPacket("udp6", "[::1]:0") + } + case "udp4": + if supportsIPv4() { + return listenPacket("udp4", "127.0.0.1:0") + } + case "udp6": + if supportsIPv6() { + return listenPacket("udp6", "[::1]:0") + } + case "unixgram": + return listenPacket(network, testUnixAddr(t)) + } + + t.Fatalf("%s is not supported", network) + return nil +} + +func newDualStackPacketListener() (cs []*UDPConn, err error) { + var args = []struct { + network string + UDPAddr + }{ + {"udp4", UDPAddr{IP: IPv4(127, 0, 0, 1)}}, + {"udp6", UDPAddr{IP: IPv6loopback}}, + } + for i := 0; i < 64; i++ { + var port int + var cs []*UDPConn + for _, arg := range args { + arg.UDPAddr.Port = port + c, err := ListenUDP(arg.network, &arg.UDPAddr) + if err != nil { + continue + } + port = c.LocalAddr().(*UDPAddr).Port + cs = append(cs, c) + } + if len(cs) != len(args) { + for _, c := range cs { + c.Close() + } + continue + } + return cs, nil + } + return nil, errors.New("no dualstack port available") +} + +type localPacketServer struct { + pcmu sync.RWMutex + PacketConn + done chan bool // signal that indicates server stopped +} + +func (ls *localPacketServer) buildup(handler func(*localPacketServer, PacketConn)) error { + go func() { + handler(ls, ls.PacketConn) + close(ls.done) + }() + return nil +} + +func (ls *localPacketServer) teardown() error { + ls.pcmu.Lock() + if ls.PacketConn != nil { + network := ls.PacketConn.LocalAddr().Network() + address := ls.PacketConn.LocalAddr().String() + ls.PacketConn.Close() + <-ls.done + ls.PacketConn = nil + switch network { + case "unixgram": + os.Remove(address) + } + } + ls.pcmu.Unlock() + return nil +} + +func newLocalPacketServer(t testing.TB, network string) *localPacketServer { + t.Helper() + c := newLocalPacketListener(t, network) + return &localPacketServer{PacketConn: c, done: make(chan bool)} +} + +type packetListener struct { + PacketConn +} + +func (pl *packetListener) newLocalServer() *localPacketServer { + return &localPacketServer{PacketConn: pl.PacketConn, done: make(chan bool)} +} + +func packetTransponder(c PacketConn, ch chan<- error) { + defer close(ch) + + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + + b := make([]byte, 256) + n, peer, err := c.ReadFrom(b) + if err != nil { + if perr := parseReadError(err); perr != nil { + ch <- perr + } + ch <- err + return + } + if peer == nil { // for connected-mode sockets + switch c.LocalAddr().Network() { + case "udp": + peer, err = ResolveUDPAddr("udp", string(b[:n])) + case "unixgram": + peer, err = ResolveUnixAddr("unixgram", string(b[:n])) + } + if err != nil { + ch <- err + return + } + } + if _, err := c.WriteTo(b[:n], peer); err != nil { + if perr := parseWriteError(err); perr != nil { + ch <- perr + } + ch <- err + return + } +} + +func packetTransceiver(c PacketConn, wb []byte, dst Addr, ch chan<- error) { + defer close(ch) + + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + + n, err := c.WriteTo(wb, dst) + if err != nil { + if perr := parseWriteError(err); perr != nil { + ch <- perr + } + ch <- err + return + } + if n != len(wb) { + ch <- fmt.Errorf("wrote %d; want %d", n, len(wb)) + } + rb := make([]byte, len(wb)) + n, _, err = c.ReadFrom(rb) + if err != nil { + if perr := parseReadError(err); perr != nil { + ch <- perr + } + ch <- err + return + } + if n != len(wb) { + ch <- fmt.Errorf("read %d; want %d", n, len(wb)) + } +} + +func spawnTestSocketPair(t testing.TB, net string) (client, server Conn) { + t.Helper() + + if !testableNetwork(net) { + t.Skipf("network %q not supported", net) + } + + ln := newLocalListener(t, net) + defer ln.Close() + var cerr, serr error + acceptDone := make(chan struct{}) + go func() { + server, serr = ln.Accept() + acceptDone <- struct{}{} + }() + client, cerr = Dial(ln.Addr().Network(), ln.Addr().String()) + <-acceptDone + if cerr != nil { + if server != nil { + server.Close() + } + t.Fatal(cerr) + } + if serr != nil { + if client != nil { + client.Close() + } + t.Fatal(serr) + } + return client, server +} + +func startTestSocketPeer(t testing.TB, conn Conn, op string, chunkSize, totalSize int) (func(t testing.TB), error) { + t.Helper() + f, err := conn.(interface{ File() (*os.File, error) }).File() + if err != nil { + return nil, err + } + + cmd := testenv.Command(t, testenv.Executable(t)) + cmd.Env = []string{ + "GO_NET_TEST_TRANSFER=1", + "GO_NET_TEST_TRANSFER_OP=" + op, + "GO_NET_TEST_TRANSFER_CHUNK_SIZE=" + strconv.Itoa(chunkSize), + "GO_NET_TEST_TRANSFER_TOTAL_SIZE=" + strconv.Itoa(totalSize), + "TMPDIR=" + os.Getenv("TMPDIR"), + } + if runtime.GOOS == "windows" { + // Windows doesn't support ExtraFiles + fd := f.Fd() + cmd.Env = append(cmd.Env, "GO_NET_TEST_TRANSFER_FD="+strconv.FormatUint(uint64(fd), 10)) + addCmdInheritedHandle(cmd, fd) + } else { + cmd.ExtraFiles = append(cmd.ExtraFiles, f) + } + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + if err := cmd.Start(); err != nil { + return nil, err + } + + cmdCh := make(chan error, 1) + go func() { + err := cmd.Wait() + conn.Close() + f.Close() + cmdCh <- err + }() + + return func(tb testing.TB) { + err := <-cmdCh + if err != nil { + tb.Errorf("process exited with error: %v", err) + } + }, nil +} + +func init() { + if os.Getenv("GO_NET_TEST_TRANSFER") == "" { + return + } + defer os.Exit(0) + + var fd uintptr + if runtime.GOOS == "windows" { + v, err := strconv.ParseUint(os.Getenv("GO_NET_TEST_TRANSFER_FD"), 10, 0) + if err != nil { + log.Fatal(err) + } + fd = uintptr(v) + } else { + fd = uintptr(3) + } + f := os.NewFile(fd, "splice-test-conn") + defer f.Close() + + conn, err := FileConn(f) + if err != nil { + log.Fatal(err) + } + + var chunkSize int + if chunkSize, err = strconv.Atoi(os.Getenv("GO_NET_TEST_TRANSFER_CHUNK_SIZE")); err != nil { + log.Fatal(err) + } + buf := make([]byte, chunkSize) + + var totalSize int + if totalSize, err = strconv.Atoi(os.Getenv("GO_NET_TEST_TRANSFER_TOTAL_SIZE")); err != nil { + log.Fatal(err) + } + + var fn func([]byte) (int, error) + switch op := os.Getenv("GO_NET_TEST_TRANSFER_OP"); op { + case "r": + fn = conn.Read + case "w": + defer conn.Close() + + fn = conn.Write + default: + log.Fatalf("unknown op %q", op) + } + + var n int + for count := 0; count < totalSize; count += n { + if count+chunkSize > totalSize { + buf = buf[:totalSize-count] + } + + var err error + if n, err = fn(buf); err != nil { + return + } + } +} diff --git a/go/src/net/mptcpsock_linux.go b/go/src/net/mptcpsock_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..5b58418653fbf51cdc68024b1302106bd6a9e38c --- /dev/null +++ b/go/src/net/mptcpsock_linux.go @@ -0,0 +1,137 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "context" + "errors" + "internal/poll" + "internal/syscall/unix" + "sync" + "syscall" +) + +var ( + mptcpOnce sync.Once + mptcpAvailable bool + hasSOLMPTCP bool // only valid if mptcpAvailable is true +) + +// These constants aren't in the syscall package, which is frozen +const ( + _IPPROTO_MPTCP = 0x106 + _SOL_MPTCP = 0x11c + _MPTCP_INFO = 0x1 +) + +func supportsMultipathTCP() bool { + mptcpOnce.Do(initMPTCPavailable) + return mptcpAvailable +} + +// Check that MPTCP is supported by attempting to create an MPTCP socket and by +// looking at the returned error if any. +func initMPTCPavailable() { + family := syscall.AF_INET + if !supportsIPv4() { + family = syscall.AF_INET6 + } + s, err := sysSocket(family, syscall.SOCK_STREAM, _IPPROTO_MPTCP) + + switch { + case errors.Is(err, syscall.EPROTONOSUPPORT): // Not supported: >= v5.6 + return + case errors.Is(err, syscall.EINVAL): // Not supported: < v5.6 + return + case err == nil: // Supported and no error + poll.CloseFunc(s) + fallthrough + default: + // another error: MPTCP was not available but it might be later + mptcpAvailable = true + } + + // SOL_MPTCP only supported from kernel 5.16. + hasSOLMPTCP = unix.KernelVersionGE(5, 16) +} + +func (sd *sysDialer) dialMPTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) { + if supportsMultipathTCP() { + if conn, err := sd.doDialTCPProto(ctx, laddr, raddr, _IPPROTO_MPTCP); err == nil { + return conn, nil + } + } + + // Fallback to dialTCP if Multipath TCP isn't supported on this operating + // system. But also fallback in case of any error with MPTCP. + // + // Possible MPTCP specific error: ENOPROTOOPT (sysctl net.mptcp.enabled=0) + // But just in case MPTCP is blocked differently (SELinux, etc.), just + // retry with "plain" TCP. + return sd.dialTCP(ctx, laddr, raddr) +} + +func (sl *sysListener) listenMPTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) { + if supportsMultipathTCP() { + if dial, err := sl.listenTCPProto(ctx, laddr, _IPPROTO_MPTCP); err == nil { + return dial, nil + } + } + + // Fallback to listenTCP if Multipath TCP isn't supported on this operating + // system. But also fallback in case of any error with MPTCP. + // + // Possible MPTCP specific error: ENOPROTOOPT (sysctl net.mptcp.enabled=0) + // But just in case MPTCP is blocked differently (SELinux, etc.), just + // retry with "plain" TCP. + return sl.listenTCP(ctx, laddr) +} + +// hasFallenBack reports whether the MPTCP connection has fallen back to "plain" +// TCP. +// +// A connection can fallback to TCP for different reasons, e.g. the other peer +// doesn't support it, a middle box "accidentally" drops the option, etc. +// +// If the MPTCP protocol has not been requested when creating the socket, this +// method will return true: MPTCP is not being used. +// +// Kernel >= 5.16 returns EOPNOTSUPP/ENOPROTOOPT in case of fallback. +// Older kernels will always return them even if MPTCP is used: not usable. +func hasFallenBack(fd *netFD) bool { + _, err := fd.pfd.GetsockoptInt(_SOL_MPTCP, _MPTCP_INFO) + + // 2 expected errors in case of fallback depending on the address family + // - AF_INET: EOPNOTSUPP + // - AF_INET6: ENOPROTOOPT + return err == syscall.EOPNOTSUPP || err == syscall.ENOPROTOOPT +} + +// isUsingMPTCPProto reports whether the socket protocol is MPTCP. +// +// Compared to hasFallenBack method, here only the socket protocol being used is +// checked: it can be MPTCP but it doesn't mean MPTCP is used on the wire, maybe +// a fallback to TCP has been done. +func isUsingMPTCPProto(fd *netFD) bool { + proto, _ := fd.pfd.GetsockoptInt(syscall.SOL_SOCKET, syscall.SO_PROTOCOL) + + return proto == _IPPROTO_MPTCP +} + +// isUsingMultipathTCP reports whether MPTCP is still being used. +// +// Please look at the description of hasFallenBack (kernel >=5.16) and +// isUsingMPTCPProto methods for more details about what is being checked here. +func isUsingMultipathTCP(fd *netFD) bool { + if !supportsMultipathTCP() { + return false + } + + if hasSOLMPTCP { + return !hasFallenBack(fd) + } + + return isUsingMPTCPProto(fd) +} diff --git a/go/src/net/mptcpsock_linux_test.go b/go/src/net/mptcpsock_linux_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5134aba75eabb5d36e168fa1c5733ae7a01f6695 --- /dev/null +++ b/go/src/net/mptcpsock_linux_test.go @@ -0,0 +1,192 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "bytes" + "context" + "errors" + "syscall" + "testing" +) + +func newLocalListenerMPTCP(t *testing.T, envVar bool) Listener { + lc := &ListenConfig{} + + if envVar { + if !lc.MultipathTCP() { + t.Fatal("MultipathTCP Listen is not on despite GODEBUG=multipathtcp=1") + } + } else { + if lc.MultipathTCP() { + t.Error("MultipathTCP should be off by default") + } + + lc.SetMultipathTCP(true) + if !lc.MultipathTCP() { + t.Fatal("MultipathTCP is not on after having been forced to on") + } + } + + ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + return ln +} + +func postAcceptMPTCP(ls *localServer, ch chan<- error) { + defer close(ch) + + if len(ls.cl) == 0 { + ch <- errors.New("no accepted stream") + return + } + + c := ls.cl[0] + + tcp, ok := c.(*TCPConn) + if !ok { + ch <- errors.New("struct is not a TCPConn") + return + } + + mptcp, err := tcp.MultipathTCP() + if err != nil { + ch <- err + return + } + + if !mptcp { + ch <- errors.New("incoming connection is not with MPTCP") + return + } + + // Also check the method for the older kernels if not tested before + if hasSOLMPTCP && !isUsingMPTCPProto(tcp.fd) { + ch <- errors.New("incoming connection is not an MPTCP proto") + return + } +} + +func dialerMPTCP(t *testing.T, addr string, envVar bool) { + d := &Dialer{} + + if envVar { + if !d.MultipathTCP() { + t.Fatal("MultipathTCP Dialer is not on despite GODEBUG=multipathtcp=1") + } + } else { + if d.MultipathTCP() { + t.Error("MultipathTCP should be off by default") + } + + d.SetMultipathTCP(true) + if !d.MultipathTCP() { + t.Fatal("MultipathTCP is not on after having been forced to on") + } + } + + c, err := d.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + + tcp, ok := c.(*TCPConn) + if !ok { + t.Fatal("struct is not a TCPConn") + } + + // Transfer a bit of data to make sure everything is still OK + snt := []byte("MPTCP TEST") + if _, err := c.Write(snt); err != nil { + t.Fatal(err) + } + b := make([]byte, len(snt)) + if _, err := c.Read(b); err != nil { + t.Fatal(err) + } + if !bytes.Equal(snt, b) { + t.Errorf("sent bytes (%s) are different from received ones (%s)", snt, b) + } + + mptcp, err := tcp.MultipathTCP() + if err != nil { + t.Fatal(err) + } + + t.Logf("outgoing connection from %s with mptcp: %t", addr, mptcp) + + if !mptcp { + t.Error("outgoing connection is not with MPTCP") + } + + // Also check the method for the older kernels if not tested before + if hasSOLMPTCP && !isUsingMPTCPProto(tcp.fd) { + t.Error("outgoing connection is not an MPTCP proto") + } +} + +func canCreateMPTCPSocket() bool { + // We want to know if we can create an MPTCP socket, not just if it is + // available (mptcpAvailable()): it could be blocked by the admin + fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, _IPPROTO_MPTCP) + if err != nil { + return false + } + + syscall.Close(fd) + return true +} + +func testMultiPathTCP(t *testing.T, envVar bool) { + if envVar { + t.Log("Test with GODEBUG=multipathtcp=1") + t.Setenv("GODEBUG", "multipathtcp=1") + } else { + t.Log("Test with GODEBUG=multipathtcp=0") + t.Setenv("GODEBUG", "multipathtcp=0") + } + + ln := newLocalListenerMPTCP(t, envVar) + + // similar to tcpsock_test:TestIPv6LinkLocalUnicastTCP + ls := (&streamListener{Listener: ln}).newLocalServer() + defer ls.teardown() + + if g, w := ls.Listener.Addr().Network(), "tcp"; g != w { + t.Fatalf("Network type mismatch: got %q, want %q", g, w) + } + + genericCh := make(chan error) + mptcpCh := make(chan error) + handler := func(ls *localServer, ln Listener) { + ls.transponder(ln, genericCh) + postAcceptMPTCP(ls, mptcpCh) + } + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + + dialerMPTCP(t, ln.Addr().String(), envVar) + + if err := <-genericCh; err != nil { + t.Error(err) + } + if err := <-mptcpCh; err != nil { + t.Error(err) + } +} + +func TestMultiPathTCP(t *testing.T) { + if !canCreateMPTCPSocket() { + t.Skip("Cannot create MPTCP sockets") + } + + for _, envVar := range []bool{false, true} { + testMultiPathTCP(t, envVar) + } +} diff --git a/go/src/net/mptcpsock_stub.go b/go/src/net/mptcpsock_stub.go new file mode 100644 index 0000000000000000000000000000000000000000..458c1530d75d6c80fcab2ef0767a3451cd084692 --- /dev/null +++ b/go/src/net/mptcpsock_stub.go @@ -0,0 +1,23 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !linux + +package net + +import ( + "context" +) + +func (sd *sysDialer) dialMPTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) { + return sd.dialTCP(ctx, laddr, raddr) +} + +func (sl *sysListener) listenMPTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) { + return sl.listenTCP(ctx, laddr) +} + +func isUsingMultipathTCP(fd *netFD) bool { + return false +} diff --git a/go/src/net/net.go b/go/src/net/net.go new file mode 100644 index 0000000000000000000000000000000000000000..72f5772155098290391aa58cf03e084a3af72fbb --- /dev/null +++ b/go/src/net/net.go @@ -0,0 +1,897 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package net provides a portable interface for network I/O, including +TCP/IP, UDP, domain name resolution, and Unix domain sockets. + +Although the package provides access to low-level networking +primitives, most clients will need only the basic interface provided +by the [Dial], [Listen], and Accept functions and the associated +[Conn] and [Listener] interfaces. The crypto/tls package uses +the same interfaces and similar Dial and Listen functions. + +The Dial function connects to a server: + + conn, err := net.Dial("tcp", "golang.org:80") + if err != nil { + // handle error + } + fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") + status, err := bufio.NewReader(conn).ReadString('\n') + // ... + +The Listen function creates servers: + + ln, err := net.Listen("tcp", ":8080") + if err != nil { + // handle error + } + for { + conn, err := ln.Accept() + if err != nil { + // handle error + } + go handleConnection(conn) + } + +# Name Resolution + +The method for resolving domain names, whether indirectly with functions like Dial +or directly with functions like [LookupHost] and [LookupAddr], varies by operating system. + +On Unix systems, the resolver has two options for resolving names. +It can use a pure Go resolver that sends DNS requests directly to the servers +listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C +library routines such as getaddrinfo and getnameinfo. + +On Unix the pure Go resolver is preferred over the cgo resolver, because a blocked DNS +request consumes only a goroutine, while a blocked C call consumes an operating system thread. +When cgo is available, the cgo-based resolver is used instead under a variety of +conditions: on systems that do not let programs make direct DNS requests (OS X), +when the LOCALDOMAIN environment variable is present (even if empty), +when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, +when the ASR_CONFIG environment variable is non-empty (OpenBSD only), +when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the +Go resolver does not implement. + +On all systems (except Plan 9), when the cgo resolver is being used +this package applies a concurrent cgo lookup limit to prevent the system +from running out of system threads. Currently, it is limited to 500 concurrent lookups. + +The resolver decision can be overridden by setting the netdns value of the +GODEBUG environment variable (see package runtime) to go or cgo, as in: + + export GODEBUG=netdns=go # force pure Go resolver + export GODEBUG=netdns=cgo # force native resolver (cgo, win32) + +The decision can also be forced while building the Go source tree +by setting the netgo or netcgo build tag. +The netgo build tag disables entirely the use of the native (CGO) resolver, +meaning the Go resolver is the only one that can be used. +With the netcgo build tag the native and the pure Go resolver are compiled into the binary, +but the native (CGO) resolver is preferred over the Go resolver. +With netcgo, the Go resolver can still be forced at runtime with GODEBUG=netdns=go. + +A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver +to print debugging information about its decisions. +To force a particular resolver while also printing debugging information, +join the two settings by a plus sign, as in GODEBUG=netdns=go+1. + +The Go resolver will send an EDNS0 additional header with a DNS request, +to signal a willingness to accept a larger DNS packet size. +This can reportedly cause sporadic failures with the DNS server run +by some modems and routers. Setting GODEBUG=netedns0=0 will disable +sending the additional header. + +On macOS, if Go code that uses the net package is built with +-buildmode=c-archive, linking the resulting archive into a C program +requires passing -lresolv when linking the C code. + +On Plan 9, the resolver always accesses /net/cs and /net/dns. + +On Windows, in Go 1.18.x and earlier, the resolver always used C +library functions, such as GetAddrInfo and DnsQuery. +*/ +package net + +import ( + "context" + "errors" + "internal/poll" + "io" + "os" + "sync" + "syscall" + "time" + _ "unsafe" // for linkname +) + +// Addr represents a network end point address. +// +// The two methods [Addr.Network] and [Addr.String] conventionally return strings +// that can be passed as the arguments to [Dial], but the exact form +// and meaning of the strings is up to the implementation. +type Addr interface { + Network() string // name of the network (for example, "tcp", "udp") + String() string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") +} + +// Conn is a generic stream-oriented network connection. +// +// Multiple goroutines may invoke methods on a Conn simultaneously. +type Conn interface { + // Read reads data from the connection. + // Read can be made to time out and return an error after a fixed + // time limit; see SetDeadline and SetReadDeadline. + Read(b []byte) (n int, err error) + + // Write writes data to the connection. + // Write can be made to time out and return an error after a fixed + // time limit; see SetDeadline and SetWriteDeadline. + Write(b []byte) (n int, err error) + + // Close closes the connection. + // Any blocked Read or Write operations will be unblocked and return errors. + // Close may or may not block until any buffered data is sent; + // for TCP connections see [*TCPConn.SetLinger]. + Close() error + + // LocalAddr returns the local network address, if known. + LocalAddr() Addr + + // RemoteAddr returns the remote network address, if known. + RemoteAddr() Addr + + // SetDeadline sets the read and write deadlines associated + // with the connection. It is equivalent to calling both + // SetReadDeadline and SetWriteDeadline. + // + // A deadline is an absolute time after which I/O operations + // fail instead of blocking. The deadline applies to all future + // and pending I/O, not just the immediately following call to + // Read or Write. After a deadline has been exceeded, the + // connection can be refreshed by setting a deadline in the future. + // + // If the deadline is exceeded a call to Read or Write or to other + // I/O methods will return an error that wraps os.ErrDeadlineExceeded. + // This can be tested using errors.Is(err, os.ErrDeadlineExceeded). + // The error's Timeout method will return true, but note that there + // are other possible errors for which the Timeout method will + // return true even if the deadline has not been exceeded. + // + // An idle timeout can be implemented by repeatedly extending + // the deadline after successful Read or Write calls. + // + // A zero value for t means I/O operations will not time out. + SetDeadline(t time.Time) error + + // SetReadDeadline sets the deadline for future Read calls + // and any currently-blocked Read call. + // A zero value for t means Read will not time out. + SetReadDeadline(t time.Time) error + + // SetWriteDeadline sets the deadline for future Write calls + // and any currently-blocked Write call. + // Even if write times out, it may return n > 0, indicating that + // some of the data was successfully written. + // A zero value for t means Write will not time out. + SetWriteDeadline(t time.Time) error +} + +type conn struct { + fd *netFD +} + +func (c *conn) ok() bool { return c != nil && c.fd != nil } + +// Implementation of the Conn interface. + +// Read implements the Conn Read method. +func (c *conn) Read(b []byte) (int, error) { + if !c.ok() { + return 0, syscall.EINVAL + } + n, err := c.fd.Read(b) + if err != nil && err != io.EOF { + err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return n, err +} + +// Write implements the Conn Write method. +func (c *conn) Write(b []byte) (int, error) { + if !c.ok() { + return 0, syscall.EINVAL + } + n, err := c.fd.Write(b) + if err != nil { + err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return n, err +} + +// Close closes the connection. +func (c *conn) Close() error { + if !c.ok() { + return syscall.EINVAL + } + err := c.fd.Close() + if err != nil { + err = &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return err +} + +// LocalAddr returns the local network address. +// The Addr returned is shared by all invocations of LocalAddr, so +// do not modify it. +func (c *conn) LocalAddr() Addr { + if !c.ok() { + return nil + } + return c.fd.laddr +} + +// RemoteAddr returns the remote network address. +// The Addr returned is shared by all invocations of RemoteAddr, so +// do not modify it. +func (c *conn) RemoteAddr() Addr { + if !c.ok() { + return nil + } + return c.fd.raddr +} + +// SetDeadline implements the Conn SetDeadline method. +func (c *conn) SetDeadline(t time.Time) error { + if !c.ok() { + return syscall.EINVAL + } + if err := c.fd.SetDeadline(t); err != nil { + return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err} + } + return nil +} + +// SetReadDeadline implements the Conn SetReadDeadline method. +func (c *conn) SetReadDeadline(t time.Time) error { + if !c.ok() { + return syscall.EINVAL + } + if err := c.fd.SetReadDeadline(t); err != nil { + return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err} + } + return nil +} + +// SetWriteDeadline implements the Conn SetWriteDeadline method. +func (c *conn) SetWriteDeadline(t time.Time) error { + if !c.ok() { + return syscall.EINVAL + } + if err := c.fd.SetWriteDeadline(t); err != nil { + return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err} + } + return nil +} + +// SetReadBuffer sets the size of the operating system's +// receive buffer associated with the connection. +func (c *conn) SetReadBuffer(bytes int) error { + if !c.ok() { + return syscall.EINVAL + } + if err := setReadBuffer(c.fd, bytes); err != nil { + return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err} + } + return nil +} + +// SetWriteBuffer sets the size of the operating system's +// transmit buffer associated with the connection. +func (c *conn) SetWriteBuffer(bytes int) error { + if !c.ok() { + return syscall.EINVAL + } + if err := setWriteBuffer(c.fd, bytes); err != nil { + return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err} + } + return nil +} + +// File returns a copy of the underlying [os.File]. +// It is the caller's responsibility to close f when finished. +// Closing c does not affect f, and closing f does not affect c. +// +// The returned os.File's file descriptor is different from the connection's. +// Attempting to change properties of the original using this duplicate +// may or may not have the desired effect. +// +// On Windows, the returned os.File's file descriptor is not usable +// on other processes. +func (c *conn) File() (f *os.File, err error) { + f, err = c.fd.dup() + if err != nil { + err = &OpError{Op: "file", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return +} + +// PacketConn is a generic packet-oriented network connection. +// +// Multiple goroutines may invoke methods on a PacketConn simultaneously. +type PacketConn interface { + // ReadFrom reads a packet from the connection, + // copying the payload into p. It returns the number of + // bytes copied into p and the return address that + // was on the packet. + // It returns the number of bytes read (0 <= n <= len(p)) + // and any error encountered. Callers should always process + // the n > 0 bytes returned before considering the error err. + // ReadFrom can be made to time out and return an error after a + // fixed time limit; see SetDeadline and SetReadDeadline. + ReadFrom(p []byte) (n int, addr Addr, err error) + + // WriteTo writes a packet with payload p to addr. + // WriteTo can be made to time out and return an Error after a + // fixed time limit; see SetDeadline and SetWriteDeadline. + // On packet-oriented connections, write timeouts are rare. + WriteTo(p []byte, addr Addr) (n int, err error) + + // Close closes the connection. + // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors. + Close() error + + // LocalAddr returns the local network address, if known. + LocalAddr() Addr + + // SetDeadline sets the read and write deadlines associated + // with the connection. It is equivalent to calling both + // SetReadDeadline and SetWriteDeadline. + // + // A deadline is an absolute time after which I/O operations + // fail instead of blocking. The deadline applies to all future + // and pending I/O, not just the immediately following call to + // Read or Write. After a deadline has been exceeded, the + // connection can be refreshed by setting a deadline in the future. + // + // If the deadline is exceeded a call to Read or Write or to other + // I/O methods will return an error that wraps os.ErrDeadlineExceeded. + // This can be tested using errors.Is(err, os.ErrDeadlineExceeded). + // The error's Timeout method will return true, but note that there + // are other possible errors for which the Timeout method will + // return true even if the deadline has not been exceeded. + // + // An idle timeout can be implemented by repeatedly extending + // the deadline after successful ReadFrom or WriteTo calls. + // + // A zero value for t means I/O operations will not time out. + SetDeadline(t time.Time) error + + // SetReadDeadline sets the deadline for future ReadFrom calls + // and any currently-blocked ReadFrom call. + // A zero value for t means ReadFrom will not time out. + SetReadDeadline(t time.Time) error + + // SetWriteDeadline sets the deadline for future WriteTo calls + // and any currently-blocked WriteTo call. + // Even if write times out, it may return n > 0, indicating that + // some of the data was successfully written. + // A zero value for t means WriteTo will not time out. + SetWriteDeadline(t time.Time) error +} + +var listenerBacklogCache struct { + sync.Once + val int +} + +// listenerBacklog is a caching wrapper around maxListenerBacklog. +// +// listenerBacklog should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/database64128/tfo-go/v2 +// - github.com/metacubex/tfo-go +// - github.com/sagernet/tfo-go +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname listenerBacklog +func listenerBacklog() int { + listenerBacklogCache.Do(func() { listenerBacklogCache.val = maxListenerBacklog() }) + return listenerBacklogCache.val +} + +// A Listener is a generic network listener for stream-oriented protocols. +// +// Multiple goroutines may invoke methods on a Listener simultaneously. +type Listener interface { + // Accept waits for and returns the next connection to the listener. + Accept() (Conn, error) + + // Close closes the listener. + // Any blocked Accept operations will be unblocked and return errors. + Close() error + + // Addr returns the listener's network address. + Addr() Addr +} + +// An Error represents a network error. +type Error interface { + error + Timeout() bool // Is the error a timeout? + + // Deprecated: Temporary errors are not well-defined. + // Most "temporary" errors are timeouts, and the few exceptions are surprising. + // Do not use this method. + Temporary() bool +} + +// Various errors contained in OpError. +var ( + // For connection setup operations. + errNoSuitableAddress = errors.New("no suitable address found") + + // For connection setup and write operations. + errMissingAddress = errors.New("missing address") + + // For both read and write operations. + errCanceled = canceledError{} + ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection") +) + +// canceledError lets us return the same error string we have always +// returned, while still being Is context.Canceled. +type canceledError struct{} + +func (canceledError) Error() string { return "operation was canceled" } + +func (canceledError) Is(err error) bool { return err == context.Canceled } + +// mapErr maps from the context errors to the historical internal net +// error values. +func mapErr(err error) error { + switch err { + case context.Canceled: + return errCanceled + case context.DeadlineExceeded: + return errTimeout + default: + return err + } +} + +// OpError is the error type usually returned by functions in the net +// package. It describes the operation, network type, and address of +// an error. +type OpError struct { + // Op is the operation which caused the error, such as + // "read" or "write". + Op string + + // Net is the network type on which this error occurred, + // such as "tcp" or "udp6". + Net string + + // For operations involving a remote network connection, like + // Dial, Read, or Write, Source is the corresponding local + // network address. + Source Addr + + // Addr is the network address for which this error occurred. + // For local operations, like Listen or SetDeadline, Addr is + // the address of the local endpoint being manipulated. + // For operations involving a remote network connection, like + // Dial, Read, or Write, Addr is the remote address of that + // connection. + Addr Addr + + // Err is the error that occurred during the operation. + // The Error method panics if the error is nil. + Err error +} + +func (e *OpError) Unwrap() error { return e.Err } + +func (e *OpError) Error() string { + if e == nil { + return "" + } + s := e.Op + if e.Net != "" { + s += " " + e.Net + } + if e.Source != nil { + s += " " + e.Source.String() + } + if e.Addr != nil { + if e.Source != nil { + s += "->" + } else { + s += " " + } + s += e.Addr.String() + } + s += ": " + e.Err.Error() + return s +} + +var ( + // aLongTimeAgo is a non-zero time, far in the past, used for + // immediate cancellation of dials. + aLongTimeAgo = time.Unix(1, 0) + + // noDeadline and noCancel are just zero values for + // readability with functions taking too many parameters. + noDeadline = time.Time{} + noCancel = (chan struct{})(nil) +) + +type timeout interface { + Timeout() bool +} + +func (e *OpError) Timeout() bool { + if ne, ok := e.Err.(*os.SyscallError); ok { + t, ok := ne.Err.(timeout) + return ok && t.Timeout() + } + t, ok := e.Err.(timeout) + return ok && t.Timeout() +} + +type temporary interface { + Temporary() bool +} + +func (e *OpError) Temporary() bool { + // Treat ECONNRESET and ECONNABORTED as temporary errors when + // they come from calling accept. See issue 6163. + if e.Op == "accept" && isConnError(e.Err) { + return true + } + + if ne, ok := e.Err.(*os.SyscallError); ok { + t, ok := ne.Err.(temporary) + return ok && t.Temporary() + } + t, ok := e.Err.(temporary) + return ok && t.Temporary() +} + +// A ParseError is the error type of literal network address parsers. +type ParseError struct { + // Type is the type of string that was expected, such as + // "IP address", "CIDR address". + Type string + + // Text is the malformed text string. + Text string +} + +func (e *ParseError) Error() string { return "invalid " + e.Type + ": " + e.Text } + +func (e *ParseError) Timeout() bool { return false } +func (e *ParseError) Temporary() bool { return false } + +type AddrError struct { + Err string + Addr string +} + +func (e *AddrError) Error() string { + if e == nil { + return "" + } + s := e.Err + if e.Addr != "" { + s = "address " + e.Addr + ": " + s + } + return s +} + +func (e *AddrError) Timeout() bool { return false } +func (e *AddrError) Temporary() bool { return false } + +type UnknownNetworkError string + +func (e UnknownNetworkError) Error() string { return "unknown network " + string(e) } +func (e UnknownNetworkError) Timeout() bool { return false } +func (e UnknownNetworkError) Temporary() bool { return false } + +type InvalidAddrError string + +func (e InvalidAddrError) Error() string { return string(e) } +func (e InvalidAddrError) Timeout() bool { return false } +func (e InvalidAddrError) Temporary() bool { return false } + +// errTimeout exists to return the historical "i/o timeout" string +// for context.DeadlineExceeded. See mapErr. +// It is also used when Dialer.Deadline is exceeded. +// error.Is(errTimeout, context.DeadlineExceeded) returns true. +// +// TODO(iant): We could consider changing this to os.ErrDeadlineExceeded +// in the future, if we make +// +// errors.Is(os.ErrDeadlineExceeded, context.DeadlineExceeded) +// +// return true. +var errTimeout error = &timeoutError{} + +type timeoutError struct{} + +func (e *timeoutError) Error() string { return "i/o timeout" } +func (e *timeoutError) Timeout() bool { return true } +func (e *timeoutError) Temporary() bool { return true } + +func (e *timeoutError) Is(err error) bool { + return err == context.DeadlineExceeded +} + +// DNSConfigError represents an error reading the machine's DNS configuration. +// (No longer used; kept for compatibility.) +type DNSConfigError struct { + Err error +} + +func (e *DNSConfigError) Unwrap() error { return e.Err } +func (e *DNSConfigError) Error() string { return "error reading DNS config: " + e.Err.Error() } +func (e *DNSConfigError) Timeout() bool { return false } +func (e *DNSConfigError) Temporary() bool { return false } + +// Various errors contained in DNSError. +var ( + errNoSuchHost = ¬FoundError{"no such host"} + errUnknownPort = ¬FoundError{"unknown port"} +) + +// notFoundError is a special error understood by the newDNSError function, +// which causes a creation of a DNSError with IsNotFound field set to true. +type notFoundError struct{ s string } + +func (e *notFoundError) Error() string { return e.s } + +// temporaryError is an error type that implements the [Error] interface. +// It returns true from the Temporary method. +type temporaryError struct{ s string } + +func (e *temporaryError) Error() string { return e.s } +func (e *temporaryError) Temporary() bool { return true } +func (e *temporaryError) Timeout() bool { return false } + +// DNSError represents a DNS lookup error. +type DNSError struct { + UnwrapErr error // error returned by the [DNSError.Unwrap] method, might be nil + Err string // description of the error + Name string // name looked for + Server string // server used + IsTimeout bool // if true, timed out; not all timeouts set this + IsTemporary bool // if true, error is temporary; not all errors set this + + // IsNotFound is set to true when the requested name does not + // contain any records of the requested type (data not found), + // or the name itself was not found (NXDOMAIN). + IsNotFound bool +} + +// newDNSError creates a new *DNSError. +// Based on the err, it sets the UnwrapErr, IsTimeout, IsTemporary, IsNotFound fields. +func newDNSError(err error, name, server string) *DNSError { + var ( + isTimeout bool + isTemporary bool + unwrapErr error + ) + + if err, ok := err.(Error); ok { + isTimeout = err.Timeout() + isTemporary = err.Temporary() + } + + // At this time, the only errors we wrap are context errors, to allow + // users to check for canceled/timed out requests. + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + unwrapErr = err + } + + _, isNotFound := err.(*notFoundError) + return &DNSError{ + UnwrapErr: unwrapErr, + Err: err.Error(), + Name: name, + Server: server, + IsTimeout: isTimeout, + IsTemporary: isTemporary, + IsNotFound: isNotFound, + } +} + +// Unwrap returns e.UnwrapErr. +func (e *DNSError) Unwrap() error { return e.UnwrapErr } + +func (e *DNSError) Error() string { + if e == nil { + return "" + } + s := "lookup " + e.Name + if e.Server != "" { + s += " on " + e.Server + } + s += ": " + e.Err + return s +} + +// Timeout reports whether the DNS lookup is known to have timed out. +// This is not always known; a DNS lookup may fail due to a timeout +// and return a [DNSError] for which Timeout returns false. +func (e *DNSError) Timeout() bool { return e.IsTimeout } + +// Temporary reports whether the DNS error is known to be temporary. +// This is not always known; a DNS lookup may fail due to a temporary +// error and return a [DNSError] for which Temporary returns false. +func (e *DNSError) Temporary() bool { return e.IsTimeout || e.IsTemporary } + +// errClosed exists just so that the docs for ErrClosed don't mention +// the internal package poll. +var errClosed = poll.ErrNetClosing + +// ErrClosed is the error returned by an I/O call on a network +// connection that has already been closed, or that is closed by +// another goroutine before the I/O is completed. This may be wrapped +// in another error, and should normally be tested using +// errors.Is(err, net.ErrClosed). +var ErrClosed error = errClosed + +// noReadFrom can be embedded alongside another type to +// hide the ReadFrom method of that other type. +type noReadFrom struct{} + +// ReadFrom hides another ReadFrom method. +// It should never be called. +func (noReadFrom) ReadFrom(io.Reader) (int64, error) { + panic("can't happen") +} + +// tcpConnWithoutReadFrom implements all the methods of *TCPConn other +// than ReadFrom. This is used to permit ReadFrom to call io.Copy +// without leading to a recursive call to ReadFrom. +type tcpConnWithoutReadFrom struct { + noReadFrom + *TCPConn +} + +// Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't +// applicable. +func genericReadFrom(c *TCPConn, r io.Reader) (n int64, err error) { + // Use wrapper to hide existing r.ReadFrom from io.Copy. + return io.Copy(tcpConnWithoutReadFrom{TCPConn: c}, r) +} + +// noWriteTo can be embedded alongside another type to +// hide the WriteTo method of that other type. +type noWriteTo struct{} + +// WriteTo hides another WriteTo method. +// It should never be called. +func (noWriteTo) WriteTo(io.Writer) (int64, error) { + panic("can't happen") +} + +// tcpConnWithoutWriteTo implements all the methods of *TCPConn other +// than WriteTo. This is used to permit WriteTo to call io.Copy +// without leading to a recursive call to WriteTo. +type tcpConnWithoutWriteTo struct { + noWriteTo + *TCPConn +} + +// Fallback implementation of io.WriterTo's WriteTo, when zero-copy isn't applicable. +func genericWriteTo(c *TCPConn, w io.Writer) (n int64, err error) { + // Use wrapper to hide existing w.WriteTo from io.Copy. + return io.Copy(w, tcpConnWithoutWriteTo{TCPConn: c}) +} + +// Limit the number of concurrent cgo-using goroutines, because +// each will block an entire operating system thread. The usual culprit +// is resolving many DNS names in separate goroutines but the DNS +// server is not responding. Then the many lookups each use a different +// thread, and the system or the program runs out of threads. + +var threadLimit chan struct{} + +var threadOnce sync.Once + +func acquireThread(ctx context.Context) error { + threadOnce.Do(func() { + threadLimit = make(chan struct{}, concurrentThreadsLimit()) + }) + select { + case threadLimit <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func releaseThread() { + <-threadLimit +} + +// buffersWriter is the interface implemented by Conns that support a +// "writev"-like batch write optimization. +// writeBuffers should fully consume and write all chunks from the +// provided Buffers, else it should report a non-nil error. +type buffersWriter interface { + writeBuffers(*Buffers) (int64, error) +} + +// Buffers contains zero or more runs of bytes to write. +// +// On certain machines, for certain types of connections, this is +// optimized into an OS-specific batch write operation (such as +// "writev"). +type Buffers [][]byte + +var ( + _ io.WriterTo = (*Buffers)(nil) + _ io.Reader = (*Buffers)(nil) +) + +// WriteTo writes contents of the buffers to w. +// +// WriteTo implements [io.WriterTo] for [Buffers]. +// +// WriteTo modifies the slice v as well as v[i] for 0 <= i < len(v), +// but does not modify v[i][j] for any i, j. +func (v *Buffers) WriteTo(w io.Writer) (n int64, err error) { + if wv, ok := w.(buffersWriter); ok { + return wv.writeBuffers(v) + } + for _, b := range *v { + nb, err := w.Write(b) + n += int64(nb) + if err != nil { + v.consume(n) + return n, err + } + } + v.consume(n) + return n, nil +} + +// Read from the buffers. +// +// Read implements [io.Reader] for [Buffers]. +// +// Read modifies the slice v as well as v[i] for 0 <= i < len(v), +// but does not modify v[i][j] for any i, j. +func (v *Buffers) Read(p []byte) (n int, err error) { + for len(p) > 0 && len(*v) > 0 { + n0 := copy(p, (*v)[0]) + v.consume(int64(n0)) + p = p[n0:] + n += n0 + } + if len(*v) == 0 { + err = io.EOF + } + return +} + +func (v *Buffers) consume(n int64) { + for len(*v) > 0 { + ln0 := int64(len((*v)[0])) + if ln0 > n { + (*v)[0] = (*v)[0][n:] + return + } + n -= ln0 + (*v)[0] = nil + *v = (*v)[1:] + } +} diff --git a/go/src/net/net_fake.go b/go/src/net/net_fake.go new file mode 100644 index 0000000000000000000000000000000000000000..cc35d90a26742fc3cd248f1cf2e96260ecbf7f45 --- /dev/null +++ b/go/src/net/net_fake.go @@ -0,0 +1,1165 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Fake networking for js/wasm and wasip1/wasm. +// It is intended to allow tests of other package to pass. + +//go:build js || wasip1 + +package net + +import ( + "context" + "errors" + "io" + "os" + "sync" + "sync/atomic" + "syscall" + "time" +) + +var ( + sockets sync.Map // fakeSockAddr → *netFD + fakePorts sync.Map // int (port #) → *netFD + nextPortCounter atomic.Int32 +) + +const defaultBuffer = 65535 + +type fakeSockAddr struct { + family int + address string +} + +func fakeAddr(sa sockaddr) fakeSockAddr { + return fakeSockAddr{ + family: sa.family(), + address: sa.String(), + } +} + +// socket returns a network file descriptor that is ready for +// I/O using the fake network. +func socket(ctx context.Context, net string, family, sotype, proto int, ipv6only bool, laddr, raddr sockaddr, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) (*netFD, error) { + if raddr != nil && ctrlCtxFn != nil { + return nil, os.NewSyscallError("socket", syscall.ENOTSUP) + } + switch sotype { + case syscall.SOCK_STREAM, syscall.SOCK_SEQPACKET, syscall.SOCK_DGRAM: + default: + return nil, os.NewSyscallError("socket", syscall.ENOTSUP) + } + + fd := &netFD{ + family: family, + sotype: sotype, + net: net, + } + fd.fakeNetFD = newFakeNetFD(fd) + + if raddr == nil { + if err := fakeListen(fd, laddr); err != nil { + fd.Close() + return nil, err + } + return fd, nil + } + + if err := fakeConnect(ctx, fd, laddr, raddr); err != nil { + fd.Close() + return nil, err + } + return fd, nil +} + +func validateResolvedAddr(net string, family int, sa sockaddr) error { + validateIP := func(ip IP) error { + switch family { + case syscall.AF_INET: + if len(ip) != 4 { + return &AddrError{ + Err: "non-IPv4 address", + Addr: ip.String(), + } + } + case syscall.AF_INET6: + if len(ip) != 16 { + return &AddrError{ + Err: "non-IPv6 address", + Addr: ip.String(), + } + } + default: + panic("net: unexpected address family in validateResolvedAddr") + } + return nil + } + + switch net { + case "tcp", "tcp4", "tcp6": + sa, ok := sa.(*TCPAddr) + if !ok { + return &AddrError{ + Err: "non-TCP address for " + net + " network", + Addr: sa.String(), + } + } + if err := validateIP(sa.IP); err != nil { + return err + } + if sa.Port <= 0 || sa.Port >= 1<<16 { + return &AddrError{ + Err: "port out of range", + Addr: sa.String(), + } + } + return nil + + case "udp", "udp4", "udp6": + sa, ok := sa.(*UDPAddr) + if !ok { + return &AddrError{ + Err: "non-UDP address for " + net + " network", + Addr: sa.String(), + } + } + if err := validateIP(sa.IP); err != nil { + return err + } + if sa.Port <= 0 || sa.Port >= 1<<16 { + return &AddrError{ + Err: "port out of range", + Addr: sa.String(), + } + } + return nil + + case "unix", "unixgram", "unixpacket": + sa, ok := sa.(*UnixAddr) + if !ok { + return &AddrError{ + Err: "non-Unix address for " + net + " network", + Addr: sa.String(), + } + } + if sa.Name != "" { + i := len(sa.Name) - 1 + for i > 0 && !os.IsPathSeparator(sa.Name[i]) { + i-- + } + for i > 0 && os.IsPathSeparator(sa.Name[i]) { + i-- + } + if i <= 0 { + return &AddrError{ + Err: "unix socket name missing path component", + Addr: sa.Name, + } + } + if _, err := os.Stat(sa.Name[:i+1]); err != nil { + return &AddrError{ + Err: err.Error(), + Addr: sa.Name, + } + } + } + return nil + + default: + return &AddrError{ + Err: syscall.EAFNOSUPPORT.Error(), + Addr: sa.String(), + } + } +} + +func matchIPFamily(family int, addr sockaddr) sockaddr { + convertIP := func(ip IP) IP { + switch family { + case syscall.AF_INET: + return ip.To4() + case syscall.AF_INET6: + return ip.To16() + default: + return ip + } + } + + switch addr := addr.(type) { + case *TCPAddr: + ip := convertIP(addr.IP) + if ip == nil || len(ip) == len(addr.IP) { + return addr + } + return &TCPAddr{IP: ip, Port: addr.Port, Zone: addr.Zone} + case *UDPAddr: + ip := convertIP(addr.IP) + if ip == nil || len(ip) == len(addr.IP) { + return addr + } + return &UDPAddr{IP: ip, Port: addr.Port, Zone: addr.Zone} + default: + return addr + } +} + +type fakeNetFD struct { + fd *netFD + assignedPort int // 0 if no port has been assigned for this socket + + queue *packetQueue // incoming packets + peer *netFD // connected peer (for outgoing packets); nil for listeners and PacketConns + readDeadline atomic.Pointer[deadlineTimer] + writeDeadline atomic.Pointer[deadlineTimer] + + fakeAddr fakeSockAddr // cached fakeSockAddr equivalent of fd.laddr + + // The incoming channels hold incoming connections that have not yet been accepted. + // All of these channels are 1-buffered. + incoming chan []*netFD // holds the queue when it has >0 but = q.readBufferBytes: + pq.full <- q + case q.head == nil: + if q.nBytes > 0 { + defer panic("net: put with nil packet list and nonzero nBytes") + } + pq.empty <- q + default: + pq.ready <- q + } +} + +func (pq *packetQueue) closeRead() error { + q := pq.get() + q.readClosed = true + pq.put(q) + return nil +} + +func (pq *packetQueue) closeWrite() error { + q := pq.get() + q.writeClosed = true + pq.put(q) + return nil +} + +func (pq *packetQueue) setLinger(linger bool) error { + q := pq.get() + defer func() { pq.put(q) }() + + if q.writeClosed { + return ErrClosed + } + q.noLinger = !linger + return nil +} + +func (pq *packetQueue) write(dt *deadlineTimer, b []byte, from sockaddr) (n int, err error) { + for { + dn := len(b) + if dn > maxPacketSize { + dn = maxPacketSize + } + + dn, err = pq.send(dt, b[:dn], from, true) + n += dn + if err != nil { + return n, err + } + + b = b[dn:] + if len(b) == 0 { + return n, nil + } + } +} + +func (pq *packetQueue) send(dt *deadlineTimer, b []byte, from sockaddr, block bool) (n int, err error) { + if from == nil { + return 0, os.NewSyscallError("send", syscall.EINVAL) + } + if len(b) > maxPacketSize { + return 0, os.NewSyscallError("send", syscall.EMSGSIZE) + } + + var q packetQueueState + var full chan packetQueueState + if !block { + full = pq.full + } + + select { + case <-dt.expired: + return 0, os.ErrDeadlineExceeded + + case q = <-full: + pq.put(q) + return 0, os.NewSyscallError("send", syscall.ENOBUFS) + + case q = <-pq.empty: + case q = <-pq.ready: + } + defer func() { pq.put(q) }() + + // Don't allow a packet to be sent if the deadline has expired, + // even if the select above chose a different branch. + select { + case <-dt.expired: + return 0, os.ErrDeadlineExceeded + default: + } + if q.writeClosed { + return 0, ErrClosed + } else if q.readClosed && q.nBytes >= q.readBufferBytes { + return 0, os.NewSyscallError("send", syscall.ECONNRESET) + } + + p := packetPool.Get().(*packet) + p.buf = append(p.buf[:0], b...) + p.from = from + + if q.head == nil { + q.head = p + } else { + q.tail.next = p + } + q.tail = p + q.nBytes += len(p.buf) + + return len(b), nil +} + +func (pq *packetQueue) recvfrom(dt *deadlineTimer, b []byte, wholePacket bool, checkFrom func(sockaddr) error) (n int, from sockaddr, err error) { + var q packetQueueState + var empty chan packetQueueState + if len(b) == 0 { + // For consistency with the implementation on Unix platforms, + // allow a zero-length Read to proceed if the queue is empty. + // (Without this, TestZeroByteRead deadlocks.) + empty = pq.empty + } + + select { + case <-dt.expired: + return 0, nil, os.ErrDeadlineExceeded + case q = <-empty: + case q = <-pq.ready: + case q = <-pq.full: + } + defer func() { pq.put(q) }() + + if q.readClosed { + return 0, nil, ErrClosed + } + + p := q.head + if p == nil { + switch { + case q.writeClosed: + if q.noLinger { + return 0, nil, os.NewSyscallError("recvfrom", syscall.ECONNRESET) + } + return 0, nil, io.EOF + case len(b) == 0: + return 0, nil, nil + default: + // This should be impossible: pq.full should only contain a non-empty list, + // pq.ready should either contain a non-empty list or indicate that the + // connection is closed, and we should only receive from pq.empty if + // len(b) == 0. + panic("net: nil packet list from non-closed packetQueue") + } + } + + select { + case <-dt.expired: + return 0, nil, os.ErrDeadlineExceeded + default: + } + + if checkFrom != nil { + if err := checkFrom(p.from); err != nil { + return 0, nil, err + } + } + + n = copy(b, p.buf[p.bufOffset:]) + from = p.from + if wholePacket || p.bufOffset+n == len(p.buf) { + q.head = p.next + q.nBytes -= len(p.buf) + p.clear() + packetPool.Put(p) + } else { + p.bufOffset += n + } + + return n, from, nil +} + +// setReadBuffer sets a soft limit on the number of bytes available to read +// from the pipe. +func (pq *packetQueue) setReadBuffer(bytes int) error { + if bytes <= 0 { + return os.NewSyscallError("setReadBuffer", syscall.EINVAL) + } + q := pq.get() // Use the queue as a lock. + q.readBufferBytes = bytes + pq.put(q) + return nil +} + +type deadlineTimer struct { + timer chan *time.Timer + expired chan struct{} +} + +func newDeadlineTimer(deadline time.Time) *deadlineTimer { + dt := &deadlineTimer{ + timer: make(chan *time.Timer, 1), + expired: make(chan struct{}), + } + dt.timer <- nil + dt.Reset(deadline) + return dt +} + +// Reset attempts to reset the timer. +// If the timer has already expired, Reset returns false. +func (dt *deadlineTimer) Reset(deadline time.Time) bool { + timer := <-dt.timer + defer func() { dt.timer <- timer }() + + if deadline.Equal(noDeadline) { + if timer != nil && timer.Stop() { + timer = nil + } + return timer == nil + } + + d := time.Until(deadline) + if d < 0 { + // Ensure that a deadline in the past takes effect immediately. + defer func() { <-dt.expired }() + } + + if timer == nil { + timer = time.AfterFunc(d, func() { close(dt.expired) }) + return true + } + if !timer.Stop() { + return false + } + timer.Reset(d) + return true +} + +func sysSocket(family, sotype, proto int) (int, error) { + return 0, os.NewSyscallError("sysSocket", syscall.ENOSYS) +} + +func fakeListen(fd *netFD, laddr sockaddr) (err error) { + wrapErr := func(err error) error { + if errno, ok := err.(syscall.Errno); ok { + err = os.NewSyscallError("listen", errno) + } + if errors.Is(err, syscall.EADDRINUSE) { + return err + } + if laddr != nil { + if _, ok := err.(*AddrError); !ok { + err = &AddrError{ + Err: err.Error(), + Addr: laddr.String(), + } + } + } + return err + } + + ffd := newFakeNetFD(fd) + defer func() { + if fd.fakeNetFD != ffd { + // Failed to register listener; clean up. + ffd.Close() + } + }() + + if err := ffd.assignFakeAddr(matchIPFamily(fd.family, laddr)); err != nil { + return wrapErr(err) + } + + ffd.fakeAddr = fakeAddr(fd.laddr.(sockaddr)) + switch fd.sotype { + case syscall.SOCK_STREAM, syscall.SOCK_SEQPACKET: + ffd.incoming = make(chan []*netFD, 1) + ffd.incomingFull = make(chan []*netFD, 1) + ffd.incomingEmpty = make(chan bool, 1) + ffd.incomingEmpty <- true + case syscall.SOCK_DGRAM: + ffd.queue = newPacketQueue(defaultBuffer) + default: + return wrapErr(syscall.EINVAL) + } + + fd.fakeNetFD = ffd + if _, dup := sockets.LoadOrStore(ffd.fakeAddr, fd); dup { + fd.fakeNetFD = nil + return wrapErr(syscall.EADDRINUSE) + } + + return nil +} + +func fakeConnect(ctx context.Context, fd *netFD, laddr, raddr sockaddr) error { + wrapErr := func(err error) error { + if errno, ok := err.(syscall.Errno); ok { + err = os.NewSyscallError("connect", errno) + } + if errors.Is(err, syscall.EADDRINUSE) { + return err + } + if terr, ok := err.(interface{ Timeout() bool }); !ok || !terr.Timeout() { + // For consistency with the net implementation on other platforms, + // if we don't need to preserve the Timeout-ness of err we should + // wrap it in an AddrError. (Unfortunately we can't wrap errors + // that convey structured information, because AddrError reduces + // the wrapped Err to a flat string.) + if _, ok := err.(*AddrError); !ok { + err = &AddrError{ + Err: err.Error(), + Addr: raddr.String(), + } + } + } + return err + } + + if fd.isConnected { + return wrapErr(syscall.EISCONN) + } + if ctx.Err() != nil { + return wrapErr(syscall.ETIMEDOUT) + } + + fd.raddr = matchIPFamily(fd.family, raddr) + if err := validateResolvedAddr(fd.net, fd.family, fd.raddr.(sockaddr)); err != nil { + return wrapErr(err) + } + + if err := fd.fakeNetFD.assignFakeAddr(laddr); err != nil { + return wrapErr(err) + } + fd.fakeNetFD.queue = newPacketQueue(defaultBuffer) + + switch fd.sotype { + case syscall.SOCK_DGRAM: + if ua, ok := fd.laddr.(*UnixAddr); !ok || ua.Name != "" { + fd.fakeNetFD.fakeAddr = fakeAddr(fd.laddr.(sockaddr)) + if _, dup := sockets.LoadOrStore(fd.fakeNetFD.fakeAddr, fd); dup { + return wrapErr(syscall.EADDRINUSE) + } + } + fd.isConnected = true + return nil + + case syscall.SOCK_STREAM, syscall.SOCK_SEQPACKET: + default: + return wrapErr(syscall.EINVAL) + } + + fa := fakeAddr(raddr) + lni, ok := sockets.Load(fa) + if !ok { + return wrapErr(syscall.ECONNREFUSED) + } + ln := lni.(*netFD) + if ln.sotype != fd.sotype { + return wrapErr(syscall.EPROTOTYPE) + } + if ln.incoming == nil { + return wrapErr(syscall.ECONNREFUSED) + } + + peer := &netFD{ + family: ln.family, + sotype: ln.sotype, + net: ln.net, + laddr: ln.laddr, + raddr: fd.laddr, + isConnected: true, + } + peer.fakeNetFD = newFakeNetFD(fd) + peer.fakeNetFD.queue = newPacketQueue(defaultBuffer) + defer func() { + if fd.peer != peer { + // Failed to connect; clean up. + peer.Close() + } + }() + + var incoming []*netFD + select { + case <-ctx.Done(): + return wrapErr(syscall.ETIMEDOUT) + case ok = <-ln.incomingEmpty: + case incoming, ok = <-ln.incoming: + } + if !ok { + return wrapErr(syscall.ECONNREFUSED) + } + + fd.isConnected = true + fd.peer = peer + peer.peer = fd + + incoming = append(incoming, peer) + if len(incoming) >= listenerBacklog() { + ln.incomingFull <- incoming + } else { + ln.incoming <- incoming + } + return nil +} + +func (ffd *fakeNetFD) assignFakeAddr(addr sockaddr) error { + validate := func(sa sockaddr) error { + if err := validateResolvedAddr(ffd.fd.net, ffd.fd.family, sa); err != nil { + return err + } + ffd.fd.laddr = sa + return nil + } + + assignIP := func(addr sockaddr) error { + var ( + ip IP + port int + zone string + ) + switch addr := addr.(type) { + case *TCPAddr: + if addr != nil { + ip = addr.IP + port = addr.Port + zone = addr.Zone + } + case *UDPAddr: + if addr != nil { + ip = addr.IP + port = addr.Port + zone = addr.Zone + } + default: + return validate(addr) + } + + if ip == nil { + ip = IPv4(127, 0, 0, 1) + } + switch ffd.fd.family { + case syscall.AF_INET: + if ip4 := ip.To4(); ip4 != nil { + ip = ip4 + } + case syscall.AF_INET6: + if ip16 := ip.To16(); ip16 != nil { + ip = ip16 + } + } + if ip == nil { + return syscall.EINVAL + } + + if port == 0 { + var prevPort int32 + portWrapped := false + nextPort := func() (int, bool) { + for { + port := nextPortCounter.Add(1) + if port <= 0 || port >= 1<<16 { + // nextPortCounter ran off the end of the port space. + // Bump it back into range. + for { + if nextPortCounter.CompareAndSwap(port, 0) { + break + } + if port = nextPortCounter.Load(); port >= 0 && port < 1<<16 { + break + } + } + if portWrapped { + // This is the second wraparound, so we've scanned the whole port space + // at least once already and it's time to give up. + return 0, false + } + portWrapped = true + prevPort = 0 + continue + } + + if port <= prevPort { + // nextPortCounter has wrapped around since the last time we read it. + if portWrapped { + // This is the second wraparound, so we've scanned the whole port space + // at least once already and it's time to give up. + return 0, false + } else { + portWrapped = true + } + } + + prevPort = port + return int(port), true + } + } + + for { + var ok bool + port, ok = nextPort() + if !ok { + ffd.assignedPort = 0 + return syscall.EADDRINUSE + } + + ffd.assignedPort = int(port) + if _, dup := fakePorts.LoadOrStore(ffd.assignedPort, ffd.fd); !dup { + break + } + } + } + + switch addr.(type) { + case *TCPAddr: + return validate(&TCPAddr{IP: ip, Port: port, Zone: zone}) + case *UDPAddr: + return validate(&UDPAddr{IP: ip, Port: port, Zone: zone}) + default: + panic("unreachable") + } + } + + switch ffd.fd.net { + case "tcp", "tcp4", "tcp6": + if addr == nil { + return assignIP(new(TCPAddr)) + } + return assignIP(addr) + + case "udp", "udp4", "udp6": + if addr == nil { + return assignIP(new(UDPAddr)) + } + return assignIP(addr) + + case "unix", "unixgram", "unixpacket": + uaddr, ok := addr.(*UnixAddr) + if !ok && addr != nil { + return &AddrError{ + Err: "non-Unix address for " + ffd.fd.net + " network", + Addr: addr.String(), + } + } + if uaddr == nil { + return validate(&UnixAddr{Net: ffd.fd.net}) + } + return validate(&UnixAddr{Net: ffd.fd.net, Name: uaddr.Name}) + + default: + return &AddrError{ + Err: syscall.EAFNOSUPPORT.Error(), + Addr: addr.String(), + } + } +} + +func (ffd *fakeNetFD) readFrom(p []byte) (n int, sa syscall.Sockaddr, err error) { + if ffd.queue == nil { + return 0, nil, os.NewSyscallError("readFrom", syscall.EINVAL) + } + + n, from, err := ffd.queue.recvfrom(ffd.readDeadline.Load(), p, true, nil) + + if from != nil { + // Convert the net.sockaddr to a syscall.Sockaddr type. + var saErr error + sa, saErr = from.sockaddr(ffd.fd.family) + if err == nil { + err = saErr + } + } + + return n, sa, err +} + +func (ffd *fakeNetFD) readFromInet4(p []byte, sa *syscall.SockaddrInet4) (n int, err error) { + n, _, err = ffd.queue.recvfrom(ffd.readDeadline.Load(), p, true, func(from sockaddr) error { + fromSA, err := from.sockaddr(syscall.AF_INET) + if err != nil { + return err + } + if fromSA == nil { + return os.NewSyscallError("readFromInet4", syscall.EINVAL) + } + *sa = *(fromSA.(*syscall.SockaddrInet4)) + return nil + }) + return n, err +} + +func (ffd *fakeNetFD) readFromInet6(p []byte, sa *syscall.SockaddrInet6) (n int, err error) { + n, _, err = ffd.queue.recvfrom(ffd.readDeadline.Load(), p, true, func(from sockaddr) error { + fromSA, err := from.sockaddr(syscall.AF_INET6) + if err != nil { + return err + } + if fromSA == nil { + return os.NewSyscallError("readFromInet6", syscall.EINVAL) + } + *sa = *(fromSA.(*syscall.SockaddrInet6)) + return nil + }) + return n, err +} + +func (ffd *fakeNetFD) readMsg(p []byte, oob []byte, flags int) (n, oobn, retflags int, sa syscall.Sockaddr, err error) { + if flags != 0 { + return 0, 0, 0, nil, os.NewSyscallError("readMsg", syscall.ENOTSUP) + } + n, sa, err = ffd.readFrom(p) + return n, 0, 0, sa, err +} + +func (ffd *fakeNetFD) readMsgInet4(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet4) (n, oobn, retflags int, err error) { + if flags != 0 { + return 0, 0, 0, os.NewSyscallError("readMsgInet4", syscall.ENOTSUP) + } + n, err = ffd.readFromInet4(p, sa) + return n, 0, 0, err +} + +func (ffd *fakeNetFD) readMsgInet6(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet6) (n, oobn, retflags int, err error) { + if flags != 0 { + return 0, 0, 0, os.NewSyscallError("readMsgInet6", syscall.ENOTSUP) + } + n, err = ffd.readFromInet6(p, sa) + return n, 0, 0, err +} + +func (ffd *fakeNetFD) writeMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) { + if len(oob) > 0 { + return 0, 0, os.NewSyscallError("writeMsg", syscall.ENOTSUP) + } + n, err = ffd.writeTo(p, sa) + return n, 0, err +} + +func (ffd *fakeNetFD) writeMsgInet4(p []byte, oob []byte, sa4 *syscall.SockaddrInet4) (n int, oobn int, err error) { + var sa syscall.Sockaddr + if sa4 != nil { + sa = sa4 + } + return ffd.writeMsg(p, oob, sa) +} + +func (ffd *fakeNetFD) writeMsgInet6(p []byte, oob []byte, sa6 *syscall.SockaddrInet6) (n int, oobn int, err error) { + var sa syscall.Sockaddr + if sa6 != nil { + sa = sa6 + } + return ffd.writeMsg(p, oob, sa) +} + +func (ffd *fakeNetFD) writeTo(p []byte, sa syscall.Sockaddr) (n int, err error) { + raddr := ffd.fd.raddr + if sa != nil { + if ffd.fd.isConnected { + return 0, os.NewSyscallError("writeTo", syscall.EISCONN) + } + raddr = ffd.fd.addrFunc()(sa) + } + if raddr == nil { + return 0, os.NewSyscallError("writeTo", syscall.EINVAL) + } + + peeri, _ := sockets.Load(fakeAddr(raddr.(sockaddr))) + if peeri == nil { + if len(ffd.fd.net) >= 3 && ffd.fd.net[:3] == "udp" { + return len(p), nil + } + return 0, os.NewSyscallError("writeTo", syscall.ECONNRESET) + } + peer := peeri.(*netFD) + if peer.queue == nil { + if len(ffd.fd.net) >= 3 && ffd.fd.net[:3] == "udp" { + return len(p), nil + } + return 0, os.NewSyscallError("writeTo", syscall.ECONNRESET) + } + + block := true + if len(ffd.fd.net) >= 3 && ffd.fd.net[:3] == "udp" { + block = false + } + return peer.queue.send(ffd.writeDeadline.Load(), p, ffd.fd.laddr.(sockaddr), block) +} + +func (ffd *fakeNetFD) writeToInet4(p []byte, sa *syscall.SockaddrInet4) (n int, err error) { + return ffd.writeTo(p, sa) +} + +func (ffd *fakeNetFD) writeToInet6(p []byte, sa *syscall.SockaddrInet6) (n int, err error) { + return ffd.writeTo(p, sa) +} + +func (ffd *fakeNetFD) dup() (f *os.File, err error) { + return nil, os.NewSyscallError("dup", syscall.ENOSYS) +} + +func (ffd *fakeNetFD) setReadBuffer(bytes int) error { + if ffd.queue == nil { + return os.NewSyscallError("setReadBuffer", syscall.EINVAL) + } + ffd.queue.setReadBuffer(bytes) + return nil +} + +func (ffd *fakeNetFD) setWriteBuffer(bytes int) error { + return os.NewSyscallError("setWriteBuffer", syscall.ENOTSUP) +} + +func (ffd *fakeNetFD) setLinger(sec int) error { + if sec < 0 || ffd.peer == nil { + return os.NewSyscallError("setLinger", syscall.EINVAL) + } + ffd.peer.queue.setLinger(sec > 0) + return nil +} diff --git a/go/src/net/net_fake_test.go b/go/src/net/net_fake_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4542228fbc5827f458dac13b033e29111467ddf3 --- /dev/null +++ b/go/src/net/net_fake_test.go @@ -0,0 +1,107 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js || wasip1 + +package net + +// GOOS=js and GOOS=wasip1 do not have typical socket networking capabilities +// found on other platforms. To help run test suites of the stdlib packages, +// an in-memory "fake network" facility is implemented. +// +// The tests in this files are intended to validate the behavior of the fake +// network stack on these platforms. + +import ( + "errors" + "syscall" + "testing" +) + +func TestFakePortExhaustion(t *testing.T) { + if testing.Short() { + t.Skipf("skipping test that opens 1<<16 connections") + } + + ln := newLocalListener(t, "tcp") + done := make(chan struct{}) + go func() { + var accepted []Conn + defer func() { + for _, c := range accepted { + c.Close() + } + close(done) + }() + + for { + c, err := ln.Accept() + if err != nil { + return + } + accepted = append(accepted, c) + } + }() + + var dialed []Conn + defer func() { + ln.Close() + for _, c := range dialed { + c.Close() + } + <-done + }() + + // Since this test is not running in parallel, we expect to be able to open + // all 65535 valid (fake) ports. The listener is already using one, so + // we should be able to Dial the remaining 65534. + for len(dialed) < (1<<16)-2 { + c, err := Dial(ln.Addr().Network(), ln.Addr().String()) + if err != nil { + t.Fatalf("unexpected error from Dial with %v connections: %v", len(dialed), err) + } + dialed = append(dialed, c) + if testing.Verbose() && len(dialed)%(1<<12) == 0 { + t.Logf("dialed %d connections", len(dialed)) + } + } + t.Logf("dialed %d connections", len(dialed)) + + // Now that all of the ports are in use, dialing another should fail due + // to port exhaustion, which (for POSIX-like socket APIs) should return + // an EADDRINUSE error. + c, err := Dial(ln.Addr().Network(), ln.Addr().String()) + if err == nil { + c.Close() + } + if errors.Is(err, syscall.EADDRINUSE) { + t.Logf("Dial returned expected error: %v", err) + } else { + t.Errorf("unexpected error from Dial: %v\nwant: %v", err, syscall.EADDRINUSE) + } + + // Opening a Listener should fail at this point too. + ln2, err := Listen("tcp", "localhost:0") + if err == nil { + ln2.Close() + } + if errors.Is(err, syscall.EADDRINUSE) { + t.Logf("Listen returned expected error: %v", err) + } else { + t.Errorf("unexpected error from Listen: %v\nwant: %v", err, syscall.EADDRINUSE) + } + + // When we close an arbitrary connection, we should be able to reuse its port + // even if the server hasn't yet seen the ECONNRESET for the connection. + dialed[0].Close() + dialed = dialed[1:] + t.Logf("closed one connection") + c, err = Dial(ln.Addr().Network(), ln.Addr().String()) + if err == nil { + c.Close() + t.Logf("Dial succeeded") + } else { + t.Errorf("unexpected error from Dial: %v", err) + } +} diff --git a/go/src/net/net_test.go b/go/src/net/net_test.go new file mode 100644 index 0000000000000000000000000000000000000000..637c95540f41bc805c664ab122120a54c44bb07a --- /dev/null +++ b/go/src/net/net_test.go @@ -0,0 +1,612 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "fmt" + "io" + "net/internal/socktest" + "os" + "runtime" + "sync" + "testing" + "time" +) + +func TestCloseRead(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + t.Parallel() + + for _, network := range []string{"tcp", "unix", "unixpacket"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("network %s is not testable on the current platform", network) + } + t.Parallel() + + ln := newLocalListener(t, network) + switch network { + case "unix", "unixpacket": + defer os.Remove(ln.Addr().String()) + } + defer ln.Close() + + c, err := Dial(ln.Addr().Network(), ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + switch network { + case "unix", "unixpacket": + defer os.Remove(c.LocalAddr().String()) + } + defer c.Close() + + switch c := c.(type) { + case *TCPConn: + err = c.CloseRead() + case *UnixConn: + err = c.CloseRead() + } + if err != nil { + if perr := parseCloseError(err, true); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + var b [1]byte + n, err := c.Read(b[:]) + if n != 0 || err == nil { + t.Fatalf("got (%d, %v); want (0, error)", n, err) + } + }) + } +} + +func TestCloseWrite(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + t.Parallel() + deadline, _ := t.Deadline() + if !deadline.IsZero() { + // Leave 10% headroom on the deadline to report errors and clean up. + deadline = deadline.Add(-time.Until(deadline) / 10) + } + + for _, network := range []string{"tcp", "unix", "unixpacket"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("network %s is not testable on the current platform", network) + } + t.Parallel() + + handler := func(ls *localServer, ln Listener) { + c, err := ln.Accept() + if err != nil { + t.Error(err) + return + } + + // Workaround for https://go.dev/issue/49352. + // On Windows and arm64 macOS (current as of macOS 12.4), + // reading from a socket at the same time as the client + // is closing it occasionally hangs for 60 seconds before + // returning ECONNRESET. Sleep for a bit to give the + // socket time to close before trying to read from it. + if runtime.GOOS == "windows" || (runtime.GOOS == "darwin" && runtime.GOARCH == "arm64") { + time.Sleep(10 * time.Millisecond) + } + + if !deadline.IsZero() { + c.SetDeadline(deadline) + } + defer c.Close() + + var b [1]byte + n, err := c.Read(b[:]) + if n != 0 || err != io.EOF { + t.Errorf("got (%d, %v); want (0, io.EOF)", n, err) + return + } + switch c := c.(type) { + case *TCPConn: + err = c.CloseWrite() + case *UnixConn: + err = c.CloseWrite() + } + if err != nil { + if perr := parseCloseError(err, true); perr != nil { + t.Error(perr) + } + t.Error(err) + return + } + n, err = c.Write(b[:]) + if err == nil { + t.Errorf("got (%d, %v); want (any, error)", n, err) + return + } + } + + ls := newLocalServer(t, network) + defer ls.teardown() + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + + c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + if !deadline.IsZero() { + c.SetDeadline(deadline) + } + switch network { + case "unix", "unixpacket": + defer os.Remove(c.LocalAddr().String()) + } + defer c.Close() + + switch c := c.(type) { + case *TCPConn: + err = c.CloseWrite() + case *UnixConn: + err = c.CloseWrite() + } + if err != nil { + if perr := parseCloseError(err, true); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + var b [1]byte + n, err := c.Read(b[:]) + if n != 0 || err != io.EOF { + t.Fatalf("got (%d, %v); want (0, io.EOF)", n, err) + } + n, err = c.Write(b[:]) + if err == nil { + t.Fatalf("got (%d, %v); want (any, error)", n, err) + } + }) + } +} + +func TestConnClose(t *testing.T) { + t.Parallel() + for _, network := range []string{"tcp", "unix", "unixpacket"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("network %s is not testable on the current platform", network) + } + t.Parallel() + + ln := newLocalListener(t, network) + switch network { + case "unix", "unixpacket": + defer os.Remove(ln.Addr().String()) + } + defer ln.Close() + + c, err := Dial(ln.Addr().Network(), ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + switch network { + case "unix", "unixpacket": + defer os.Remove(c.LocalAddr().String()) + } + defer c.Close() + + if err := c.Close(); err != nil { + if perr := parseCloseError(err, false); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + var b [1]byte + n, err := c.Read(b[:]) + if n != 0 || err == nil { + t.Fatalf("got (%d, %v); want (0, error)", n, err) + } + }) + } +} + +func TestListenerClose(t *testing.T) { + t.Parallel() + for _, network := range []string{"tcp", "unix", "unixpacket"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("network %s is not testable on the current platform", network) + } + t.Parallel() + + ln := newLocalListener(t, network) + switch network { + case "unix", "unixpacket": + defer os.Remove(ln.Addr().String()) + } + + if err := ln.Close(); err != nil { + if perr := parseCloseError(err, false); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + c, err := ln.Accept() + if err == nil { + c.Close() + t.Fatal("should fail") + } + + // Note: we cannot ensure that a subsequent Dial does not succeed, because + // we do not in general have any guarantee that ln.Addr is not immediately + // reused. (TCP sockets enter a TIME_WAIT state when closed, but that only + // applies to existing connections for the port — it does not prevent the + // port itself from being used for entirely new connections in the + // meantime.) + }) + } +} + +func TestPacketConnClose(t *testing.T) { + t.Parallel() + for _, network := range []string{"udp", "unixgram"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("network %s is not testable on the current platform", network) + } + t.Parallel() + + c := newLocalPacketListener(t, network) + switch network { + case "unixgram": + defer os.Remove(c.LocalAddr().String()) + } + defer c.Close() + + if err := c.Close(); err != nil { + if perr := parseCloseError(err, false); perr != nil { + t.Error(perr) + } + t.Fatal(err) + } + var b [1]byte + n, _, err := c.ReadFrom(b[:]) + if n != 0 || err == nil { + t.Fatalf("got (%d, %v); want (0, error)", n, err) + } + }) + } +} + +// See golang.org/issue/6163, golang.org/issue/6987. +func TestAcceptIgnoreAbortedConnRequest(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("%s does not have full support of socktest", runtime.GOOS) + } + + syserr := make(chan error) + go func() { + defer close(syserr) + for _, err := range abortedConnRequestErrors { + syserr <- err + } + }() + sw.Set(socktest.FilterAccept, func(so *socktest.Status) (socktest.AfterFilter, error) { + if err, ok := <-syserr; ok { + return nil, err + } + return nil, nil + }) + defer sw.Set(socktest.FilterAccept, nil) + + operr := make(chan error, 1) + handler := func(ls *localServer, ln Listener) { + defer close(operr) + c, err := ln.Accept() + if err != nil { + if perr := parseAcceptError(err); perr != nil { + operr <- perr + } + operr <- err + return + } + c.Close() + } + ls := newLocalServer(t, "tcp") + defer ls.teardown() + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + + c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + c.Close() + + for err := range operr { + t.Error(err) + } +} + +func TestZeroByteRead(t *testing.T) { + t.Parallel() + for _, network := range []string{"tcp", "unix", "unixpacket"} { + t.Run(network, func(t *testing.T) { + if !testableNetwork(network) { + t.Skipf("network %s is not testable on the current platform", network) + } + t.Parallel() + + ln := newLocalListener(t, network) + connc := make(chan Conn, 1) + defer func() { + ln.Close() + for c := range connc { + if c != nil { + c.Close() + } + } + }() + go func() { + defer close(connc) + c, err := ln.Accept() + if err != nil { + t.Error(err) + } + connc <- c // might be nil + }() + c, err := Dial(network, ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + sc := <-connc + if sc == nil { + return + } + defer sc.Close() + + if runtime.GOOS == "windows" { + // A zero byte read on Windows caused a wait for readability first. + // Rather than change that behavior, satisfy it in this test. + // See Issue 15735. + go io.WriteString(sc, "a") + } + + n, err := c.Read(nil) + if n != 0 || err != nil { + t.Errorf("%s: zero byte client read = %v, %v; want 0, nil", network, n, err) + } + + if runtime.GOOS == "windows" { + // Same as comment above. + go io.WriteString(c, "a") + } + n, err = sc.Read(nil) + if n != 0 || err != nil { + t.Errorf("%s: zero byte server read = %v, %v; want 0, nil", network, n, err) + } + }) + } +} + +// withTCPConnPair sets up a TCP connection between two peers, then +// runs peer1 and peer2 concurrently. withTCPConnPair returns when +// both have completed. +func withTCPConnPair(t *testing.T, peer1, peer2 func(c *TCPConn) error) { + t.Helper() + ln := newLocalListener(t, "tcp") + defer ln.Close() + errc := make(chan error, 2) + go func() { + c1, err := ln.Accept() + if err != nil { + errc <- err + return + } + err = peer1(c1.(*TCPConn)) + c1.Close() + errc <- err + }() + go func() { + c2, err := Dial("tcp", ln.Addr().String()) + if err != nil { + errc <- err + return + } + err = peer2(c2.(*TCPConn)) + c2.Close() + errc <- err + }() + for i := 0; i < 2; i++ { + if err := <-errc; err != nil { + t.Error(err) + } + } +} + +// Tests that a blocked Read is interrupted by a concurrent SetReadDeadline +// modifying that Conn's read deadline to the past. +// See golang.org/cl/30164 which documented this. The net/http package +// depends on this. +func TestReadTimeoutUnblocksRead(t *testing.T) { + serverDone := make(chan struct{}) + server := func(cs *TCPConn) error { + defer close(serverDone) + errc := make(chan error, 1) + go func() { + defer close(errc) + go func() { + // TODO: find a better way to wait + // until we're blocked in the cs.Read + // call below. Sleep is lame. + time.Sleep(100 * time.Millisecond) + + // Interrupt the upcoming Read, unblocking it: + cs.SetReadDeadline(time.Unix(123, 0)) // time in the past + }() + var buf [1]byte + n, err := cs.Read(buf[:1]) + if n != 0 || err == nil { + errc <- fmt.Errorf("Read = %v, %v; want 0, non-nil", n, err) + } + }() + select { + case err := <-errc: + return err + case <-time.After(5 * time.Second): + buf := make([]byte, 2<<20) + buf = buf[:runtime.Stack(buf, true)] + println("Stacks at timeout:\n", string(buf)) + return errors.New("timeout waiting for Read to finish") + } + + } + // Do nothing in the client. Never write. Just wait for the + // server's half to be done. + client := func(*TCPConn) error { + <-serverDone + return nil + } + withTCPConnPair(t, client, server) +} + +// Issue 17695: verify that a blocked Read is woken up by a Close. +func TestCloseUnblocksRead(t *testing.T) { + t.Parallel() + server := func(cs *TCPConn) error { + // Give the client time to get stuck in a Read: + time.Sleep(20 * time.Millisecond) + cs.Close() + return nil + } + client := func(ss *TCPConn) error { + n, err := ss.Read([]byte{0}) + if n != 0 || err != io.EOF { + return fmt.Errorf("Read = %v, %v; want 0, EOF", n, err) + } + return nil + } + withTCPConnPair(t, client, server) +} + +// Issue 72770: verify that a blocked UDP read is woken up by a Close. +func TestCloseUnblocksReadUDP(t *testing.T) { + t.Parallel() + var ( + mu sync.Mutex + done bool + ) + defer func() { + mu.Lock() + defer mu.Unlock() + done = true + }() + pc, err := ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + time.AfterFunc(250*time.Millisecond, func() { + mu.Lock() + defer mu.Unlock() + if done { + return + } + t.Logf("closing conn...") + pc.Close() + }) + timer := time.AfterFunc(time.Second*10, func() { + panic("timeout waiting for Close") + }) + defer timer.Stop() + + n, src, err := pc.(*UDPConn).ReadFromUDPAddrPort([]byte{}) + + // Check for n > 0. Checking err == nil alone isn't enough; + // on macOS, it returns (n=0, src=0.0.0.0:0, err=nil). + if n > 0 { + t.Fatalf("unexpected Read success from ReadFromUDPAddrPort; read %d bytes from %v, err=%v", n, src, err) + } + t.Logf("got expected UDP read error") +} + +// Issue 24808: verify that ECONNRESET is not temporary for read. +func TestNotTemporaryRead(t *testing.T) { + t.Parallel() + + ln := newLocalListener(t, "tcp") + serverDone := make(chan struct{}) + dialed := make(chan struct{}) + go func() { + defer close(serverDone) + + cs, err := ln.Accept() + if err != nil { + return + } + <-dialed + cs.(*TCPConn).SetLinger(0) + cs.Close() + }() + defer func() { + ln.Close() + <-serverDone + }() + + ss, err := Dial("tcp", ln.Addr().String()) + close(dialed) + if err != nil { + t.Fatal(err) + } + defer ss.Close() + + _, err = ss.Read([]byte{0}) + if err == nil { + t.Fatal("Read succeeded unexpectedly") + } else if err == io.EOF { + // This happens on Plan 9, but for some reason (prior to CL 385314) it was + // accepted everywhere else too. + if runtime.GOOS == "plan9" { + return + } + t.Fatal("Read unexpectedly returned io.EOF after socket was abruptly closed") + } + if ne, ok := err.(Error); !ok { + t.Errorf("Read error does not implement net.Error: %v", err) + } else if ne.Temporary() { + t.Errorf("Read error is unexpectedly temporary: %v", err) + } +} + +// The various errors should implement the Error interface. +func TestErrors(t *testing.T) { + var ( + _ Error = &OpError{} + _ Error = &ParseError{} + _ Error = &AddrError{} + _ Error = UnknownNetworkError("") + _ Error = InvalidAddrError("") + _ Error = &timeoutError{} + _ Error = &DNSConfigError{} + _ Error = &DNSError{} + ) + + // ErrClosed was introduced as type error, so we can't check + // it using a declaration. + if _, ok := ErrClosed.(Error); !ok { + t.Fatal("ErrClosed does not implement Error") + } +} diff --git a/go/src/net/net_windows_test.go b/go/src/net/net_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0a5c77f032527ef3d411fa629119840f61d53412 --- /dev/null +++ b/go/src/net/net_windows_test.go @@ -0,0 +1,627 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "bufio" + "bytes" + "fmt" + "internal/testenv" + "io" + "os" + "os/exec" + "regexp" + "slices" + "strings" + "syscall" + "testing" + "time" +) + +func toErrno(err error) (syscall.Errno, bool) { + operr, ok := err.(*OpError) + if !ok { + return 0, false + } + syserr, ok := operr.Err.(*os.SyscallError) + if !ok { + return 0, false + } + errno, ok := syserr.Err.(syscall.Errno) + if !ok { + return 0, false + } + return errno, true +} + +// TestAcceptIgnoreSomeErrors tests that windows TCPListener.AcceptTCP +// handles broken connections. It verifies that broken connections do +// not affect future connections. +func TestAcceptIgnoreSomeErrors(t *testing.T) { + recv := func(ln Listener, ignoreSomeReadErrors bool) (string, error) { + c, err := ln.Accept() + if err != nil { + // Display windows errno in error message. + errno, ok := toErrno(err) + if !ok { + return "", err + } + return "", fmt.Errorf("%v (windows errno=%d)", err, errno) + } + defer c.Close() + + b := make([]byte, 100) + n, err := c.Read(b) + if err == nil || err == io.EOF { + return string(b[:n]), nil + } + errno, ok := toErrno(err) + if ok && ignoreSomeReadErrors && (errno == syscall.ERROR_NETNAME_DELETED || errno == syscall.WSAECONNRESET) { + return "", nil + } + return "", err + } + + send := func(addr string, data string) error { + c, err := Dial("tcp", addr) + if err != nil { + return err + } + defer c.Close() + + b := []byte(data) + n, err := c.Write(b) + if err != nil { + return err + } + if n != len(b) { + return fmt.Errorf(`Only %d chars of string "%s" sent`, n, data) + } + return nil + } + + if envaddr := os.Getenv("GOTEST_DIAL_ADDR"); envaddr != "" { + // In child process. + c, err := Dial("tcp", envaddr) + if err != nil { + t.Fatal(err) + } + fmt.Printf("sleeping\n") + time.Sleep(time.Minute) // process will be killed here + c.Close() + } + + ln, err := Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + // Start child process that connects to our listener. + cmd := exec.Command(testenv.Executable(t), "-test.run=^TestAcceptIgnoreSomeErrors$") + cmd.Env = append(os.Environ(), "GOTEST_DIAL_ADDR="+ln.Addr().String()) + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatalf("cmd.StdoutPipe failed: %v", err) + } + err = cmd.Start() + if err != nil { + t.Fatalf("cmd.Start failed: %v\n", err) + } + outReader := bufio.NewReader(stdout) + for { + s, err := outReader.ReadString('\n') + if err != nil { + t.Fatalf("reading stdout failed: %v", err) + } + if s == "sleeping\n" { + break + } + } + defer cmd.Wait() // ignore error - we know it is getting killed + + const alittle = 100 * time.Millisecond + time.Sleep(alittle) + cmd.Process.Kill() // the only way to trigger the errors + time.Sleep(alittle) + + // Send second connection data (with delay in a separate goroutine). + result := make(chan error) + go func() { + time.Sleep(alittle) + err := send(ln.Addr().String(), "abc") + if err != nil { + result <- err + } + result <- nil + }() + defer func() { + err := <-result + if err != nil { + t.Fatalf("send failed: %v", err) + } + }() + + // Receive first or second connection. + s, err := recv(ln, true) + if err != nil { + t.Fatalf("recv failed: %v", err) + } + switch s { + case "": + // First connection data is received, let's get second connection data. + case "abc": + // First connection is lost forever, but that is ok. + return + default: + t.Fatalf(`"%s" received from recv, but "" or "abc" expected`, s) + } + + // Get second connection data. + s, err = recv(ln, false) + if err != nil { + t.Fatalf("recv failed: %v", err) + } + if s != "abc" { + t.Fatalf(`"%s" received from recv, but "abc" expected`, s) + } +} + +func runCmd(args ...string) ([]byte, error) { + removeUTF8BOM := func(b []byte) []byte { + if len(b) >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF { + return b[3:] + } + return b + } + f, err := os.CreateTemp("", "netcmd") + if err != nil { + return nil, err + } + f.Close() + defer os.Remove(f.Name()) + cmd := fmt.Sprintf(`%s | Out-File "%s" -encoding UTF8`, strings.Join(args, " "), f.Name()) + out, err := exec.Command("powershell", "-Command", cmd).CombinedOutput() + if err != nil { + if len(out) != 0 { + return nil, fmt.Errorf("%s failed: %v: %q", args[0], err, string(removeUTF8BOM(out))) + } + var err2 error + out, err2 = os.ReadFile(f.Name()) + if err2 != nil { + return nil, err2 + } + if len(out) != 0 { + return nil, fmt.Errorf("%s failed: %v: %q", args[0], err, string(removeUTF8BOM(out))) + } + return nil, fmt.Errorf("%s failed: %v", args[0], err) + } + out, err = os.ReadFile(f.Name()) + if err != nil { + return nil, err + } + return removeUTF8BOM(out), nil +} + +func checkNetsh(t *testing.T) { + if testenv.Builder() == "windows-arm64-10" { + // netsh was observed to sometimes hang on this builder. + // We have not observed failures on windows-arm64-11, so for the + // moment we are leaving the test enabled elsewhere on the theory + // that it may have been a platform bug fixed in Windows 11. + testenv.SkipFlaky(t, 52082) + } + out, err := runCmd("netsh", "help") + if err != nil { + t.Fatal(err) + } + if bytes.Contains(out, []byte("The following helper DLL cannot be loaded")) { + t.Skipf("powershell failure:\n%s", err) + } + if !bytes.Contains(out, []byte("The following commands are available:")) { + t.Skipf("powershell does not speak English:\n%s", out) + } +} + +func netshInterfaceIPShowInterface(ipver string, ifaces map[string]bool) error { + out, err := runCmd("netsh", "interface", ipver, "show", "interface", "level=verbose") + if err != nil { + return err + } + // interface information is listed like: + // + //Interface Local Area Connection Parameters + //---------------------------------------------- + //IfLuid : ethernet_6 + //IfIndex : 11 + //State : connected + //Metric : 10 + //... + var name string + for line := range bytes.SplitSeq(out, []byte{'\r', '\n'}) { + if bytes.HasPrefix(line, []byte("Interface ")) && bytes.HasSuffix(line, []byte(" Parameters")) { + f := line[len("Interface "):] + f = f[:len(f)-len(" Parameters")] + name = string(f) + continue + } + var isup bool + switch string(line) { + case "State : connected": + isup = true + case "State : disconnected": + isup = false + default: + continue + } + if name != "" { + if v, ok := ifaces[name]; ok && v != isup { + return fmt.Errorf("%s:%s isup=%v: ipv4 and ipv6 report different interface state", ipver, name, isup) + } + ifaces[name] = isup + name = "" + } + } + return nil +} + +func TestInterfacesWithNetsh(t *testing.T) { + checkNetsh(t) + + toString := func(name string, isup bool) string { + if isup { + return name + ":up" + } + return name + ":down" + } + + ift, err := Interfaces() + if err != nil { + t.Fatal(err) + } + have := make([]string, 0) + for _, ifi := range ift { + have = append(have, toString(ifi.Name, ifi.Flags&FlagUp != 0)) + } + slices.Sort(have) + + ifaces := make(map[string]bool) + err = netshInterfaceIPShowInterface("ipv6", ifaces) + if err != nil { + t.Fatal(err) + } + err = netshInterfaceIPShowInterface("ipv4", ifaces) + if err != nil { + t.Fatal(err) + } + want := make([]string, 0) + for name, isup := range ifaces { + want = append(want, toString(name, isup)) + } + slices.Sort(want) + + if !slices.Equal(want, have) { + t.Fatalf("unexpected interface list %q, want %q", have, want) + } +} + +func netshInterfaceIPv4ShowAddress(name string, netshOutput []byte) []string { + // Address information is listed like: + // + //Configuration for interface "Local Area Connection" + // DHCP enabled: Yes + // IP Address: 10.0.0.2 + // Subnet Prefix: 10.0.0.0/24 (mask 255.255.255.0) + // IP Address: 10.0.0.3 + // Subnet Prefix: 10.0.0.0/24 (mask 255.255.255.0) + // Default Gateway: 10.0.0.254 + // Gateway Metric: 0 + // InterfaceMetric: 10 + // + //Configuration for interface "Loopback Pseudo-Interface 1" + // DHCP enabled: No + // IP Address: 127.0.0.1 + // Subnet Prefix: 127.0.0.0/8 (mask 255.0.0.0) + // InterfaceMetric: 50 + // + addrs := make([]string, 0) + var addr, subnetprefix string + var processingOurInterface bool + for line := range bytes.SplitSeq(netshOutput, []byte{'\r', '\n'}) { + if !processingOurInterface { + if !bytes.HasPrefix(line, []byte("Configuration for interface")) { + continue + } + if !bytes.Contains(line, []byte(`"`+name+`"`)) { + continue + } + processingOurInterface = true + continue + } + if len(line) == 0 { + break + } + if bytes.Contains(line, []byte("Subnet Prefix:")) { + f := bytes.Split(line, []byte{':'}) + if len(f) == 2 { + f = bytes.Split(f[1], []byte{'('}) + if len(f) == 2 { + f = bytes.Split(f[0], []byte{'/'}) + if len(f) == 2 { + subnetprefix = string(bytes.TrimSpace(f[1])) + if addr != "" && subnetprefix != "" { + addrs = append(addrs, addr+"/"+subnetprefix) + } + } + } + } + } + addr = "" + if bytes.Contains(line, []byte("IP Address:")) { + f := bytes.Split(line, []byte{':'}) + if len(f) == 2 { + addr = string(bytes.TrimSpace(f[1])) + } + } + } + return addrs +} + +func netshInterfaceIPv6ShowAddress(name string, netshOutput []byte) []string { + // Address information is listed like: + // + //Address ::1 Parameters + //--------------------------------------------------------- + //Interface Luid : Loopback Pseudo-Interface 1 + //Scope Id : 0.0 + //Valid Lifetime : infinite + //Preferred Lifetime : infinite + //DAD State : Preferred + //Address Type : Other + //Skip as Source : false + // + //Address XXXX::XXXX:XXXX:XXXX:XXXX%11 Parameters + //--------------------------------------------------------- + //Interface Luid : Local Area Connection + //Scope Id : 0.11 + //Valid Lifetime : infinite + //Preferred Lifetime : infinite + //DAD State : Preferred + //Address Type : Other + //Skip as Source : false + // + + // TODO: need to test ipv6 netmask too, but netsh does not outputs it + var addr string + addrs := make([]string, 0) + for line := range bytes.SplitSeq(netshOutput, []byte{'\r', '\n'}) { + if addr != "" { + if len(line) == 0 { + addr = "" + continue + } + if string(line) != "Interface Luid : "+name { + continue + } + addrs = append(addrs, addr) + addr = "" + continue + } + if !bytes.HasPrefix(line, []byte("Address")) { + continue + } + if !bytes.HasSuffix(line, []byte("Parameters")) { + continue + } + f := bytes.Split(line, []byte{' '}) + if len(f) != 3 { + continue + } + // remove scope ID if present + f = bytes.Split(f[1], []byte{'%'}) + + // netsh can create IPv4-embedded IPv6 addresses, like fe80::5efe:192.168.140.1. + // Convert these to all hexadecimal fe80::5efe:c0a8:8c01 for later string comparisons. + ipv4Tail := regexp.MustCompile(`:\d+\.\d+\.\d+\.\d+$`) + if ipv4Tail.Match(f[0]) { + f[0] = []byte(ParseIP(string(f[0])).String()) + } + + addr = string(bytes.ToLower(bytes.TrimSpace(f[0]))) + } + return addrs +} + +func TestInterfaceAddrsWithNetsh(t *testing.T) { + checkNetsh(t) + + outIPV4, err := runCmd("netsh", "interface", "ipv4", "show", "address") + if err != nil { + t.Fatal(err) + } + outIPV6, err := runCmd("netsh", "interface", "ipv6", "show", "address", "level=verbose") + if err != nil { + t.Fatal(err) + } + + ift, err := Interfaces() + if err != nil { + t.Fatal(err) + } + for _, ifi := range ift { + // Skip the interface if it's down. + if (ifi.Flags & FlagUp) == 0 { + continue + } + have := make([]string, 0) + addrs, err := ifi.Addrs() + if err != nil { + t.Fatal(err) + } + for _, addr := range addrs { + switch addr := addr.(type) { + case *IPNet: + if addr.IP.To4() != nil { + have = append(have, addr.String()) + } + if addr.IP.To16() != nil && addr.IP.To4() == nil { + // netsh does not output netmask for ipv6, so ignore ipv6 mask + have = append(have, addr.IP.String()) + } + case *IPAddr: + if addr.IP.To4() != nil { + have = append(have, addr.String()) + } + if addr.IP.To16() != nil && addr.IP.To4() == nil { + // netsh does not output netmask for ipv6, so ignore ipv6 mask + have = append(have, addr.IP.String()) + } + } + } + slices.Sort(have) + + want := netshInterfaceIPv4ShowAddress(ifi.Name, outIPV4) + wantIPv6 := netshInterfaceIPv6ShowAddress(ifi.Name, outIPV6) + want = append(want, wantIPv6...) + slices.Sort(want) + + if !slices.Equal(want, have) { + t.Errorf("%s: unexpected addresses list %q, want %q", ifi.Name, have, want) + } + } +} + +// check that getmac exists as a powershell command, and that it +// speaks English. +func checkGetmac(t *testing.T) { + out, err := runCmd("getmac", "/?") + if err != nil { + if strings.Contains(err.Error(), "term 'getmac' is not recognized as the name of a cmdlet") { + t.Skipf("getmac not available") + } + t.Fatal(err) + } + if !bytes.Contains(out, []byte("network adapters on a system")) { + t.Skipf("skipping test on non-English system") + } +} + +func TestInterfaceHardwareAddrWithGetmac(t *testing.T) { + checkGetmac(t) + + ift, err := Interfaces() + if err != nil { + t.Fatal(err) + } + have := make(map[string]string) + for _, ifi := range ift { + if ifi.Flags&FlagLoopback != 0 { + // no MAC address for loopback interfaces + continue + } + have[ifi.Name] = ifi.HardwareAddr.String() + } + + out, err := runCmd("getmac", "/fo", "list", "/v") + if err != nil { + t.Fatal(err) + } + // getmac output looks like: + // + //Connection Name: Local Area Connection + //Network Adapter: Intel Gigabit Network Connection + //Physical Address: XX-XX-XX-XX-XX-XX + //Transport Name: \Device\Tcpip_{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} + // + //Connection Name: Wireless Network Connection + //Network Adapter: Wireles WLAN Card + //Physical Address: XX-XX-XX-XX-XX-XX + //Transport Name: Media disconnected + // + //Connection Name: Bluetooth Network Connection + //Network Adapter: Bluetooth Device (Personal Area Network) + //Physical Address: N/A + //Transport Name: Hardware not present + // + //Connection Name: VMware Network Adapter VMnet8 + //Network Adapter: VMware Virtual Ethernet Adapter for VMnet8 + //Physical Address: Disabled + //Transport Name: Disconnected + // + want := make(map[string]string) + group := make(map[string]string) // name / values for single adapter + getValue := func(name string) string { + value, found := group[name] + if !found { + t.Fatalf("%q has no %q line in it", group, name) + } + if value == "" { + t.Fatalf("%q has empty %q value", group, name) + } + return value + } + processGroup := func() { + if len(group) == 0 { + return + } + tname := strings.ToLower(getValue("Transport Name")) + if tname == "n/a" { + // skip these + return + } + addr := strings.ToLower(getValue("Physical Address")) + if addr == "disabled" || addr == "n/a" { + // skip these + return + } + addr = strings.ReplaceAll(addr, "-", ":") + cname := getValue("Connection Name") + want[cname] = addr + group = make(map[string]string) + } + for line := range bytes.SplitSeq(out, []byte{'\r', '\n'}) { + if len(line) == 0 { + processGroup() + continue + } + i := bytes.IndexByte(line, ':') + if i == -1 { + t.Fatalf("line %q has no : in it", line) + } + group[string(line[:i])] = string(bytes.TrimSpace(line[i+1:])) + } + processGroup() + + dups := make(map[string][]string) + for name, addr := range want { + if _, ok := dups[addr]; !ok { + dups[addr] = make([]string, 0) + } + dups[addr] = append(dups[addr], name) + } + +nextWant: + for name, wantAddr := range want { + if haveAddr, ok := have[name]; ok { + if haveAddr != wantAddr { + t.Errorf("unexpected MAC address for %q - %v, want %v", name, haveAddr, wantAddr) + } + continue + } + // We could not find the interface in getmac output by name. + // But sometimes getmac lists many interface names + // for the same MAC address. If that is the case here, + // and we can match at least one of those names, + // let's ignore the other names. + if dupNames, ok := dups[wantAddr]; ok && len(dupNames) > 1 { + for _, dupName := range dupNames { + if haveAddr, ok := have[dupName]; ok && haveAddr == wantAddr { + continue nextWant + } + } + } + t.Errorf("getmac lists %q, but it could not be found among Go interfaces %v", name, have) + } +} diff --git a/go/src/net/netcgo_off.go b/go/src/net/netcgo_off.go new file mode 100644 index 0000000000000000000000000000000000000000..54677dcac6cd7987c3eddd570aae8c8f18316e86 --- /dev/null +++ b/go/src/net/netcgo_off.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !netcgo + +package net + +const netCgoBuildTag = false diff --git a/go/src/net/netcgo_on.go b/go/src/net/netcgo_on.go new file mode 100644 index 0000000000000000000000000000000000000000..25d4bdca72a0449c5d8de847f2ec5b97c47d57f9 --- /dev/null +++ b/go/src/net/netcgo_on.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build netcgo + +package net + +const netCgoBuildTag = true diff --git a/go/src/net/netgo_netcgo.go b/go/src/net/netgo_netcgo.go new file mode 100644 index 0000000000000000000000000000000000000000..7f3a5fd007fb43b3bdce55379cef74cd48415b2d --- /dev/null +++ b/go/src/net/netgo_netcgo.go @@ -0,0 +1,14 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build netgo && netcgo + +package net + +func init() { + // This will give a compile time error about the unused constant. + // The advantage of this approach is that the gc compiler + // actually prints the constant, making the problem obvious. + "Do not use both netgo and netcgo build tags." +} diff --git a/go/src/net/netgo_off.go b/go/src/net/netgo_off.go new file mode 100644 index 0000000000000000000000000000000000000000..e6bc2d7d069d11c9598b5e50748f34938e92247c --- /dev/null +++ b/go/src/net/netgo_off.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !netgo + +package net + +const netGoBuildTag = false diff --git a/go/src/net/netgo_on.go b/go/src/net/netgo_on.go new file mode 100644 index 0000000000000000000000000000000000000000..4f088de6e3f80bf83c289d3dcaba19fe5ec83538 --- /dev/null +++ b/go/src/net/netgo_on.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build netgo + +package net + +const netGoBuildTag = true diff --git a/go/src/net/nss.go b/go/src/net/nss.go new file mode 100644 index 0000000000000000000000000000000000000000..092b515cc7d01ed6d68cf0cf17e1ab8e167c6ded --- /dev/null +++ b/go/src/net/nss.go @@ -0,0 +1,249 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "internal/bytealg" + "os" + "sync" + "time" +) + +const ( + nssConfigPath = "/etc/nsswitch.conf" +) + +var nssConfig nsswitchConfig + +type nsswitchConfig struct { + initOnce sync.Once // guards init of nsswitchConfig + + // ch is used as a semaphore that only allows one lookup at a + // time to recheck nsswitch.conf + ch chan struct{} // guards lastChecked and modTime + lastChecked time.Time // last time nsswitch.conf was checked + + mu sync.Mutex // protects nssConf + nssConf *nssConf +} + +func getSystemNSS() *nssConf { + nssConfig.tryUpdate() + nssConfig.mu.Lock() + conf := nssConfig.nssConf + nssConfig.mu.Unlock() + return conf +} + +// init initializes conf and is only called via conf.initOnce. +func (conf *nsswitchConfig) init() { + conf.nssConf = parseNSSConfFile("/etc/nsswitch.conf") + conf.lastChecked = time.Now() + conf.ch = make(chan struct{}, 1) +} + +// tryUpdate tries to update conf. +func (conf *nsswitchConfig) tryUpdate() { + conf.initOnce.Do(conf.init) + + // Ensure only one update at a time checks nsswitch.conf + if !conf.tryAcquireSema() { + return + } + defer conf.releaseSema() + + now := time.Now() + if conf.lastChecked.After(now.Add(-5 * time.Second)) { + return + } + conf.lastChecked = now + + var mtime time.Time + if fi, err := os.Stat(nssConfigPath); err == nil { + mtime = fi.ModTime() + } + if mtime.Equal(conf.nssConf.mtime) { + return + } + + nssConf := parseNSSConfFile(nssConfigPath) + conf.mu.Lock() + conf.nssConf = nssConf + conf.mu.Unlock() +} + +func (conf *nsswitchConfig) acquireSema() { + conf.ch <- struct{}{} +} + +func (conf *nsswitchConfig) tryAcquireSema() bool { + select { + case conf.ch <- struct{}{}: + return true + default: + return false + } +} + +func (conf *nsswitchConfig) releaseSema() { + <-conf.ch +} + +// nssConf represents the state of the machine's /etc/nsswitch.conf file. +type nssConf struct { + mtime time.Time // time of nsswitch.conf modification + err error // any error encountered opening or parsing the file + sources map[string][]nssSource // keyed by database (e.g. "hosts") +} + +type nssSource struct { + source string // e.g. "compat", "files", "mdns4_minimal" + criteria []nssCriterion +} + +// standardCriteria reports all specified criteria have the default +// status actions. +func (s nssSource) standardCriteria() bool { + for i, crit := range s.criteria { + if !crit.standardStatusAction(i == len(s.criteria)-1) { + return false + } + } + return true +} + +// nssCriterion is the parsed structure of one of the criteria in brackets +// after an NSS source name. +type nssCriterion struct { + negate bool // if "!" was present + status string // e.g. "success", "unavail" (lowercase) + action string // e.g. "return", "continue" (lowercase) +} + +// standardStatusAction reports whether c is equivalent to not +// specifying the criterion at all. last is whether this criteria is the +// last in the list. +func (c nssCriterion) standardStatusAction(last bool) bool { + if c.negate { + return false + } + var def string + switch c.status { + case "success": + def = "return" + case "notfound", "unavail", "tryagain": + def = "continue" + default: + // Unknown status + return false + } + if last && c.action == "return" { + return true + } + return c.action == def +} + +func parseNSSConfFile(file string) *nssConf { + f, err := open(file) + if err != nil { + return &nssConf{err: err} + } + defer f.close() + mtime, _, err := f.stat() + if err != nil { + return &nssConf{err: err} + } + + conf := parseNSSConf(f) + conf.mtime = mtime + return conf +} + +func parseNSSConf(f *file) *nssConf { + conf := new(nssConf) + for line, ok := f.readLine(); ok; line, ok = f.readLine() { + line = trimSpace(removeComment(line)) + if len(line) == 0 { + continue + } + colon := bytealg.IndexByteString(line, ':') + if colon == -1 { + conf.err = errors.New("no colon on line") + return conf + } + db := trimSpace(line[:colon]) + srcs := line[colon+1:] + for { + srcs = trimSpace(srcs) + if len(srcs) == 0 { + break + } + sp := bytealg.IndexByteString(srcs, ' ') + var src string + if sp == -1 { + src = srcs + srcs = "" // done + } else { + src = srcs[:sp] + srcs = trimSpace(srcs[sp+1:]) + } + var criteria []nssCriterion + // See if there's a criteria block in brackets. + if len(srcs) > 0 && srcs[0] == '[' { + bclose := bytealg.IndexByteString(srcs, ']') + if bclose == -1 { + conf.err = errors.New("unclosed criterion bracket") + return conf + } + var err error + criteria, err = parseCriteria(srcs[1:bclose]) + if err != nil { + conf.err = errors.New("invalid criteria: " + srcs[1:bclose]) + return conf + } + srcs = srcs[bclose+1:] + } + if conf.sources == nil { + conf.sources = make(map[string][]nssSource) + } + conf.sources[db] = append(conf.sources[db], nssSource{ + source: src, + criteria: criteria, + }) + } + } + return conf +} + +// parses "foo=bar !foo=bar" +func parseCriteria(x string) (c []nssCriterion, err error) { + err = foreachField(x, func(f string) error { + not := false + if len(f) > 0 && f[0] == '!' { + not = true + f = f[1:] + } + if len(f) < 3 { + return errors.New("criterion too short") + } + eq := bytealg.IndexByteString(f, '=') + if eq == -1 { + return errors.New("criterion lacks equal sign") + } + if hasUpperCase(f) { + lower := []byte(f) + lowerASCIIBytes(lower) + f = string(lower) + } + c = append(c, nssCriterion{ + negate: not, + status: f[:eq], + action: f[eq+1:], + }) + return nil + }) + return +} diff --git a/go/src/net/nss_test.go b/go/src/net/nss_test.go new file mode 100644 index 0000000000000000000000000000000000000000..94e6b5fc0a216ef0309c05dbb90c383889a0a5d3 --- /dev/null +++ b/go/src/net/nss_test.go @@ -0,0 +1,172 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris + +package net + +import ( + "reflect" + "testing" + "time" +) + +const ubuntuTrustyAvahi = `# /etc/nsswitch.conf +# +# Example configuration of GNU Name Service Switch functionality. +# If you have the libc-doc-reference' and nfo' packages installed, try: +# nfo libc "Name Service Switch"' for information about this file. + +passwd: compat +group: compat +shadow: compat + +hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4 +networks: files + +protocols: db files +services: db files +ethers: db files +rpc: db files + +netgroup: nis +` + +func TestParseNSSConf(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want *nssConf + }{ + { + name: "no_newline", + in: "foo: a b", + want: &nssConf{ + sources: map[string][]nssSource{ + "foo": {{source: "a"}, {source: "b"}}, + }, + }, + }, + { + name: "newline", + in: "foo: a b\n", + want: &nssConf{ + sources: map[string][]nssSource{ + "foo": {{source: "a"}, {source: "b"}}, + }, + }, + }, + { + name: "whitespace", + in: " foo:a b \n", + want: &nssConf{ + sources: map[string][]nssSource{ + "foo": {{source: "a"}, {source: "b"}}, + }, + }, + }, + { + name: "comment1", + in: " foo:a b#c\n", + want: &nssConf{ + sources: map[string][]nssSource{ + "foo": {{source: "a"}, {source: "b"}}, + }, + }, + }, + { + name: "comment2", + in: " foo:a b #c \n", + want: &nssConf{ + sources: map[string][]nssSource{ + "foo": {{source: "a"}, {source: "b"}}, + }, + }, + }, + { + name: "crit", + in: " foo:a b [!a=b X=Y ] c#d \n", + want: &nssConf{ + sources: map[string][]nssSource{ + "foo": { + {source: "a"}, + { + source: "b", + criteria: []nssCriterion{ + { + negate: true, + status: "a", + action: "b", + }, + { + status: "x", + action: "y", + }, + }, + }, + {source: "c"}, + }, + }, + }, + }, + + // Ubuntu Trusty w/ avahi-daemon, libavahi-* etc installed. + { + name: "ubuntu_trusty_avahi", + in: ubuntuTrustyAvahi, + want: &nssConf{ + sources: map[string][]nssSource{ + "passwd": {{source: "compat"}}, + "group": {{source: "compat"}}, + "shadow": {{source: "compat"}}, + "hosts": { + {source: "files"}, + { + source: "mdns4_minimal", + criteria: []nssCriterion{ + { + negate: false, + status: "notfound", + action: "return", + }, + }, + }, + {source: "dns"}, + {source: "mdns4"}, + }, + "networks": {{source: "files"}}, + "protocols": { + {source: "db"}, + {source: "files"}, + }, + "services": { + {source: "db"}, + {source: "files"}, + }, + "ethers": { + {source: "db"}, + {source: "files"}, + }, + "rpc": { + {source: "db"}, + {source: "files"}, + }, + "netgroup": { + {source: "nis"}, + }, + }, + }, + }, + } + + for _, tt := range tests { + gotConf := nssStr(t, tt.in) + gotConf.mtime = time.Time{} // ignore mtime in comparison + if !reflect.DeepEqual(gotConf, tt.want) { + t.Errorf("%s: mismatch\n got %#v\nwant %#v", tt.name, gotConf, tt.want) + } + } +} diff --git a/go/src/net/packetconn_test.go b/go/src/net/packetconn_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e39e7de5d7f6f5bbd0bbff204bd4bbd94ed7275d --- /dev/null +++ b/go/src/net/packetconn_test.go @@ -0,0 +1,149 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements API tests across platforms and should never have a build +// constraint. + +package net + +import ( + "os" + "testing" +) + +// The full stack test cases for IPConn have been moved to the +// following: +// golang.org/x/net/ipv4 +// golang.org/x/net/ipv6 +// golang.org/x/net/icmp + +func packetConnTestData(t *testing.T, network string) ([]byte, func()) { + if !testableNetwork(network) { + return nil, func() { t.Logf("skipping %s test", network) } + } + return []byte("PACKETCONN TEST"), nil +} + +func TestPacketConn(t *testing.T) { + var packetConnTests = []struct { + net string + addr1 string + addr2 string + }{ + {"udp", "127.0.0.1:0", "127.0.0.1:0"}, + {"unixgram", testUnixAddr(t), testUnixAddr(t)}, + } + + closer := func(c PacketConn, net, addr1, addr2 string) { + c.Close() + switch net { + case "unixgram": + os.Remove(addr1) + os.Remove(addr2) + } + } + + for _, tt := range packetConnTests { + wb, skipOrFatalFn := packetConnTestData(t, tt.net) + if skipOrFatalFn != nil { + skipOrFatalFn() + continue + } + + c1, err := ListenPacket(tt.net, tt.addr1) + if err != nil { + t.Fatal(err) + } + defer closer(c1, tt.net, tt.addr1, tt.addr2) + c1.LocalAddr() + + c2, err := ListenPacket(tt.net, tt.addr2) + if err != nil { + t.Fatal(err) + } + defer closer(c2, tt.net, tt.addr1, tt.addr2) + c2.LocalAddr() + rb2 := make([]byte, 128) + + if _, err := c1.WriteTo(wb, c2.LocalAddr()); err != nil { + t.Fatal(err) + } + if _, _, err := c2.ReadFrom(rb2); err != nil { + t.Fatal(err) + } + if _, err := c2.WriteTo(wb, c1.LocalAddr()); err != nil { + t.Fatal(err) + } + rb1 := make([]byte, 128) + if _, _, err := c1.ReadFrom(rb1); err != nil { + t.Fatal(err) + } + } +} + +func TestConnAndPacketConn(t *testing.T) { + var packetConnTests = []struct { + net string + addr1 string + addr2 string + }{ + {"udp", "127.0.0.1:0", "127.0.0.1:0"}, + {"unixgram", testUnixAddr(t), testUnixAddr(t)}, + } + + closer := func(c PacketConn, net, addr1, addr2 string) { + c.Close() + switch net { + case "unixgram": + os.Remove(addr1) + os.Remove(addr2) + } + } + + for _, tt := range packetConnTests { + var wb []byte + wb, skipOrFatalFn := packetConnTestData(t, tt.net) + if skipOrFatalFn != nil { + skipOrFatalFn() + continue + } + + c1, err := ListenPacket(tt.net, tt.addr1) + if err != nil { + t.Fatal(err) + } + defer closer(c1, tt.net, tt.addr1, tt.addr2) + c1.LocalAddr() + + c2, err := Dial(tt.net, c1.LocalAddr().String()) + if err != nil { + t.Fatal(err) + } + defer c2.Close() + c2.LocalAddr() + c2.RemoteAddr() + + if _, err := c2.Write(wb); err != nil { + t.Fatal(err) + } + rb1 := make([]byte, 128) + if _, _, err := c1.ReadFrom(rb1); err != nil { + t.Fatal(err) + } + var dst Addr + switch tt.net { + case "unixgram": + continue + default: + dst = c2.LocalAddr() + } + if _, err := c1.WriteTo(wb, dst); err != nil { + t.Fatal(err) + } + rb2 := make([]byte, 128) + if _, err := c2.Read(rb2); err != nil { + t.Fatal(err) + } + } +} diff --git a/go/src/net/parse.go b/go/src/net/parse.go new file mode 100644 index 0000000000000000000000000000000000000000..106a303dfadae443c7bece173faf1be77df482c3 --- /dev/null +++ b/go/src/net/parse.go @@ -0,0 +1,272 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Simple file i/o and string manipulation, to avoid +// depending on strconv and bufio and strings. + +package net + +import ( + "internal/bytealg" + "io" + "os" + "time" +) + +type file struct { + file *os.File + data []byte + atEOF bool +} + +func (f *file) close() { f.file.Close() } + +func (f *file) getLineFromData() (s string, ok bool) { + data := f.data + i := 0 + for i = 0; i < len(data); i++ { + if data[i] == '\n' { + s = string(data[0:i]) + ok = true + // move data + i++ + n := len(data) - i + copy(data[0:], data[i:]) + f.data = data[0:n] + return + } + } + if f.atEOF && len(f.data) > 0 { + // EOF, return all we have + s = string(data) + f.data = f.data[0:0] + ok = true + } + return +} + +func (f *file) readLine() (s string, ok bool) { + if s, ok = f.getLineFromData(); ok { + return + } + if len(f.data) < cap(f.data) { + ln := len(f.data) + n, err := io.ReadFull(f.file, f.data[ln:cap(f.data)]) + if n >= 0 { + f.data = f.data[0 : ln+n] + } + if err == io.EOF || err == io.ErrUnexpectedEOF { + f.atEOF = true + } + } + s, ok = f.getLineFromData() + return +} + +func (f *file) stat() (mtime time.Time, size int64, err error) { + st, err := f.file.Stat() + if err != nil { + return time.Time{}, 0, err + } + return st.ModTime(), st.Size(), nil +} + +func open(name string) (*file, error) { + fd, err := os.Open(name) + if err != nil { + return nil, err + } + return &file{fd, make([]byte, 0, 64*1024), false}, nil +} + +func stat(name string) (mtime time.Time, size int64, err error) { + st, err := os.Stat(name) + if err != nil { + return time.Time{}, 0, err + } + return st.ModTime(), st.Size(), nil +} + +// Count occurrences in s of any bytes in t. +func countAnyByte(s string, t string) int { + n := 0 + for i := 0; i < len(s); i++ { + if bytealg.IndexByteString(t, s[i]) >= 0 { + n++ + } + } + return n +} + +// Split s at any bytes in t. +func splitAtBytes(s string, t string) []string { + a := make([]string, 1+countAnyByte(s, t)) + n := 0 + last := 0 + for i := 0; i < len(s); i++ { + if bytealg.IndexByteString(t, s[i]) >= 0 { + if last < i { + a[n] = s[last:i] + n++ + } + last = i + 1 + } + } + if last < len(s) { + a[n] = s[last:] + n++ + } + return a[0:n] +} + +func getFields(s string) []string { return splitAtBytes(s, " \r\t\n") } + +// Bigger than we need, not too big to worry about overflow +const big = 0xFFFFFF + +// Decimal to integer. +// Returns number, characters consumed, success. +func dtoi(s string) (n int, i int, ok bool) { + n = 0 + for i = 0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { + n = n*10 + int(s[i]-'0') + if n >= big { + return big, i, false + } + } + if i == 0 { + return 0, 0, false + } + return n, i, true +} + +// Hexadecimal to integer. +// Returns number, characters consumed, success. +func xtoi(s string) (n int, i int, ok bool) { + n = 0 + for i = 0; i < len(s); i++ { + if '0' <= s[i] && s[i] <= '9' { + n *= 16 + n += int(s[i] - '0') + } else if 'a' <= s[i] && s[i] <= 'f' { + n *= 16 + n += int(s[i]-'a') + 10 + } else if 'A' <= s[i] && s[i] <= 'F' { + n *= 16 + n += int(s[i]-'A') + 10 + } else { + break + } + if n >= big { + return 0, i, false + } + } + if i == 0 { + return 0, i, false + } + return n, i, true +} + +// xtoi2 converts the next two hex digits of s into a byte. +// If s is longer than 2 bytes then the third byte must be e. +// If the first two bytes of s are not hex digits or the third byte +// does not match e, false is returned. +func xtoi2(s string, e byte) (byte, bool) { + if len(s) > 2 && s[2] != e { + return 0, false + } + n, ei, ok := xtoi(s[:2]) + return byte(n), ok && ei == 2 +} + +// hasUpperCase tells whether the given string contains at least one upper-case. +func hasUpperCase(s string) bool { + for i := range s { + if 'A' <= s[i] && s[i] <= 'Z' { + return true + } + } + return false +} + +// lowerASCIIBytes makes x ASCII lowercase in-place. +func lowerASCIIBytes(x []byte) { + for i, b := range x { + if 'A' <= b && b <= 'Z' { + x[i] += 'a' - 'A' + } + } +} + +// lowerASCII returns the ASCII lowercase version of b. +func lowerASCII(b byte) byte { + if 'A' <= b && b <= 'Z' { + return b + ('a' - 'A') + } + return b +} + +// trimSpace returns x without any leading or trailing ASCII whitespace. +func trimSpace(x string) string { + for len(x) > 0 && isSpace(x[0]) { + x = x[1:] + } + for len(x) > 0 && isSpace(x[len(x)-1]) { + x = x[:len(x)-1] + } + return x +} + +// isSpace reports whether b is an ASCII space character. +func isSpace(b byte) bool { + return b == ' ' || b == '\t' || b == '\n' || b == '\r' +} + +// removeComment returns line, removing any '#' byte and any following +// bytes. +func removeComment(line string) string { + if i := bytealg.IndexByteString(line, '#'); i != -1 { + return line[:i] + } + return line +} + +// foreachField runs fn on each non-empty run of non-space bytes in x. +// It returns the first non-nil error returned by fn. +func foreachField(x string, fn func(field string) error) error { + x = trimSpace(x) + for len(x) > 0 { + sp := bytealg.IndexByteString(x, ' ') + if sp == -1 { + return fn(x) + } + if field := trimSpace(x[:sp]); len(field) > 0 { + if err := fn(field); err != nil { + return err + } + } + x = trimSpace(x[sp+1:]) + } + return nil +} + +// stringsHasSuffixFold reports whether s ends in suffix, +// ASCII-case-insensitively. +func stringsHasSuffixFold(s, suffix string) bool { + return len(s) >= len(suffix) && stringsEqualFold(s[len(s)-len(suffix):], suffix) +} + +// stringsEqualFold is strings.EqualFold, ASCII only. It reports whether s and t +// are equal, ASCII-case-insensitively. +func stringsEqualFold(s, t string) bool { + if len(s) != len(t) { + return false + } + for i := 0; i < len(s); i++ { + if lowerASCII(s[i]) != lowerASCII(t[i]) { + return false + } + } + return true +} diff --git a/go/src/net/parse_test.go b/go/src/net/parse_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e58d9541544425d656fe27afe7109e850a2eec45 --- /dev/null +++ b/go/src/net/parse_test.go @@ -0,0 +1,75 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "bufio" + "os" + "runtime" + "testing" +) + +func TestReadLine(t *testing.T) { + // /etc/services file does not exist on android, plan9, windows, or wasip1 + // where it would be required to be mounted from the host file system. + switch runtime.GOOS { + case "android", "plan9", "windows", "wasip1": + t.Skipf("not supported on %s", runtime.GOOS) + } + filename := "/etc/services" // a nice big file + + fd, err := os.Open(filename) + if err != nil { + // The file is missing even on some Unix systems. + t.Skipf("skipping because failed to open /etc/services: %v", err) + } + defer fd.Close() + br := bufio.NewReader(fd) + + file, err := open(filename) + if file == nil { + t.Fatal(err) + } + defer file.close() + + lineno := 1 + byteno := 0 + for { + bline, berr := br.ReadString('\n') + if n := len(bline); n > 0 { + bline = bline[0 : n-1] + } + line, ok := file.readLine() + if (berr != nil) != !ok || bline != line { + t.Fatalf("%s:%d (#%d)\nbufio => %q, %v\nnet => %q, %v", filename, lineno, byteno, bline, berr, line, ok) + } + if !ok { + break + } + lineno++ + byteno += len(line) + 1 + } +} + +func TestDtoi(t *testing.T) { + for _, tt := range []struct { + in string + out int + off int + ok bool + }{ + {"", 0, 0, false}, + {"0", 0, 1, true}, + {"65536", 65536, 5, true}, + {"123456789", big, 8, false}, + {"-0", 0, 0, false}, + {"-1234", 0, 0, false}, + } { + n, i, ok := dtoi(tt.in) + if n != tt.out || i != tt.off || ok != tt.ok { + t.Errorf("got %d, %d, %v; want %d, %d, %v", n, i, ok, tt.out, tt.off, tt.ok) + } + } +} diff --git a/go/src/net/pipe.go b/go/src/net/pipe.go new file mode 100644 index 0000000000000000000000000000000000000000..69955e4617c23a79a440b81e99c0e327adf7ceed --- /dev/null +++ b/go/src/net/pipe.go @@ -0,0 +1,238 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "io" + "os" + "sync" + "time" +) + +// pipeDeadline is an abstraction for handling timeouts. +type pipeDeadline struct { + mu sync.Mutex // Guards timer and cancel + timer *time.Timer + cancel chan struct{} // Must be non-nil +} + +func makePipeDeadline() pipeDeadline { + return pipeDeadline{cancel: make(chan struct{})} +} + +// set sets the point in time when the deadline will time out. +// A timeout event is signaled by closing the channel returned by waiter. +// Once a timeout has occurred, the deadline can be refreshed by specifying a +// t value in the future. +// +// A zero value for t prevents timeout. +func (d *pipeDeadline) set(t time.Time) { + d.mu.Lock() + defer d.mu.Unlock() + + if d.timer != nil && !d.timer.Stop() { + <-d.cancel // Wait for the timer callback to finish and close cancel + } + d.timer = nil + + // Time is zero, then there is no deadline. + closed := isClosedChan(d.cancel) + if t.IsZero() { + if closed { + d.cancel = make(chan struct{}) + } + return + } + + // Time in the future, setup a timer to cancel in the future. + if dur := time.Until(t); dur > 0 { + if closed { + d.cancel = make(chan struct{}) + } + d.timer = time.AfterFunc(dur, func() { + close(d.cancel) + }) + return + } + + // Time in the past, so close immediately. + if !closed { + close(d.cancel) + } +} + +// wait returns a channel that is closed when the deadline is exceeded. +func (d *pipeDeadline) wait() chan struct{} { + d.mu.Lock() + defer d.mu.Unlock() + return d.cancel +} + +func isClosedChan(c <-chan struct{}) bool { + select { + case <-c: + return true + default: + return false + } +} + +type pipeAddr struct{} + +func (pipeAddr) Network() string { return "pipe" } +func (pipeAddr) String() string { return "pipe" } + +type pipe struct { + wrMu sync.Mutex // Serialize Write operations + + // Used by local Read to interact with remote Write. + // Successful receive on rdRx is always followed by send on rdTx. + rdRx <-chan []byte + rdTx chan<- int + + // Used by local Write to interact with remote Read. + // Successful send on wrTx is always followed by receive on wrRx. + wrTx chan<- []byte + wrRx <-chan int + + once sync.Once // Protects closing localDone + localDone chan struct{} + remoteDone <-chan struct{} + + readDeadline pipeDeadline + writeDeadline pipeDeadline +} + +// Pipe creates a synchronous, in-memory, full duplex +// network connection; both ends implement the [Conn] interface. +// Reads on one end are matched with writes on the other, +// copying data directly between the two; there is no internal +// buffering. +func Pipe() (Conn, Conn) { + cb1 := make(chan []byte) + cb2 := make(chan []byte) + cn1 := make(chan int) + cn2 := make(chan int) + done1 := make(chan struct{}) + done2 := make(chan struct{}) + + p1 := &pipe{ + rdRx: cb1, rdTx: cn1, + wrTx: cb2, wrRx: cn2, + localDone: done1, remoteDone: done2, + readDeadline: makePipeDeadline(), + writeDeadline: makePipeDeadline(), + } + p2 := &pipe{ + rdRx: cb2, rdTx: cn2, + wrTx: cb1, wrRx: cn1, + localDone: done2, remoteDone: done1, + readDeadline: makePipeDeadline(), + writeDeadline: makePipeDeadline(), + } + return p1, p2 +} + +func (*pipe) LocalAddr() Addr { return pipeAddr{} } +func (*pipe) RemoteAddr() Addr { return pipeAddr{} } + +func (p *pipe) Read(b []byte) (int, error) { + n, err := p.read(b) + if err != nil && err != io.EOF && err != io.ErrClosedPipe { + err = &OpError{Op: "read", Net: "pipe", Err: err} + } + return n, err +} + +func (p *pipe) read(b []byte) (n int, err error) { + switch { + case isClosedChan(p.localDone): + return 0, io.ErrClosedPipe + case isClosedChan(p.remoteDone): + return 0, io.EOF + case isClosedChan(p.readDeadline.wait()): + return 0, os.ErrDeadlineExceeded + } + + select { + case bw := <-p.rdRx: + nr := copy(b, bw) + p.rdTx <- nr + return nr, nil + case <-p.localDone: + return 0, io.ErrClosedPipe + case <-p.remoteDone: + return 0, io.EOF + case <-p.readDeadline.wait(): + return 0, os.ErrDeadlineExceeded + } +} + +func (p *pipe) Write(b []byte) (int, error) { + n, err := p.write(b) + if err != nil && err != io.ErrClosedPipe { + err = &OpError{Op: "write", Net: "pipe", Err: err} + } + return n, err +} + +func (p *pipe) write(b []byte) (n int, err error) { + switch { + case isClosedChan(p.localDone): + return 0, io.ErrClosedPipe + case isClosedChan(p.remoteDone): + return 0, io.ErrClosedPipe + case isClosedChan(p.writeDeadline.wait()): + return 0, os.ErrDeadlineExceeded + } + + p.wrMu.Lock() // Ensure entirety of b is written together + defer p.wrMu.Unlock() + for once := true; once || len(b) > 0; once = false { + select { + case p.wrTx <- b: + nw := <-p.wrRx + b = b[nw:] + n += nw + case <-p.localDone: + return n, io.ErrClosedPipe + case <-p.remoteDone: + return n, io.ErrClosedPipe + case <-p.writeDeadline.wait(): + return n, os.ErrDeadlineExceeded + } + } + return n, nil +} + +func (p *pipe) SetDeadline(t time.Time) error { + if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) { + return io.ErrClosedPipe + } + p.readDeadline.set(t) + p.writeDeadline.set(t) + return nil +} + +func (p *pipe) SetReadDeadline(t time.Time) error { + if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) { + return io.ErrClosedPipe + } + p.readDeadline.set(t) + return nil +} + +func (p *pipe) SetWriteDeadline(t time.Time) error { + if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) { + return io.ErrClosedPipe + } + p.writeDeadline.set(t) + return nil +} + +func (p *pipe) Close() error { + p.once.Do(func() { close(p.localDone) }) + return nil +} diff --git a/go/src/net/pipe_test.go b/go/src/net/pipe_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9cc24148ca26fe0173412ae378b38c51fa47b1a8 --- /dev/null +++ b/go/src/net/pipe_test.go @@ -0,0 +1,49 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net_test + +import ( + "io" + "net" + "testing" + "time" + + "golang.org/x/net/nettest" +) + +func TestPipe(t *testing.T) { + nettest.TestConn(t, func() (c1, c2 net.Conn, stop func(), err error) { + c1, c2 = net.Pipe() + stop = func() { + c1.Close() + c2.Close() + } + return + }) +} + +func TestPipeCloseError(t *testing.T) { + c1, c2 := net.Pipe() + c1.Close() + + if _, err := c1.Read(nil); err != io.ErrClosedPipe { + t.Errorf("c1.Read() = %v, want io.ErrClosedPipe", err) + } + if _, err := c1.Write(nil); err != io.ErrClosedPipe { + t.Errorf("c1.Write() = %v, want io.ErrClosedPipe", err) + } + if err := c1.SetDeadline(time.Time{}); err != io.ErrClosedPipe { + t.Errorf("c1.SetDeadline() = %v, want io.ErrClosedPipe", err) + } + if _, err := c2.Read(nil); err != io.EOF { + t.Errorf("c2.Read() = %v, want io.EOF", err) + } + if _, err := c2.Write(nil); err != io.ErrClosedPipe { + t.Errorf("c2.Write() = %v, want io.ErrClosedPipe", err) + } + if err := c2.SetDeadline(time.Time{}); err != io.ErrClosedPipe { + t.Errorf("c2.SetDeadline() = %v, want io.ErrClosedPipe", err) + } +} diff --git a/go/src/net/platform_plan9_test.go b/go/src/net/platform_plan9_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e1ca0aadae1238782bd0ed467fab5b92d882a660 --- /dev/null +++ b/go/src/net/platform_plan9_test.go @@ -0,0 +1,9 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +func supportsUnixSocket() bool { + return false +} diff --git a/go/src/net/platform_test.go b/go/src/net/platform_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f8317104d03ed1dbab75762c9d898af2996c7d8f --- /dev/null +++ b/go/src/net/platform_test.go @@ -0,0 +1,161 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/testenv" + "os" + "runtime" + "strings" + "testing" +) + +// testableNetwork reports whether network is testable on the current +// platform configuration. +func testableNetwork(network string) bool { + net, _, _ := strings.Cut(network, ":") + switch net { + case "ip+nopriv": + case "ip", "ip4", "ip6": + switch runtime.GOOS { + case "plan9": + return false + default: + if os.Getuid() != 0 { + return false + } + } + case "unixgram": + switch runtime.GOOS { + case "windows": + return false + default: + return supportsUnixSocket() + } + case "unix": + return supportsUnixSocket() + case "unixpacket": + switch runtime.GOOS { + case "aix", "android", "darwin", "ios", "plan9", "windows": + return false + } + } + switch net { + case "tcp4", "udp4", "ip4": + if !supportsIPv4() { + return false + } + case "tcp6", "udp6", "ip6": + if !supportsIPv6() { + return false + } + } + return true +} + +// testableAddress reports whether address of network is testable on +// the current platform configuration. +func testableAddress(network, address string) bool { + switch net, _, _ := strings.Cut(network, ":"); net { + case "unix", "unixgram", "unixpacket": + // Abstract unix domain sockets, a Linux-ism. + if address[0] == '@' && runtime.GOOS != "linux" { + return false + } + } + return true +} + +// testableListenArgs reports whether arguments are testable on the +// current platform configuration. +func testableListenArgs(network, address, client string) bool { + if !testableNetwork(network) || !testableAddress(network, address) { + return false + } + + var err error + var addr Addr + switch net, _, _ := strings.Cut(network, ":"); net { + case "tcp", "tcp4", "tcp6": + addr, err = ResolveTCPAddr("tcp", address) + case "udp", "udp4", "udp6": + addr, err = ResolveUDPAddr("udp", address) + case "ip", "ip4", "ip6": + addr, err = ResolveIPAddr("ip", address) + default: + return true + } + if err != nil { + return false + } + var ip IP + var wildcard bool + switch addr := addr.(type) { + case *TCPAddr: + ip = addr.IP + wildcard = addr.isWildcard() + case *UDPAddr: + ip = addr.IP + wildcard = addr.isWildcard() + case *IPAddr: + ip = addr.IP + wildcard = addr.isWildcard() + } + + // Test wildcard IP addresses. + if wildcard && !testenv.HasExternalNetwork() { + return false + } + + // Test functionality of IPv4 communication using AF_INET and + // IPv6 communication using AF_INET6 sockets. + if !supportsIPv4() && ip.To4() != nil { + return false + } + if !supportsIPv6() && ip.To16() != nil && ip.To4() == nil { + return false + } + cip := ParseIP(client) + if cip != nil { + if !supportsIPv4() && cip.To4() != nil { + return false + } + if !supportsIPv6() && cip.To16() != nil && cip.To4() == nil { + return false + } + } + + // Test functionality of IPv4 communication using AF_INET6 + // sockets. + if !supportsIPv4map() && supportsIPv4() && (network == "tcp" || network == "udp" || network == "ip") && wildcard { + // At this point, we prefer IPv4 when ip is nil. + // See favoriteAddrFamily for further information. + if ip.To16() != nil && ip.To4() == nil && cip.To4() != nil { // a pair of IPv6 server and IPv4 client + return false + } + if (ip.To4() != nil || ip == nil) && cip.To16() != nil && cip.To4() == nil { // a pair of IPv4 server and IPv6 client + return false + } + } + + return true +} + +func condFatalf(t *testing.T, network string, format string, args ...any) { + t.Helper() + // A few APIs like File and Read/WriteMsg{UDP,IP} are not + // fully implemented yet on Plan 9 and Windows. + switch runtime.GOOS { + case "windows", "js", "wasip1": + if network == "file+net" { + t.Logf(format, args...) + return + } + case "plan9": + t.Logf(format, args...) + return + } + t.Fatalf(format, args...) +} diff --git a/go/src/net/platform_unix_test.go b/go/src/net/platform_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6b3a5549de86509f0351fc8ca58b2a25947796a --- /dev/null +++ b/go/src/net/platform_unix_test.go @@ -0,0 +1,40 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 + +package net + +import ( + "os/exec" + "runtime" + "strconv" +) + +var unixEnabledOnAIX bool + +func init() { + if runtime.GOOS == "aix" { + // Unix network isn't properly working on AIX 7.2 with + // Technical Level < 2. + // The information is retrieved only once in this init() + // instead of everytime testableNetwork is called. + out, _ := exec.Command("oslevel", "-s").Output() + if len(out) >= len("7200-XX-ZZ-YYMM") { // AIX 7.2, Tech Level XX, Service Pack ZZ, date YYMM + aixVer := string(out[:4]) + tl, _ := strconv.Atoi(string(out[5:7])) + unixEnabledOnAIX = aixVer > "7200" || (aixVer == "7200" && tl >= 2) + } + } +} + +func supportsUnixSocket() bool { + switch runtime.GOOS { + case "android", "ios": + return false + case "aix": + return unixEnabledOnAIX + } + return true +} diff --git a/go/src/net/platform_windows_test.go b/go/src/net/platform_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ec2c861e80142e1a1edc685e73485ebbad40bc21 --- /dev/null +++ b/go/src/net/platform_windows_test.go @@ -0,0 +1,11 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "internal/syscall/windows" + +func supportsUnixSocket() bool { + return windows.SupportUnixSocket() +} diff --git a/go/src/net/port.go b/go/src/net/port.go new file mode 100644 index 0000000000000000000000000000000000000000..32e76286193c23ca2a196e9ddceaab33b7f0f5ac --- /dev/null +++ b/go/src/net/port.go @@ -0,0 +1,62 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +// parsePort parses service as a decimal integer and returns the +// corresponding value as port. It is the caller's responsibility to +// parse service as a non-decimal integer when needsLookup is true. +// +// Some system resolvers will return a valid port number when given a number +// over 65536 (see https://golang.org/issues/11715). Alas, the parser +// can't bail early on numbers > 65536. Therefore reasonably large/small +// numbers are parsed in full and rejected if invalid. +func parsePort(service string) (port int, needsLookup bool) { + if service == "" { + // Lock in the legacy behavior that an empty string + // means port 0. See golang.org/issue/13610. + return 0, false + } + const ( + max = uint32(1<<32 - 1) + cutoff = uint32(1 << 30) + ) + neg := false + if service[0] == '+' { + service = service[1:] + } else if service[0] == '-' { + neg = true + service = service[1:] + } + var n uint32 + for _, d := range service { + if '0' <= d && d <= '9' { + d -= '0' + } else { + return 0, true + } + if n >= cutoff { + n = max + break + } + n *= 10 + nn := n + uint32(d) + if nn < n || nn > max { + n = max + break + } + n = nn + } + if !neg && n >= cutoff { + port = int(cutoff - 1) + } else if neg && n > cutoff { + port = int(cutoff) + } else { + port = int(n) + } + if neg { + port = -port + } + return port, false +} diff --git a/go/src/net/port_test.go b/go/src/net/port_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e0bdb4247d31f51485f65dc53e49101b4154e290 --- /dev/null +++ b/go/src/net/port_test.go @@ -0,0 +1,52 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import "testing" + +var parsePortTests = []struct { + service string + port int + needsLookup bool +}{ + {"", 0, false}, + + // Decimal number literals + {"-1073741825", -1 << 30, false}, + {"-1073741824", -1 << 30, false}, + {"-1073741823", -(1<<30 - 1), false}, + {"-123456789", -123456789, false}, + {"-1", -1, false}, + {"-0", 0, false}, + {"0", 0, false}, + {"+0", 0, false}, + {"+1", 1, false}, + {"65535", 65535, false}, + {"65536", 65536, false}, + {"123456789", 123456789, false}, + {"1073741822", 1<<30 - 2, false}, + {"1073741823", 1<<30 - 1, false}, + {"1073741824", 1<<30 - 1, false}, + {"1073741825", 1<<30 - 1, false}, + + // Others + {"abc", 0, true}, + {"9pfs", 0, true}, + {"123badport", 0, true}, + {"bad123port", 0, true}, + {"badport123", 0, true}, + {"123456789badport", 0, true}, + {"-2147483649badport", 0, true}, + {"2147483649badport", 0, true}, +} + +func TestParsePort(t *testing.T) { + // The following test cases are cribbed from the strconv + for _, tt := range parsePortTests { + if port, needsLookup := parsePort(tt.service); port != tt.port || needsLookup != tt.needsLookup { + t.Errorf("parsePort(%q) = %d, %t; want %d, %t", tt.service, port, needsLookup, tt.port, tt.needsLookup) + } + } +} diff --git a/go/src/net/port_unix.go b/go/src/net/port_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..df73dbabb3c25fa5c754980e4f53c5d85815629a --- /dev/null +++ b/go/src/net/port_unix.go @@ -0,0 +1,57 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || js || wasip1 + +// Read system port mappings from /etc/services + +package net + +import ( + "internal/bytealg" + "sync" +) + +var onceReadServices sync.Once + +func readServices() { + file, err := open("/etc/services") + if err != nil { + return + } + defer file.close() + + for line, ok := file.readLine(); ok; line, ok = file.readLine() { + // "http 80/tcp www www-http # World Wide Web HTTP" + if i := bytealg.IndexByteString(line, '#'); i >= 0 { + line = line[:i] + } + f := getFields(line) + if len(f) < 2 { + continue + } + portnet := f[1] // "80/tcp" + port, j, ok := dtoi(portnet) + if !ok || port <= 0 || j >= len(portnet) || portnet[j] != '/' { + continue + } + netw := portnet[j+1:] // "tcp" + m, ok1 := services[netw] + if !ok1 { + m = make(map[string]int) + services[netw] = m + } + for i := 0; i < len(f); i++ { + if i != 1 { // f[1] was port/net + m[f[i]] = port + } + } + } +} + +// goLookupPort is the native Go implementation of LookupPort. +func goLookupPort(network, service string) (port int, err error) { + onceReadServices.Do(readServices) + return lookupPortMap(network, service) +} diff --git a/go/src/net/protoconn_test.go b/go/src/net/protoconn_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a617470580d5288b517fa3753d874dfb8193952d --- /dev/null +++ b/go/src/net/protoconn_test.go @@ -0,0 +1,352 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements API tests across platforms and will never have a build +// tag. + +package net + +import ( + "internal/testenv" + "os" + "runtime" + "testing" + "time" +) + +// The full stack test cases for IPConn have been moved to the +// following: +// golang.org/x/net/ipv4 +// golang.org/x/net/ipv6 +// golang.org/x/net/icmp + +func TestTCPListenerSpecificMethods(t *testing.T) { + switch runtime.GOOS { + case "plan9": + t.Skipf("not supported on %s", runtime.GOOS) + } + + la, err := ResolveTCPAddr("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + ln, err := ListenTCP("tcp4", la) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + ln.Addr() + mustSetDeadline(t, ln.SetDeadline, 30*time.Nanosecond) + + if c, err := ln.Accept(); err != nil { + if !err.(Error).Timeout() { + t.Fatal(err) + } + } else { + c.Close() + } + if c, err := ln.AcceptTCP(); err != nil { + if !err.(Error).Timeout() { + t.Fatal(err) + } + } else { + c.Close() + } + + if f, err := ln.File(); err != nil { + condFatalf(t, "file+net", "%v", err) + } else { + f.Close() + } +} + +func TestTCPConnSpecificMethods(t *testing.T) { + la, err := ResolveTCPAddr("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + ln, err := ListenTCP("tcp4", la) + if err != nil { + t.Fatal(err) + } + ch := make(chan error, 1) + handler := func(ls *localServer, ln Listener) { ls.transponder(ls.Listener, ch) } + ls := (&streamListener{Listener: ln}).newLocalServer() + defer ls.teardown() + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + + ra, err := ResolveTCPAddr("tcp4", ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + c, err := DialTCP("tcp4", nil, ra) + if err != nil { + t.Fatal(err) + } + defer c.Close() + c.SetKeepAlive(false) + c.SetKeepAlivePeriod(3 * time.Second) + c.SetLinger(0) + c.SetNoDelay(false) + c.LocalAddr() + c.RemoteAddr() + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + + if _, err := c.Write([]byte("TCPCONN TEST")); err != nil { + t.Fatal(err) + } + rb := make([]byte, 128) + if _, err := c.Read(rb); err != nil { + t.Fatal(err) + } + + for err := range ch { + t.Error(err) + } +} + +func TestUDPConnSpecificMethods(t *testing.T) { + la, err := ResolveUDPAddr("udp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + c, err := ListenUDP("udp4", la) + if err != nil { + t.Fatal(err) + } + defer c.Close() + c.LocalAddr() + c.RemoteAddr() + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + c.SetReadBuffer(2048) + c.SetWriteBuffer(2048) + + wb := []byte("UDPCONN TEST") + rb := make([]byte, 128) + if _, err := c.WriteToUDP(wb, c.LocalAddr().(*UDPAddr)); err != nil { + t.Fatal(err) + } + if _, _, err := c.ReadFromUDP(rb); err != nil { + t.Fatal(err) + } + if _, _, err := c.WriteMsgUDP(wb, nil, c.LocalAddr().(*UDPAddr)); err != nil { + condFatalf(t, c.LocalAddr().Network(), "%v", err) + } + if _, _, _, _, err := c.ReadMsgUDP(rb, nil); err != nil { + condFatalf(t, c.LocalAddr().Network(), "%v", err) + } + + if f, err := c.File(); err != nil { + condFatalf(t, "file+net", "%v", err) + } else { + f.Close() + } + + defer func() { + if p := recover(); p != nil { + t.Fatalf("panicked: %v", p) + } + }() + + c.WriteToUDP(wb, nil) + c.WriteMsgUDP(wb, nil, nil) +} + +func TestIPConnSpecificMethods(t *testing.T) { + if !testableNetwork("ip4") { + t.Skip("skipping: ip4 not supported") + } + + la, err := ResolveIPAddr("ip4", "127.0.0.1") + if err != nil { + t.Fatal(err) + } + c, err := ListenIP("ip4:icmp", la) + if testenv.SyscallIsNotSupported(err) { + // May be inside a container that disallows creating a socket or + // not running as root. + t.Skipf("skipping: %v", err) + } else if err != nil { + t.Fatal(err) + } + defer c.Close() + c.LocalAddr() + c.RemoteAddr() + c.SetDeadline(time.Now().Add(someTimeout)) + c.SetReadDeadline(time.Now().Add(someTimeout)) + c.SetWriteDeadline(time.Now().Add(someTimeout)) + c.SetReadBuffer(2048) + c.SetWriteBuffer(2048) + + if f, err := c.File(); err != nil { + condFatalf(t, "file+net", "%v", err) + } else { + f.Close() + } + + defer func() { + if p := recover(); p != nil { + t.Fatalf("panicked: %v", p) + } + }() + + wb := []byte("IPCONN TEST") + c.WriteToIP(wb, nil) + c.WriteMsgIP(wb, nil, nil) +} + +func TestUnixListenerSpecificMethods(t *testing.T) { + if !testableNetwork("unix") { + t.Skip("unix test") + } + + addr := testUnixAddr(t) + la, err := ResolveUnixAddr("unix", addr) + if err != nil { + t.Fatal(err) + } + ln, err := ListenUnix("unix", la) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + defer os.Remove(addr) + ln.Addr() + mustSetDeadline(t, ln.SetDeadline, 30*time.Nanosecond) + + if c, err := ln.Accept(); err != nil { + if !err.(Error).Timeout() { + t.Fatal(err) + } + } else { + c.Close() + } + if c, err := ln.AcceptUnix(); err != nil { + if !err.(Error).Timeout() { + t.Fatal(err) + } + } else { + c.Close() + } + + if f, err := ln.File(); err != nil { + condFatalf(t, "file+net", "%v", err) + } else { + f.Close() + } +} + +func TestUnixConnSpecificMethods(t *testing.T) { + if !testableNetwork("unixgram") { + t.Skip("unixgram test") + } + + addr1, addr2, addr3 := testUnixAddr(t), testUnixAddr(t), testUnixAddr(t) + + a1, err := ResolveUnixAddr("unixgram", addr1) + if err != nil { + t.Fatal(err) + } + c1, err := DialUnix("unixgram", a1, nil) + if err != nil { + t.Fatal(err) + } + defer c1.Close() + defer os.Remove(addr1) + c1.LocalAddr() + c1.RemoteAddr() + c1.SetDeadline(time.Now().Add(someTimeout)) + c1.SetReadDeadline(time.Now().Add(someTimeout)) + c1.SetWriteDeadline(time.Now().Add(someTimeout)) + c1.SetReadBuffer(2048) + c1.SetWriteBuffer(2048) + + a2, err := ResolveUnixAddr("unixgram", addr2) + if err != nil { + t.Fatal(err) + } + c2, err := DialUnix("unixgram", a2, nil) + if err != nil { + t.Fatal(err) + } + defer c2.Close() + defer os.Remove(addr2) + c2.LocalAddr() + c2.RemoteAddr() + c2.SetDeadline(time.Now().Add(someTimeout)) + c2.SetReadDeadline(time.Now().Add(someTimeout)) + c2.SetWriteDeadline(time.Now().Add(someTimeout)) + c2.SetReadBuffer(2048) + c2.SetWriteBuffer(2048) + + a3, err := ResolveUnixAddr("unixgram", addr3) + if err != nil { + t.Fatal(err) + } + c3, err := ListenUnixgram("unixgram", a3) + if err != nil { + t.Fatal(err) + } + defer c3.Close() + defer os.Remove(addr3) + c3.LocalAddr() + c3.RemoteAddr() + c3.SetDeadline(time.Now().Add(someTimeout)) + c3.SetReadDeadline(time.Now().Add(someTimeout)) + c3.SetWriteDeadline(time.Now().Add(someTimeout)) + c3.SetReadBuffer(2048) + c3.SetWriteBuffer(2048) + + wb := []byte("UNIXCONN TEST") + rb1 := make([]byte, 128) + rb2 := make([]byte, 128) + rb3 := make([]byte, 128) + if _, _, err := c1.WriteMsgUnix(wb, nil, a2); err != nil { + t.Fatal(err) + } + if _, _, _, _, err := c2.ReadMsgUnix(rb2, nil); err != nil { + t.Fatal(err) + } + if _, err := c2.WriteToUnix(wb, a1); err != nil { + t.Fatal(err) + } + if _, _, err := c1.ReadFromUnix(rb1); err != nil { + t.Fatal(err) + } + if _, err := c3.WriteToUnix(wb, a1); err != nil { + t.Fatal(err) + } + if _, _, err := c1.ReadFromUnix(rb1); err != nil { + t.Fatal(err) + } + if _, err := c2.WriteToUnix(wb, a3); err != nil { + t.Fatal(err) + } + if _, _, err := c3.ReadFromUnix(rb3); err != nil { + t.Fatal(err) + } + + if f, err := c1.File(); err != nil { + condFatalf(t, "file+net", "%v", err) + } else { + f.Close() + } + + defer func() { + if p := recover(); p != nil { + t.Fatalf("panicked: %v", p) + } + }() + + c1.WriteToUnix(wb, nil) + c1.WriteMsgUnix(wb, nil, nil) + c3.WriteToUnix(wb, nil) + c3.WriteMsgUnix(wb, nil, nil) +} diff --git a/go/src/net/rawconn.go b/go/src/net/rawconn.go new file mode 100644 index 0000000000000000000000000000000000000000..19228e94ed9e44eb9ff50f7f778518da294be887 --- /dev/null +++ b/go/src/net/rawconn.go @@ -0,0 +1,107 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "internal/poll" + "runtime" + "syscall" +) + +// BUG(tmm1): On Windows, the Write method of syscall.RawConn +// does not integrate with the runtime's network poller. It cannot +// wait for the connection to become writeable, and does not respect +// deadlines. If the user-provided callback returns false, the Write +// method will fail immediately. + +// BUG(mikio): On JS and Plan 9, the Control, Read and Write +// methods of syscall.RawConn are not implemented. + +type rawConn struct { + fd *netFD +} + +func (c *rawConn) ok() bool { return c != nil && c.fd != nil } + +func (c *rawConn) Control(f func(uintptr)) error { + if !c.ok() { + return syscall.EINVAL + } + err := c.fd.pfd.RawControl(f) + runtime.KeepAlive(c.fd) + if err != nil { + err = &OpError{Op: "raw-control", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err} + } + return err +} + +func (c *rawConn) Read(f func(uintptr) bool) error { + if !c.ok() { + return syscall.EINVAL + } + err := c.fd.pfd.RawRead(f) + runtime.KeepAlive(c.fd) + if err != nil { + err = &OpError{Op: "raw-read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return err +} + +func (c *rawConn) Write(f func(uintptr) bool) error { + if !c.ok() { + return syscall.EINVAL + } + err := c.fd.pfd.RawWrite(f) + runtime.KeepAlive(c.fd) + if err != nil { + err = &OpError{Op: "raw-write", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err} + } + return err +} + +// PollFD returns the poll.FD of the underlying connection. +// +// Other packages in std that also import [internal/poll] (such as os) +// can use a type assertion to access this extension method so that +// they can pass the *poll.FD to functions like poll.Splice. +// +// PollFD is not intended for use outside the standard library. +func (c *rawConn) PollFD() *poll.FD { + if !c.ok() { + return nil + } + return &c.fd.pfd +} + +func newRawConn(fd *netFD) *rawConn { + return &rawConn{fd: fd} +} + +// Network returns the network type of the underlying connection. +// +// Other packages in std that import internal/poll and are unable to +// import net (such as os) can use a type assertion to access this +// extension method so that they can distinguish different socket types. +// +// Network is not intended for use outside the standard library. +func (c *rawConn) Network() poll.String { + return poll.String(c.fd.net) +} + +type rawListener struct { + rawConn +} + +func (l *rawListener) Read(func(uintptr) bool) error { + return syscall.EINVAL +} + +func (l *rawListener) Write(func(uintptr) bool) error { + return syscall.EINVAL +} + +func newRawListener(fd *netFD) *rawListener { + return &rawListener{rawConn{fd: fd}} +} diff --git a/go/src/net/rawconn_stub_test.go b/go/src/net/rawconn_stub_test.go new file mode 100644 index 0000000000000000000000000000000000000000..6d54f2df55be1516af9f562e8f25bd17b813155e --- /dev/null +++ b/go/src/net/rawconn_stub_test.go @@ -0,0 +1,28 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js || plan9 || wasip1 + +package net + +import ( + "errors" + "syscall" +) + +func readRawConn(c syscall.RawConn, b []byte) (int, error) { + return 0, errors.New("not supported") +} + +func writeRawConn(c syscall.RawConn, b []byte) error { + return errors.New("not supported") +} + +func controlRawConn(c syscall.RawConn, addr Addr) error { + return errors.New("not supported") +} + +func controlOnConnSetup(network string, address string, c syscall.RawConn) error { + return nil +} diff --git a/go/src/net/rawconn_test.go b/go/src/net/rawconn_test.go new file mode 100644 index 0000000000000000000000000000000000000000..70b16c411534a1a7ff39288cb65159f4f894350d --- /dev/null +++ b/go/src/net/rawconn_test.go @@ -0,0 +1,209 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "bytes" + "runtime" + "testing" + "time" +) + +func TestRawConnReadWrite(t *testing.T) { + switch runtime.GOOS { + case "plan9", "js", "wasip1": + t.Skipf("not supported on %s", runtime.GOOS) + } + + t.Run("TCP", func(t *testing.T) { + handler := func(ls *localServer, ln Listener) { + c, err := ln.Accept() + if err != nil { + t.Error(err) + return + } + defer c.Close() + + cc, err := ln.(*TCPListener).SyscallConn() + if err != nil { + t.Fatal(err) + } + called := false + op := func(uintptr) bool { + called = true + return true + } + err = cc.Write(op) + if err == nil { + t.Error("Write should return an error") + } + if called { + t.Error("Write shouldn't call op") + } + called = false + err = cc.Read(op) + if err == nil { + t.Error("Read should return an error") + } + if called { + t.Error("Read shouldn't call op") + } + + var b [32]byte + n, err := c.Read(b[:]) + if err != nil { + t.Error(err) + return + } + if _, err := c.Write(b[:n]); err != nil { + t.Error(err) + return + } + } + ls := newLocalServer(t, "tcp") + defer ls.teardown() + if err := ls.buildup(handler); err != nil { + t.Fatal(err) + } + + c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + + cc, err := c.(*TCPConn).SyscallConn() + if err != nil { + t.Fatal(err) + } + data := []byte("HELLO-R-U-THERE") + if err := writeRawConn(cc, data); err != nil { + t.Fatal(err) + } + var b [32]byte + n, err := readRawConn(cc, b[:]) + if err != nil { + t.Fatal(err) + } + if bytes.Compare(b[:n], data) != 0 { + t.Fatalf("got %q; want %q", b[:n], data) + } + }) + t.Run("Deadline", func(t *testing.T) { + switch runtime.GOOS { + case "windows": + t.Skipf("not supported on %s", runtime.GOOS) + } + + ln := newLocalListener(t, "tcp") + defer ln.Close() + + c, err := Dial(ln.Addr().Network(), ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + + cc, err := c.(*TCPConn).SyscallConn() + if err != nil { + t.Fatal(err) + } + var b [1]byte + + c.SetDeadline(noDeadline) + if err := c.SetDeadline(time.Now().Add(-1)); err != nil { + t.Fatal(err) + } + if err = writeRawConn(cc, b[:]); err == nil { + t.Fatal("Write should fail") + } + if perr := parseWriteError(err); perr != nil { + t.Error(perr) + } + if !isDeadlineExceeded(err) { + t.Errorf("got %v; want timeout", err) + } + if _, err = readRawConn(cc, b[:]); err == nil { + t.Fatal("Read should fail") + } + if perr := parseReadError(err); perr != nil { + t.Error(perr) + } + if !isDeadlineExceeded(err) { + t.Errorf("got %v; want timeout", err) + } + + c.SetReadDeadline(noDeadline) + if err := c.SetReadDeadline(time.Now().Add(-1)); err != nil { + t.Fatal(err) + } + if _, err = readRawConn(cc, b[:]); err == nil { + t.Fatal("Read should fail") + } + if perr := parseReadError(err); perr != nil { + t.Error(perr) + } + if !isDeadlineExceeded(err) { + t.Errorf("got %v; want timeout", err) + } + + c.SetWriteDeadline(noDeadline) + if err := c.SetWriteDeadline(time.Now().Add(-1)); err != nil { + t.Fatal(err) + } + if err = writeRawConn(cc, b[:]); err == nil { + t.Fatal("Write should fail") + } + if perr := parseWriteError(err); perr != nil { + t.Error(perr) + } + if !isDeadlineExceeded(err) { + t.Errorf("got %v; want timeout", err) + } + }) +} + +func TestRawConnControl(t *testing.T) { + switch runtime.GOOS { + case "plan9", "js", "wasip1": + t.Skipf("not supported on %s", runtime.GOOS) + } + + t.Run("TCP", func(t *testing.T) { + ln := newLocalListener(t, "tcp") + defer ln.Close() + + cc1, err := ln.(*TCPListener).SyscallConn() + if err != nil { + t.Fatal(err) + } + if err := controlRawConn(cc1, ln.Addr()); err != nil { + t.Fatal(err) + } + + c, err := Dial(ln.Addr().Network(), ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + + cc2, err := c.(*TCPConn).SyscallConn() + if err != nil { + t.Fatal(err) + } + if err := controlRawConn(cc2, c.LocalAddr()); err != nil { + t.Fatal(err) + } + + ln.Close() + if err := controlRawConn(cc1, ln.Addr()); err == nil { + t.Fatal("Control after Close should fail") + } + c.Close() + if err := controlRawConn(cc2, c.LocalAddr()); err == nil { + t.Fatal("Control after Close should fail") + } + }) +} diff --git a/go/src/net/rawconn_unix_test.go b/go/src/net/rawconn_unix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f11119ed9ec0da04cd04e1ca48452229efa7803c --- /dev/null +++ b/go/src/net/rawconn_unix_test.go @@ -0,0 +1,115 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package net + +import ( + "errors" + "syscall" +) + +func readRawConn(c syscall.RawConn, b []byte) (int, error) { + var operr error + var n int + err := c.Read(func(s uintptr) bool { + n, operr = syscall.Read(int(s), b) + if operr == syscall.EAGAIN { + return false + } + return true + }) + if err != nil { + return n, err + } + return n, operr +} + +func writeRawConn(c syscall.RawConn, b []byte) error { + var operr error + err := c.Write(func(s uintptr) bool { + _, operr = syscall.Write(int(s), b) + if operr == syscall.EAGAIN { + return false + } + return true + }) + if err != nil { + return err + } + return operr +} + +func controlRawConn(c syscall.RawConn, addr Addr) error { + var operr error + fn := func(s uintptr) { + _, operr = syscall.GetsockoptInt(int(s), syscall.SOL_SOCKET, syscall.SO_REUSEADDR) + if operr != nil { + return + } + switch addr := addr.(type) { + case *TCPAddr: + // There's no guarantee that IP-level socket + // options work well with dual stack sockets. + // A simple solution would be to take a look + // at the bound address to the raw connection + // and to classify the address family of the + // underlying socket by the bound address: + // + // - When IP.To16() != nil and IP.To4() == nil, + // we can assume that the raw connection + // consists of an IPv6 socket using only + // IPv6 addresses. + // + // - When IP.To16() == nil and IP.To4() != nil, + // the raw connection consists of an IPv4 + // socket using only IPv4 addresses. + // + // - Otherwise, the raw connection is a dual + // stack socket, an IPv6 socket using IPv6 + // addresses including IPv4-mapped or + // IPv4-embedded IPv6 addresses. + if addr.IP.To16() != nil && addr.IP.To4() == nil { + operr = syscall.SetsockoptInt(int(s), syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS, 1) + } else if addr.IP.To16() == nil && addr.IP.To4() != nil { + operr = syscall.SetsockoptInt(int(s), syscall.IPPROTO_IP, syscall.IP_TTL, 1) + } + } + } + if err := c.Control(fn); err != nil { + return err + } + return operr +} + +func controlOnConnSetup(network string, address string, c syscall.RawConn) error { + var operr error + var fn func(uintptr) + switch network { + case "tcp", "udp", "ip": + return errors.New("ambiguous network: " + network) + case "unix", "unixpacket", "unixgram": + fn = func(s uintptr) { + _, operr = syscall.GetsockoptInt(int(s), syscall.SOL_SOCKET, syscall.SO_ERROR) + } + default: + switch network[len(network)-1] { + case '4': + fn = func(s uintptr) { + operr = syscall.SetsockoptInt(int(s), syscall.IPPROTO_IP, syscall.IP_TTL, 1) + } + case '6': + fn = func(s uintptr) { + operr = syscall.SetsockoptInt(int(s), syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS, 1) + } + default: + return errors.New("unknown network: " + network) + } + } + if err := c.Control(fn); err != nil { + return err + } + return operr +} diff --git a/go/src/net/rawconn_windows_test.go b/go/src/net/rawconn_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ebfec3499a2fdd9e0c7eff7ee511b402a3a9589b --- /dev/null +++ b/go/src/net/rawconn_windows_test.go @@ -0,0 +1,121 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package net + +import ( + "errors" + "syscall" + "unsafe" +) + +func readRawConn(c syscall.RawConn, b []byte) (int, error) { + var operr error + var n int + err := c.Read(func(s uintptr) bool { + var read uint32 + var flags uint32 + var buf syscall.WSABuf + buf.Buf = &b[0] + buf.Len = uint32(len(b)) + operr = syscall.WSARecv(syscall.Handle(s), &buf, 1, &read, &flags, nil, nil) + n = int(read) + return true + }) + if err != nil { + return n, err + } + return n, operr +} + +func writeRawConn(c syscall.RawConn, b []byte) error { + var operr error + err := c.Write(func(s uintptr) bool { + var written uint32 + var buf syscall.WSABuf + buf.Buf = &b[0] + buf.Len = uint32(len(b)) + operr = syscall.WSASend(syscall.Handle(s), &buf, 1, &written, 0, nil, nil) + return true + }) + if err != nil { + return err + } + return operr +} + +func controlRawConn(c syscall.RawConn, addr Addr) error { + var operr error + fn := func(s uintptr) { + var v, l int32 + l = int32(unsafe.Sizeof(v)) + operr = syscall.Getsockopt(syscall.Handle(s), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, (*byte)(unsafe.Pointer(&v)), &l) + if operr != nil { + return + } + switch addr := addr.(type) { + case *TCPAddr: + // There's no guarantee that IP-level socket + // options work well with dual stack sockets. + // A simple solution would be to take a look + // at the bound address to the raw connection + // and to classify the address family of the + // underlying socket by the bound address: + // + // - When IP.To16() != nil and IP.To4() == nil, + // we can assume that the raw connection + // consists of an IPv6 socket using only + // IPv6 addresses. + // + // - When IP.To16() == nil and IP.To4() != nil, + // the raw connection consists of an IPv4 + // socket using only IPv4 addresses. + // + // - Otherwise, the raw connection is a dual + // stack socket, an IPv6 socket using IPv6 + // addresses including IPv4-mapped or + // IPv4-embedded IPv6 addresses. + if addr.IP.To16() != nil && addr.IP.To4() == nil { + operr = syscall.SetsockoptInt(syscall.Handle(s), syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS, 1) + } else if addr.IP.To16() == nil && addr.IP.To4() != nil { + operr = syscall.SetsockoptInt(syscall.Handle(s), syscall.IPPROTO_IP, syscall.IP_TTL, 1) + } + } + } + if err := c.Control(fn); err != nil { + return err + } + return operr +} + +func controlOnConnSetup(network string, address string, c syscall.RawConn) error { + var operr error + var fn func(uintptr) + switch network { + case "tcp", "udp", "ip": + return errors.New("ambiguous network: " + network) + case "unix", "unixpacket", "unixgram": + fn = func(s uintptr) { + const SO_ERROR = 0x1007 + _, operr = syscall.GetsockoptInt(syscall.Handle(s), syscall.SOL_SOCKET, SO_ERROR) + } + default: + switch network[len(network)-1] { + case '4': + fn = func(s uintptr) { + operr = syscall.SetsockoptInt(syscall.Handle(s), syscall.IPPROTO_IP, syscall.IP_TTL, 1) + } + case '6': + fn = func(s uintptr) { + operr = syscall.SetsockoptInt(syscall.Handle(s), syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS, 1) + } + default: + return errors.New("unknown network: " + network) + } + } + if err := c.Control(fn); err != nil { + return err + } + return operr +} diff --git a/go/test/dwarf/dwarf.dir/main.go b/go/test/dwarf/dwarf.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..175a09c7799734082fe0c69d704d40558f1eb952 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/main.go @@ -0,0 +1,32 @@ +// $G $D/$F.go $D/z*.go && $L $F.$A && ./$A.out + +// NOTE: This test is not run by 'run.go' and so not run by all.bash. +// To run this test you must use the ./run shell script. + +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main +func main() { +F1() +F2() +F3() +F4() +F5() +F6() +F7() +F8() +F9() +F10() +F11() +F12() +F13() +F14() +F15() +F16() +F17() +F18() +F19() +F20() +} diff --git a/go/test/dwarf/dwarf.dir/z1.go b/go/test/dwarf/dwarf.dir/z1.go new file mode 100644 index 0000000000000000000000000000000000000000..7f163e9a1d97c4f3fb1afd4f3bd57f8415e95b8a --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z1.go @@ -0,0 +1,5 @@ + + +//line x1.go:4 +package main +func F1() {} diff --git a/go/test/dwarf/dwarf.dir/z10.go b/go/test/dwarf/dwarf.dir/z10.go new file mode 100644 index 0000000000000000000000000000000000000000..19c70020e0ca367624a97a47be7256aebee1f32b --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z10.go @@ -0,0 +1,6 @@ + + + +//line x10.go:4 +package main +func F10() {} diff --git a/go/test/dwarf/dwarf.dir/z11.go b/go/test/dwarf/dwarf.dir/z11.go new file mode 100644 index 0000000000000000000000000000000000000000..c1d2f9180f11752e79734507a7d041d193c80903 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z11.go @@ -0,0 +1,4 @@ + +//line x11.go:4 +package main +func F11() {} diff --git a/go/test/dwarf/dwarf.dir/z12.go b/go/test/dwarf/dwarf.dir/z12.go new file mode 100644 index 0000000000000000000000000000000000000000..7455f18946826965937e88b17cf613e9802f410d --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z12.go @@ -0,0 +1,4 @@ + +//line x12.go:4 +package main +func F12() {} diff --git a/go/test/dwarf/dwarf.dir/z13.go b/go/test/dwarf/dwarf.dir/z13.go new file mode 100644 index 0000000000000000000000000000000000000000..ecb3c4c8c711dba7e20d8fdfaba1f47389a4c720 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z13.go @@ -0,0 +1,4 @@ + +//line x13.go:4 +package main +func F13() {} diff --git a/go/test/dwarf/dwarf.dir/z14.go b/go/test/dwarf/dwarf.dir/z14.go new file mode 100644 index 0000000000000000000000000000000000000000..134b39b64e2bda6b4bf3fd9da6c4419590546971 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z14.go @@ -0,0 +1,4 @@ + +//line x14.go:4 +package main +func F14() {} diff --git a/go/test/dwarf/dwarf.dir/z15.go b/go/test/dwarf/dwarf.dir/z15.go new file mode 100644 index 0000000000000000000000000000000000000000..d73819b443ba1b7734261eb0fc9ec7e262022c1f --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z15.go @@ -0,0 +1,4 @@ + +//line x15.go:4 +package main +func F15() {} diff --git a/go/test/dwarf/dwarf.dir/z16.go b/go/test/dwarf/dwarf.dir/z16.go new file mode 100644 index 0000000000000000000000000000000000000000..6c31651baa891e4ebff5e8a061e05a060fd336f3 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z16.go @@ -0,0 +1,4 @@ + +//line x16.go:4 +package main +func F16() {} diff --git a/go/test/dwarf/dwarf.dir/z17.go b/go/test/dwarf/dwarf.dir/z17.go new file mode 100644 index 0000000000000000000000000000000000000000..b742d1672606cabc4b9fc31cdb3e039f69481186 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z17.go @@ -0,0 +1,4 @@ + +//line x17.go:4 +package main +func F17() {} diff --git a/go/test/dwarf/dwarf.dir/z18.go b/go/test/dwarf/dwarf.dir/z18.go new file mode 100644 index 0000000000000000000000000000000000000000..84150ff0a35569ddbdcc45021f3200f377443324 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z18.go @@ -0,0 +1,5 @@ + + +//line x18.go:4 +package main +func F18() {} diff --git a/go/test/dwarf/dwarf.dir/z19.go b/go/test/dwarf/dwarf.dir/z19.go new file mode 100644 index 0000000000000000000000000000000000000000..bb2e29684174f20a92926ec988ba9daad1f3d47b --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z19.go @@ -0,0 +1,4 @@ + +//line x19.go:4 +package main +func F19() {} diff --git a/go/test/dwarf/dwarf.dir/z2.go b/go/test/dwarf/dwarf.dir/z2.go new file mode 100644 index 0000000000000000000000000000000000000000..68bd58257d9a025d26459c9f471278fd6a131e18 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z2.go @@ -0,0 +1,4 @@ + +//line x2.go:4 +package main +func F2() {} diff --git a/go/test/dwarf/dwarf.dir/z20.go b/go/test/dwarf/dwarf.dir/z20.go new file mode 100644 index 0000000000000000000000000000000000000000..03111e184521d6a5535cc22ca60d42cfef73ca3c --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z20.go @@ -0,0 +1,4 @@ + +//line x20.go:4 +package main +func F20() {} diff --git a/go/test/dwarf/dwarf.dir/z3.go b/go/test/dwarf/dwarf.dir/z3.go new file mode 100644 index 0000000000000000000000000000000000000000..5e4ad3ae257df2bdbeaee6e382005121e049188d --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z3.go @@ -0,0 +1,4 @@ + +//line x3.go:4 +package main +func F3() {} diff --git a/go/test/dwarf/dwarf.dir/z4.go b/go/test/dwarf/dwarf.dir/z4.go new file mode 100644 index 0000000000000000000000000000000000000000..1f28465c57714f35f4dbac9b173f32a5b424fa26 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z4.go @@ -0,0 +1,4 @@ + +//line x4.go:4 +package main +func F4() {} diff --git a/go/test/dwarf/dwarf.dir/z5.go b/go/test/dwarf/dwarf.dir/z5.go new file mode 100644 index 0000000000000000000000000000000000000000..7f4eeb419a35bcec5bdb83f1b767a4032df4570e --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z5.go @@ -0,0 +1,4 @@ + +//line x5.go:4 +package main +func F5() {} diff --git a/go/test/dwarf/dwarf.dir/z6.go b/go/test/dwarf/dwarf.dir/z6.go new file mode 100644 index 0000000000000000000000000000000000000000..241791dff2b0e003fa592d70e4752689e51e81ef --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z6.go @@ -0,0 +1,4 @@ + +//line x6.go:4 +package main +func F6() {} diff --git a/go/test/dwarf/dwarf.dir/z7.go b/go/test/dwarf/dwarf.dir/z7.go new file mode 100644 index 0000000000000000000000000000000000000000..68c1ad0c2434ad098addca086e34a88998456372 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z7.go @@ -0,0 +1,4 @@ + +//line x7.go:4 +package main +func F7() {} diff --git a/go/test/dwarf/dwarf.dir/z8.go b/go/test/dwarf/dwarf.dir/z8.go new file mode 100644 index 0000000000000000000000000000000000000000..16eed32a28d3c4bcca08507f31ff5e3508f68438 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z8.go @@ -0,0 +1,4 @@ + +//line x8.go:4 +package main +func F8() {} diff --git a/go/test/dwarf/dwarf.dir/z9.go b/go/test/dwarf/dwarf.dir/z9.go new file mode 100644 index 0000000000000000000000000000000000000000..cbb94b4d2beddef80e39ec29177b561725c920a3 --- /dev/null +++ b/go/test/dwarf/dwarf.dir/z9.go @@ -0,0 +1,4 @@ + +//line x9.go:4 +package main +func F9() {} diff --git a/go/test/fixedbugs/bug083.dir/bug0.go b/go/test/fixedbugs/bug083.dir/bug0.go new file mode 100644 index 0000000000000000000000000000000000000000..2f59d81a614d4857ec61f5e786a2e1f0a544bfb4 --- /dev/null +++ b/go/test/fixedbugs/bug083.dir/bug0.go @@ -0,0 +1,10 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug0 + +type t0 struct { +} + +var V0 t0 diff --git a/go/test/fixedbugs/bug083.dir/bug1.go b/go/test/fixedbugs/bug083.dir/bug1.go new file mode 100644 index 0000000000000000000000000000000000000000..ea5bcfe205ad5da6f954bd31cdc317537f8ab457 --- /dev/null +++ b/go/test/fixedbugs/bug083.dir/bug1.go @@ -0,0 +1,14 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug1 + +import "./bug0" + +// This is expected to fail--t0 is in package bug0 and should not be +// visible here in package bug1. The test for failure is in +// ../bug083.go. + +var v1 bug0.t0; // ERROR "bug0" + diff --git a/go/test/fixedbugs/bug088.dir/bug0.go b/go/test/fixedbugs/bug088.dir/bug0.go new file mode 100644 index 0000000000000000000000000000000000000000..7a6e34747f6605013de116965fbbfb8146b21a79 --- /dev/null +++ b/go/test/fixedbugs/bug088.dir/bug0.go @@ -0,0 +1,9 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug0 + +var V0 func() int; +var V1 func() (a int); +var V2 func() (a, b int); diff --git a/go/test/fixedbugs/bug088.dir/bug1.go b/go/test/fixedbugs/bug088.dir/bug1.go new file mode 100644 index 0000000000000000000000000000000000000000..2568e37d0209cef4ac690c094c2c2559298fff53 --- /dev/null +++ b/go/test/fixedbugs/bug088.dir/bug1.go @@ -0,0 +1,23 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import P "./bug0" + +func main() { + a0 := P.V0(); // works + a1 := P.V1(); // works + a2, b2 := P.V2(); // doesn't work + _, _, _, _ = a0, a1, a2, b2; +} + +/* +uetli:~/Source/go1/test/bugs/bug088.dir gri$ 6g bug0.go && 6g bug1.go +bug1.go:8: shape error across := +bug1.go:8: a2: undefined +bug1.go:8: b2: undefined +bug1.go:8: illegal types for operand: AS + (<(bug0)P.int32>INT32) +*/ diff --git a/go/test/fixedbugs/bug106.dir/bug0.go b/go/test/fixedbugs/bug106.dir/bug0.go new file mode 100644 index 0000000000000000000000000000000000000000..7494c580b77df90b611f873c52e4f3431aae6967 --- /dev/null +++ b/go/test/fixedbugs/bug106.dir/bug0.go @@ -0,0 +1,7 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug0 + +const A = -1 diff --git a/go/test/fixedbugs/bug106.dir/bug1.go b/go/test/fixedbugs/bug106.dir/bug1.go new file mode 100644 index 0000000000000000000000000000000000000000..eff0d36ed29532d38db96962fa511d18e9f10f93 --- /dev/null +++ b/go/test/fixedbugs/bug106.dir/bug1.go @@ -0,0 +1,8 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug1 + +import _ "./bug0" + diff --git a/go/test/fixedbugs/bug133.dir/bug0.go b/go/test/fixedbugs/bug133.dir/bug0.go new file mode 100644 index 0000000000000000000000000000000000000000..19a2bfbd4b545214ecd153ea7e7cf12c3a3f76a1 --- /dev/null +++ b/go/test/fixedbugs/bug133.dir/bug0.go @@ -0,0 +1,7 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug0 + +type T struct { i int } diff --git a/go/test/fixedbugs/bug133.dir/bug1.go b/go/test/fixedbugs/bug133.dir/bug1.go new file mode 100644 index 0000000000000000000000000000000000000000..dd59b2f2ec193b58a436c20f501c69c48e599c72 --- /dev/null +++ b/go/test/fixedbugs/bug133.dir/bug1.go @@ -0,0 +1,9 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug1 + +import "./bug0" + +type T struct { t bug0.T } diff --git a/go/test/fixedbugs/bug133.dir/bug2.go b/go/test/fixedbugs/bug133.dir/bug2.go new file mode 100644 index 0000000000000000000000000000000000000000..b6184c2e75b03e047441741e301690f16399a03a --- /dev/null +++ b/go/test/fixedbugs/bug133.dir/bug2.go @@ -0,0 +1,16 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug2 + +import _ "./bug1" +import "./bug0" + +type T2 struct { t bug0.T } + +func fn(p *T2) int { + // This reference should be invalid, because bug0.T.i is local + // to package bug0 and should not be visible in package bug1. + return p.t.i; // ERROR "field|undef" +} diff --git a/go/test/fixedbugs/bug160.dir/x.go b/go/test/fixedbugs/bug160.dir/x.go new file mode 100644 index 0000000000000000000000000000000000000000..2673552d80b8a6a2a6286ff79dc01987d2772ca9 --- /dev/null +++ b/go/test/fixedbugs/bug160.dir/x.go @@ -0,0 +1,8 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package x + +const Zero = 0.0 +const Ten = 10.0 diff --git a/go/test/fixedbugs/bug160.dir/y.go b/go/test/fixedbugs/bug160.dir/y.go new file mode 100644 index 0000000000000000000000000000000000000000..428808dd19879a0a56ce39b90a60363a19c914f4 --- /dev/null +++ b/go/test/fixedbugs/bug160.dir/y.go @@ -0,0 +1,19 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "os" +import "./x" + +func main() { + if x.Zero != 0 { + println("x.Zero = ", x.Zero); + os.Exit(1); + } + if x.Ten != 10 { + println("x.Ten = ", x.Ten); + os.Exit(1); + } +} diff --git a/go/test/fixedbugs/bug191.dir/a.go b/go/test/fixedbugs/bug191.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..139a8a3a2307d0814548dc16ba0a908e3a280e19 --- /dev/null +++ b/go/test/fixedbugs/bug191.dir/a.go @@ -0,0 +1,14 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var A int + +func init() { + A = 1 +} + +type T int; + diff --git a/go/test/fixedbugs/bug191.dir/b.go b/go/test/fixedbugs/bug191.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..36770f6fc99e3f814ec16dd13d4d2f305a81dc98 --- /dev/null +++ b/go/test/fixedbugs/bug191.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +var B int + +func init() { + B = 2 +} + +type V int; diff --git a/go/test/fixedbugs/bug191.dir/main.go b/go/test/fixedbugs/bug191.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2d24dd12d5293d97e7891dd52493e2e393e8cc68 --- /dev/null +++ b/go/test/fixedbugs/bug191.dir/main.go @@ -0,0 +1,17 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import . "./a" +import . "./b" + +var _ T +var _ V + +func main() { + if A != 1 || B != 2 { + panic("wrong vars") + } +} diff --git a/go/test/fixedbugs/bug222.dir/chanbug.go b/go/test/fixedbugs/bug222.dir/chanbug.go new file mode 100644 index 0000000000000000000000000000000000000000..16920246e00d2056e7978efbb73f1db77848de09 --- /dev/null +++ b/go/test/fixedbugs/bug222.dir/chanbug.go @@ -0,0 +1,9 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package chanbug +var C chan<- (chan int) +var D chan<- func() +var E func() chan int +var F func() (func()) diff --git a/go/test/fixedbugs/bug222.dir/chanbug2.go b/go/test/fixedbugs/bug222.dir/chanbug2.go new file mode 100644 index 0000000000000000000000000000000000000000..b6c416f83458d71b9930d05211ca712f66d034d1 --- /dev/null +++ b/go/test/fixedbugs/bug222.dir/chanbug2.go @@ -0,0 +1,7 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package Bar + +import _ "./chanbug" diff --git a/go/test/fixedbugs/bug248.dir/bug0.go b/go/test/fixedbugs/bug248.dir/bug0.go new file mode 100644 index 0000000000000000000000000000000000000000..78433f504d322f0d786a8dbd2a7a72ab08d91c70 --- /dev/null +++ b/go/test/fixedbugs/bug248.dir/bug0.go @@ -0,0 +1,13 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package p + +type T struct { + X, Y int +} + +type I interface { + M(T) +} diff --git a/go/test/fixedbugs/bug248.dir/bug1.go b/go/test/fixedbugs/bug248.dir/bug1.go new file mode 100644 index 0000000000000000000000000000000000000000..f1db77d2f5d31976a2af3c395e0e158f81400fdc --- /dev/null +++ b/go/test/fixedbugs/bug248.dir/bug1.go @@ -0,0 +1,13 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package q + +type T struct { + X, Y int +} + +type I interface { + M(T) +} diff --git a/go/test/fixedbugs/bug248.dir/bug2.go b/go/test/fixedbugs/bug248.dir/bug2.go new file mode 100644 index 0000000000000000000000000000000000000000..92a7974679eae10349fe8f4f7817cbf39fbf28dd --- /dev/null +++ b/go/test/fixedbugs/bug248.dir/bug2.go @@ -0,0 +1,73 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package s + +import ( + p0 "./bug0" + p1 "./bug1" +) + +// both p0.T and p1.T are struct { X, Y int }. + +var v0 p0.T +var v1 p1.T + +// interfaces involving the two + +type I0 interface { + M(p0.T) +} + +type I1 interface { + M(p1.T) +} + +// t0 satisfies I0 and p0.I +type t0 int + +func (t0) M(p0.T) {} + +// t1 satisfies I1 and p1.I +type t1 float64 + +func (t1) M(p1.T) {} + +// check static interface assignments +var i0 I0 = t0(0) // ok +var i1 I1 = t1(0) // ok + +var i2 I0 = t1(0) // ERROR "does not implement|incompatible" +var i3 I1 = t0(0) // ERROR "does not implement|incompatible" + +var p0i p0.I = t0(0) // ok +var p1i p1.I = t1(0) // ok + +var p0i1 p0.I = t1(0) // ERROR "does not implement|incompatible" +var p0i2 p1.I = t0(0) // ERROR "does not implement|incompatible" + +func foobar() { + // check that cannot assign one to the other, + // but can convert. + v0 = v1 // ERROR "assign|cannot use" + v1 = v0 // ERROR "assign|cannot use" + + v0 = p0.T(v1) + v1 = p1.T(v0) + + i0 = i1 // ERROR "cannot use|incompatible" + i1 = i0 // ERROR "cannot use|incompatible" + p0i = i1 // ERROR "cannot use|incompatible" + p1i = i0 // ERROR "cannot use|incompatible" + i0 = p1i // ERROR "cannot use|incompatible" + i1 = p0i // ERROR "cannot use|incompatible" + p0i = p1i // ERROR "cannot use|incompatible" + p1i = p0i // ERROR "cannot use|incompatible" + + i0 = p0i + p0i = i0 + + i1 = p1i + p1i = i1 +} diff --git a/go/test/fixedbugs/bug248.dir/bug3.go b/go/test/fixedbugs/bug248.dir/bug3.go new file mode 100644 index 0000000000000000000000000000000000000000..ba547d64a1074fd63facf0d7416a4284ffcfd40f --- /dev/null +++ b/go/test/fixedbugs/bug248.dir/bug3.go @@ -0,0 +1,105 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package main + +import ( + p0 "./bug0" + p1 "./bug1" + + "reflect" + "strings" +) + +var v0 p0.T +var v1 p1.T + +type I0 interface { + M(p0.T) +} + +type I1 interface { + M(p1.T) +} + +type t0 int + +func (t0) M(p0.T) {} + +type t1 float64 + +func (t1) M(p1.T) {} + +var i0 I0 = t0(0) // ok +var i1 I1 = t1(0) // ok + +var p0i p0.I = t0(0) // ok +var p1i p1.I = t1(0) // ok + +func main() { + // check that reflect paths are correct, + // meaning that reflect data for v0, v1 didn't get confused. + + // path is full (rooted) path name. check suffix for gc, prefix for gccgo + if s := reflect.TypeOf(v0).PkgPath(); !strings.HasSuffix(s, "/bug0") && !strings.HasPrefix(s, "bug0") { + println("bad v0 path", len(s), s) + panic("fail") + } + if s := reflect.TypeOf(v1).PkgPath(); !strings.HasSuffix(s, "/bug1") && !strings.HasPrefix(s, "bug1") { + println("bad v1 path", s) + panic("fail") + } + + // check that dynamic interface check doesn't get confused + var i interface{} = t0(0) + if _, ok := i.(I1); ok { + println("used t0 as i1") + panic("fail") + } + if _, ok := i.(p1.I); ok { + println("used t0 as p1.I") + panic("fail") + } + + i = t1(1) + if _, ok := i.(I0); ok { + println("used t1 as i0") + panic("fail") + } + if _, ok := i.(p0.I); ok { + println("used t1 as p0.I") + panic("fail") + } + + // check that type switch works. + // the worry is that if p0.T and p1.T have the same hash, + // the binary search will handle one of them incorrectly. + for j := 0; j < 3; j++ { + switch j { + case 0: + i = p0.T{} + case 1: + i = p1.T{} + case 2: + i = 3.14 + } + switch i.(type) { + case p0.T: + if j != 0 { + println("type switch p0.T") + panic("fail") + } + case p1.T: + if j != 1 { + println("type switch p1.T") + panic("fail") + } + default: + if j != 2 { + println("type switch default", j) + panic("fail") + } + } + } +} diff --git a/go/test/fixedbugs/bug282.dir/p1.go b/go/test/fixedbugs/bug282.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..0f7422c0ba0e2d68c30a28e4c702785daa2523f5 --- /dev/null +++ b/go/test/fixedbugs/bug282.dir/p1.go @@ -0,0 +1,10 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +type T struct { + f func() "x" +} + diff --git a/go/test/fixedbugs/bug282.dir/p2.go b/go/test/fixedbugs/bug282.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..f614507946602c75adfc1d76ba41b1908c7b9da7 --- /dev/null +++ b/go/test/fixedbugs/bug282.dir/p2.go @@ -0,0 +1,8 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p2 + +import _ "./p1" + diff --git a/go/test/fixedbugs/bug306.dir/p1.go b/go/test/fixedbugs/bug306.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..b28551807d663b885f3ff0e167651869367be5c3 --- /dev/null +++ b/go/test/fixedbugs/bug306.dir/p1.go @@ -0,0 +1,9 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +type T <-chan int +var x = make(chan T) + diff --git a/go/test/fixedbugs/bug306.dir/p2.go b/go/test/fixedbugs/bug306.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..f614507946602c75adfc1d76ba41b1908c7b9da7 --- /dev/null +++ b/go/test/fixedbugs/bug306.dir/p2.go @@ -0,0 +1,8 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p2 + +import _ "./p1" + diff --git a/go/test/fixedbugs/bug313.dir/a.go b/go/test/fixedbugs/bug313.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..335f84d4ba16b2e1fa2ae0c178429289ef991801 --- /dev/null +++ b/go/test/fixedbugs/bug313.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "fmt" + +func a() { + fmt.DoesNotExist() // ERROR "undefined" +} diff --git a/go/test/fixedbugs/bug313.dir/b.go b/go/test/fixedbugs/bug313.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..26e6413702fc3bcbff42d2765aeaa2c08783d88d --- /dev/null +++ b/go/test/fixedbugs/bug313.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import . "fmt" + +func b() { + Println() +} diff --git a/go/test/fixedbugs/bug322.dir/lib.go b/go/test/fixedbugs/bug322.dir/lib.go new file mode 100644 index 0000000000000000000000000000000000000000..0de56d3d649354e5196e2b2af18f520516083149 --- /dev/null +++ b/go/test/fixedbugs/bug322.dir/lib.go @@ -0,0 +1,15 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package lib + +type T struct { + x int // non-exported field +} + +func (t T) M() { +} + +func (t *T) PM() { +} diff --git a/go/test/fixedbugs/bug322.dir/main.go b/go/test/fixedbugs/bug322.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f403c7d32e2ac187a054100c679d97aa1c73a851 --- /dev/null +++ b/go/test/fixedbugs/bug322.dir/main.go @@ -0,0 +1,40 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./lib" + +type I interface { + M() +} + +type PI interface { + PM() +} + +func main() { + var t lib.T + t.M() + t.PM() + + // This is still an error. + // var i1 I = t + // i1.M() + + // This combination is illegal because + // PM requires a pointer receiver. + // var pi1 PI = t + // pi1.PM() + + var pt = &t + pt.M() + pt.PM() + + var i2 I = pt + i2.M() + + var pi2 PI = pt + pi2.PM() +} diff --git a/go/test/fixedbugs/bug324.dir/p.go b/go/test/fixedbugs/bug324.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..d1e3b991aada1d9775328bde4054610fd2255681 --- /dev/null +++ b/go/test/fixedbugs/bug324.dir/p.go @@ -0,0 +1,15 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Exported interface { + private() +} + +type Implementation struct{} + +func (p *Implementation) private() { println("p.Implementation.private()") } + +var X = new(Implementation) diff --git a/go/test/fixedbugs/bug324.dir/prog.go b/go/test/fixedbugs/bug324.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..3ab61f3eb5e87fecc23e7ffc92bd380f67ad5fc4 --- /dev/null +++ b/go/test/fixedbugs/bug324.dir/prog.go @@ -0,0 +1,53 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./p" +) + +type Exported interface { + private() +} + +type Implementation struct{} + +func (p *Implementation) private() {} + + +func main() { + // nothing unusual here + var x Exported + x = new(Implementation) + x.private() // main.Implementation.private() + + // same here - should be and is legal + var px p.Exported + px = p.X + + // this assignment is correctly illegal: + // px.private undefined (cannot refer to unexported field or method private) + // px.private() + + // this assignment is correctly illegal: + // *Implementation does not implement p.Exported (missing p.private method) + // px = new(Implementation) + + // this assignment is correctly illegal: + // p.Exported does not implement Exported (missing private method) + // x = px + + // this assignment unexpectedly compiles and then executes + defer func() { + recover() + }() + x = px.(Exported) + + println("should not get this far") + + // this is a legitimate call, but because of the previous assignment, + // it invokes the method private in p! + x.private() // p.Implementation.private() +} diff --git a/go/test/fixedbugs/bug335.dir/a.go b/go/test/fixedbugs/bug335.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..6ecc5c45ef89224d7f2a20272dc83b200c540e31 --- /dev/null +++ b/go/test/fixedbugs/bug335.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T interface{} + +func f() T { return nil } + +var Foo T = f() diff --git a/go/test/fixedbugs/bug335.dir/b.go b/go/test/fixedbugs/bug335.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..a7735a82e41e57a53d1e026127bc9b787c9a67fb --- /dev/null +++ b/go/test/fixedbugs/bug335.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var Bar = a.Foo diff --git a/go/test/fixedbugs/bug345.dir/io.go b/go/test/fixedbugs/bug345.dir/io.go new file mode 100644 index 0000000000000000000000000000000000000000..ca7a5092e9f849cbe04e70c23bf86b90646b4f66 --- /dev/null +++ b/go/test/fixedbugs/bug345.dir/io.go @@ -0,0 +1,15 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package io + +type Writer interface { + WrongWrite() +} + +type SectionReader struct { + X int +} + +func SR(*SectionReader) {} diff --git a/go/test/fixedbugs/bug345.dir/main.go b/go/test/fixedbugs/bug345.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..a53d3e8586ed553a73d847d6b8493a95bcb9a513 --- /dev/null +++ b/go/test/fixedbugs/bug345.dir/main.go @@ -0,0 +1,29 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "bufio" + goio "io" + + "./io" +) + +func main() { + // The errors here complain that io.X != io.X + // for different values of io so they should be + // showing the full import path, which for the + // "./io" import is really ..../go/test/io. + // For example: + // + // main.go:25: cannot use w (type "/Users/rsc/g/go/test/fixedbugs/bug345.dir/io".Writer) as type "io".Writer in function argument: + // io.Writer does not implement io.Writer (missing Write method) + // main.go:27: cannot use &x (type *"io".SectionReader) as type *"/Users/rsc/g/go/test/fixedbugs/bug345.dir/io".SectionReader in function argument + + var w io.Writer + bufio.NewWriter(w) // ERROR "[\w.]+[^.]/io|has incompatible type|cannot use" + var x goio.SectionReader + io.SR(&x) // ERROR "[\w.]+[^.]/io|has incompatible type|cannot use" +} diff --git a/go/test/fixedbugs/bug367.dir/p.go b/go/test/fixedbugs/bug367.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..2028f740ccdbe959c0501bf45cef7cb27a0e4935 --- /dev/null +++ b/go/test/fixedbugs/bug367.dir/p.go @@ -0,0 +1,19 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package p + +type T struct{ x int } +type S struct{} + +func (p *S) get() { +} + +type I interface { + get() +} + +func F(i I) { + i.get() +} diff --git a/go/test/fixedbugs/bug367.dir/prog.go b/go/test/fixedbugs/bug367.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..c278e4dd95ff78799c91ca1032886dfb9ff6d9b0 --- /dev/null +++ b/go/test/fixedbugs/bug367.dir/prog.go @@ -0,0 +1,28 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package main + +import ( + "./p" +) + +type T struct{ *p.S } +type I interface { + get() +} + +func main() { + var t T + p.F(t) + var x interface{} = t + _, ok := x.(I) + if ok { + panic("should not satisfy main.I") + } + _, ok = x.(p.I) + if !ok { + panic("should satisfy p.I") + } +} diff --git a/go/test/fixedbugs/bug369.dir/main.go b/go/test/fixedbugs/bug369.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..03b53a5b90d29c579ad3f20401270e11a141f09d --- /dev/null +++ b/go/test/fixedbugs/bug369.dir/main.go @@ -0,0 +1,55 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "flag" + "os" + "runtime" + "testing" + + fast "./fast" + slow "./slow" +) + +var buf = make([]byte, 1048576) + +func BenchmarkFastNonASCII(b *testing.B) { + for i := 0; i < b.N; i++ { + fast.NonASCII(buf, 0) + } +} + +func BenchmarkSlowNonASCII(b *testing.B) { + for i := 0; i < b.N; i++ { + slow.NonASCII(buf, 0) + } +} + +func main() { + testing.Init() + os.Args = []string{os.Args[0], "-test.benchtime=100ms"} + flag.Parse() + + rslow := testing.Benchmark(BenchmarkSlowNonASCII) + rfast := testing.Benchmark(BenchmarkFastNonASCII) + tslow := rslow.NsPerOp() + tfast := rfast.NsPerOp() + + // Optimization should be good for at least 2x, but be forgiving. + // On the ARM simulator we see closer to 1.5x. + speedup := float64(tslow) / float64(tfast) + want := 1.8 + if runtime.GOARCH == "arm" { + want = 1.3 + } + if speedup < want { + // TODO(rsc): doesn't work on linux-amd64 or darwin-amd64 builders, nor on + // a Lenovo x200 (linux-amd64) laptop. + // println("fast:", tfast, "slow:", tslow, "speedup:", speedup, "want:", want) + // println("not fast enough") + // os.Exit(1) + } +} diff --git a/go/test/fixedbugs/bug369.dir/pkg.go b/go/test/fixedbugs/bug369.dir/pkg.go new file mode 100644 index 0000000000000000000000000000000000000000..9964347250948886b45eb066a59e7bfb20e14c63 --- /dev/null +++ b/go/test/fixedbugs/bug369.dir/pkg.go @@ -0,0 +1,15 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkg + +func NonASCII(b []byte, i int) int { + for i = 0; i < len(b); i++ { + if b[i] >= 0x80 { + break + } + } + return i +} + diff --git a/go/test/fixedbugs/bug377.dir/one.go b/go/test/fixedbugs/bug377.dir/one.go new file mode 100644 index 0000000000000000000000000000000000000000..e29b813a481d01fedae3e6db0eb4340e1b53e16e --- /dev/null +++ b/go/test/fixedbugs/bug377.dir/one.go @@ -0,0 +1,10 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package one + +func Foo() (n int64, _ *int) { + return 42, nil +} + diff --git a/go/test/fixedbugs/bug377.dir/two.go b/go/test/fixedbugs/bug377.dir/two.go new file mode 100644 index 0000000000000000000000000000000000000000..2a10812d56d0a558febeaf87b3b0ffdf53b7db1a --- /dev/null +++ b/go/test/fixedbugs/bug377.dir/two.go @@ -0,0 +1,8 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +package two + +import _ "./one" + diff --git a/go/test/fixedbugs/bug382.dir/pkg.go b/go/test/fixedbugs/bug382.dir/pkg.go new file mode 100644 index 0000000000000000000000000000000000000000..92fe4e335a1815d33728a8bb20c58c100e2f53de --- /dev/null +++ b/go/test/fixedbugs/bug382.dir/pkg.go @@ -0,0 +1,7 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkg +type T struct {} +var E T diff --git a/go/test/fixedbugs/bug382.dir/prog.go b/go/test/fixedbugs/bug382.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..b74a82d8241c6f19109d005501e86ab1ea03de1b --- /dev/null +++ b/go/test/fixedbugs/bug382.dir/prog.go @@ -0,0 +1,13 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +// Issue 2529 + +package main + +import "./pkg" + +var x = pkg.E + +var fo = struct{ F pkg.T }{F: x} diff --git a/go/test/fixedbugs/bug392.dir/one.go b/go/test/fixedbugs/bug392.dir/one.go new file mode 100644 index 0000000000000000000000000000000000000000..aba8649b5b1d387a32fc96c85048a4c85356bce9 --- /dev/null +++ b/go/test/fixedbugs/bug392.dir/one.go @@ -0,0 +1,43 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Functions that the inliner exported incorrectly. + +package one + +type T int + +// Issue 2678 +func F1(T *T) bool { return T == nil } + +// Issue 2682. +func F2(c chan int) bool { return c == (<-chan int)(nil) } + +// Use of single named return value. +func F3() (ret []int) { return append(ret, 1) } + +// Call of inlined method with blank receiver. +func (_ *T) M() int { return 1 } +func (t *T) MM() int { return t.M() } + + +// One more like issue 2678 +type S struct { x, y int } +type U []S + +func F4(S int) U { return U{{S,S}} } + +func F5() []*S { + return []*S{ {1,2}, { 3, 4} } +} + +func F6(S int) *U { + return &U{{S,S}} +} + +// Bug in the fix. + +type PB struct { x int } + +func (t *PB) Reset() { *t = PB{} } diff --git a/go/test/fixedbugs/bug392.dir/pkg2.go b/go/test/fixedbugs/bug392.dir/pkg2.go new file mode 100644 index 0000000000000000000000000000000000000000..2ee41f0251072d9d19e5c9696709bf931ee0f39c --- /dev/null +++ b/go/test/fixedbugs/bug392.dir/pkg2.go @@ -0,0 +1,25 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Use the functions in one.go so that the inlined +// forms get type-checked. + +package pkg2 + +import "./one" + +func use() { + one.F1(nil) + one.F2(nil) + one.F3() + one.F4(1) + + var t *one.T + t.M() + t.MM() +} + +var V = []one.PB{{}, {}} + +func F() *one.PB diff --git a/go/test/fixedbugs/bug392.dir/pkg3.go b/go/test/fixedbugs/bug392.dir/pkg3.go new file mode 100644 index 0000000000000000000000000000000000000000..1403798bd30a4fe473e1a465ff33696f00ca75d3 --- /dev/null +++ b/go/test/fixedbugs/bug392.dir/pkg3.go @@ -0,0 +1,13 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Use the functions in pkg2.go so that the inlined +// forms get type-checked. + +package pkg3 + +import "./pkg2" + +var x = pkg2.F() +var v = pkg2.V diff --git a/go/test/fixedbugs/bug396.dir/one.go b/go/test/fixedbugs/bug396.dir/one.go new file mode 100644 index 0000000000000000000000000000000000000000..66eba63f5c1dfd3614f10cc1370409f3dd017533 --- /dev/null +++ b/go/test/fixedbugs/bug396.dir/one.go @@ -0,0 +1,10 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package one + +// Issue 2687 +type T struct { int } + +func New(i int) T { return T{i} } diff --git a/go/test/fixedbugs/bug396.dir/two.go b/go/test/fixedbugs/bug396.dir/two.go new file mode 100644 index 0000000000000000000000000000000000000000..9152bec2545b73f7598d008d048960ff87d5a95d --- /dev/null +++ b/go/test/fixedbugs/bug396.dir/two.go @@ -0,0 +1,14 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Use the functions in one.go so that the inlined +// forms get type-checked. + +package two + +import "./one" + +func use() { + _ = one.New(1) +} \ No newline at end of file diff --git a/go/test/fixedbugs/bug404.dir/one.go b/go/test/fixedbugs/bug404.dir/one.go new file mode 100644 index 0000000000000000000000000000000000000000..9fc47707891a5467dae3b95515648c0a637302e7 --- /dev/null +++ b/go/test/fixedbugs/bug404.dir/one.go @@ -0,0 +1,19 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package one + +type T1 int +type T2 []T1 +type T3 T2 + +func F1(T2) { +} + +func (p *T1) M1() T3 { + return nil +} + +func (p T3) M2() { +} diff --git a/go/test/fixedbugs/bug404.dir/two.go b/go/test/fixedbugs/bug404.dir/two.go new file mode 100644 index 0000000000000000000000000000000000000000..0c70a23a9e4b5a2aaf3332114ed0b72750bf150d --- /dev/null +++ b/go/test/fixedbugs/bug404.dir/two.go @@ -0,0 +1,12 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The gccgo compiler would fail on the import statement. +// two.go:10:13: error: use of undefined type ‘one.T2’ + +package two + +import "./one" + +var V one.T3 diff --git a/go/test/fixedbugs/bug407.dir/one.go b/go/test/fixedbugs/bug407.dir/one.go new file mode 100644 index 0000000000000000000000000000000000000000..c85b077b66cdefca1c152808fb38edfa9660584c --- /dev/null +++ b/go/test/fixedbugs/bug407.dir/one.go @@ -0,0 +1,20 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package one + +// Issue 2877 +type T struct { + f func(t *T, arg int) + g func(t T, arg int) +} + +func (t *T) foo(arg int) {} +func (t T) goo(arg int) {} + +func (t *T) F() { t.f = (*T).foo } +func (t *T) G() { t.g = T.goo } + + + diff --git a/go/test/fixedbugs/bug407.dir/two.go b/go/test/fixedbugs/bug407.dir/two.go new file mode 100644 index 0000000000000000000000000000000000000000..640305c654167039f53c9245e62401e5e71bd325 --- /dev/null +++ b/go/test/fixedbugs/bug407.dir/two.go @@ -0,0 +1,15 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Use the functions in one.go so that the inlined +// forms get type-checked. + +package two + +import "./one" + +func use() { + var r one.T + r.F() +} diff --git a/go/test/fixedbugs/bug414.dir/p1.go b/go/test/fixedbugs/bug414.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..143e600073f010ac118ab6e84f43f614108d259e --- /dev/null +++ b/go/test/fixedbugs/bug414.dir/p1.go @@ -0,0 +1,21 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +import "fmt" + +type Fer interface { + f() string +} + +type Object struct{} + +func (this *Object) f() string { + return "Object.f" +} + +func PrintFer(fer Fer) { + fmt.Sprintln(fer.f()) +} diff --git a/go/test/fixedbugs/bug414.dir/prog.go b/go/test/fixedbugs/bug414.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..8945d6543d6d2ed7845ddf7c5cfb78824086a2d8 --- /dev/null +++ b/go/test/fixedbugs/bug414.dir/prog.go @@ -0,0 +1,18 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./p1" + +type MyObject struct { + p1.Fer +} + +func main() { + var b p1.Fer = &p1.Object{} + p1.PrintFer(b) + var c p1.Fer = &MyObject{b} + p1.PrintFer(c) +} diff --git a/go/test/fixedbugs/bug415.dir/p.go b/go/test/fixedbugs/bug415.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..e86a697643b3f755989a5f4757e13a105fa187eb --- /dev/null +++ b/go/test/fixedbugs/bug415.dir/p.go @@ -0,0 +1,14 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A struct { + s struct{int} +} + +func (a *A) f() { + a.s = struct{int}{0} +} + diff --git a/go/test/fixedbugs/bug415.dir/prog.go b/go/test/fixedbugs/bug415.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..1ffde188b7858e0973a3bda3eb602570b4b0bc64 --- /dev/null +++ b/go/test/fixedbugs/bug415.dir/prog.go @@ -0,0 +1,9 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main +import "./p" +func main() {} +var _ p.A + diff --git a/go/test/fixedbugs/bug424.dir/lib.go b/go/test/fixedbugs/bug424.dir/lib.go new file mode 100644 index 0000000000000000000000000000000000000000..31df8c600f3a284da534c5d195b3a7a0f3c29d6b --- /dev/null +++ b/go/test/fixedbugs/bug424.dir/lib.go @@ -0,0 +1,16 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package lib + +type I interface { + m() string +} + +type T struct{} + +// m is not accessible from outside this package. +func (t *T) m() string { + return "lib.T.m" +} diff --git a/go/test/fixedbugs/bug424.dir/main.go b/go/test/fixedbugs/bug424.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..28b41e68a737dfe9e3e43f0b2c99238c673ddc54 --- /dev/null +++ b/go/test/fixedbugs/bug424.dir/main.go @@ -0,0 +1,97 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests that method calls through an interface always +// call the locally defined method localT.m independent +// at which embedding level it is and in which order +// embedding is done. + +package main + +import "./lib" +import "reflect" +import "fmt" + +type localI interface { + m() string +} + +type localT struct{} + +func (t *localT) m() string { + return "main.localT.m" +} + +type myT1 struct { + localT +} + +type myT2 struct { + localT + lib.T +} + +type myT3 struct { + lib.T + localT +} + +func main() { + var i localI + + i = new(localT) + if i.m() != "main.localT.m" { + println("BUG: localT:", i.m(), "called") + } + + i = new(myT1) + if i.m() != "main.localT.m" { + println("BUG: myT1:", i.m(), "called") + } + + i = new(myT2) + if i.m() != "main.localT.m" { + println("BUG: myT2:", i.m(), "called") + } + + t3 := new(myT3) + if t3.m() != "main.localT.m" { + println("BUG: t3:", t3.m(), "called") + } + + i = new(myT3) + if i.m() != "main.localT.m" { + t := reflect.TypeOf(i) + n := t.NumMethod() + for j := 0; j < n; j++ { + m := t.Method(j) + fmt.Printf("#%d: %s.%s %s\n", j, m.PkgPath, m.Name, m.Type) + } + println("BUG: myT3:", i.m(), "called") + } + + var t4 struct { + localT + lib.T + } + if t4.m() != "main.localT.m" { + println("BUG: t4:", t4.m(), "called") + } + i = &t4 + if i.m() != "main.localT.m" { + println("BUG: myT4:", i.m(), "called") + } + + var t5 struct { + lib.T + localT + } + if t5.m() != "main.localT.m" { + println("BUG: t5:", t5.m(), "called") + } + i = &t5 + if i.m() != "main.localT.m" { + println("BUG: myT5:", i.m(), "called") + } +} diff --git a/go/test/fixedbugs/bug437.dir/one.go b/go/test/fixedbugs/bug437.dir/one.go new file mode 100644 index 0000000000000000000000000000000000000000..633573e51d1cb6ec3437f78cdd14637ca3e63814 --- /dev/null +++ b/go/test/fixedbugs/bug437.dir/one.go @@ -0,0 +1,18 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package one + +type I1 interface { + f() +} + +type S1 struct { +} + +func (s S1) f() { +} + +func F1(i1 I1) { +} diff --git a/go/test/fixedbugs/bug437.dir/two.go b/go/test/fixedbugs/bug437.dir/two.go new file mode 100644 index 0000000000000000000000000000000000000000..61da121d513270a8b6e7bcb9e10f939a3e315fb6 --- /dev/null +++ b/go/test/fixedbugs/bug437.dir/two.go @@ -0,0 +1,11 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package two + +import "./one" + +type S2 struct { + one.S1 +} diff --git a/go/test/fixedbugs/bug437.dir/x.go b/go/test/fixedbugs/bug437.dir/x.go new file mode 100644 index 0000000000000000000000000000000000000000..585b480c0a918f4cdba9475c0b2e418a25ecac8b --- /dev/null +++ b/go/test/fixedbugs/bug437.dir/x.go @@ -0,0 +1,25 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test converting a type defined in a different package to an +// interface defined in a third package, where the interface has a +// hidden method. This used to cause a link error with gccgo. + +package main + +import ( + "./one" + "./two" +) + +func F(i1 one.I1) { + switch v := i1.(type) { + case two.S2: + one.F1(v) + } +} + +func main() { + F(nil) +} diff --git a/go/test/fixedbugs/bug448.dir/pkg1.go b/go/test/fixedbugs/bug448.dir/pkg1.go new file mode 100644 index 0000000000000000000000000000000000000000..291903ca459f3d5dc6ac3db0685938ad1ace0cfb --- /dev/null +++ b/go/test/fixedbugs/bug448.dir/pkg1.go @@ -0,0 +1,11 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkg1 + +var x = make(chan interface{}) + +func Do() int { + return (<-x).(int) +} diff --git a/go/test/fixedbugs/bug448.dir/pkg2.go b/go/test/fixedbugs/bug448.dir/pkg2.go new file mode 100644 index 0000000000000000000000000000000000000000..20d850915dde7ea16e93da6a323939bf7fd98f95 --- /dev/null +++ b/go/test/fixedbugs/bug448.dir/pkg2.go @@ -0,0 +1,14 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Issue 3843: inlining bug due to wrong receive operator precedence. + +package pkg2 + +import "./pkg1" + +func F() { + pkg1.Do() +} + diff --git a/go/test/fixedbugs/bug460.dir/a.go b/go/test/fixedbugs/bug460.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..51c6836be7e92914f27c58e97205540956c30fea --- /dev/null +++ b/go/test/fixedbugs/bug460.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Foo struct { + int + int8 + error + rune + byte +} diff --git a/go/test/fixedbugs/bug460.dir/b.go b/go/test/fixedbugs/bug460.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..5d388fc413f783de1aa93fe6c0aacab463b87e63 --- /dev/null +++ b/go/test/fixedbugs/bug460.dir/b.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var x a.Foo + +func main() { + x.int = 20 // ERROR "unexported field|undefined" + x.int8 = 20 // ERROR "unexported field|undefined" + x.error = nil // ERROR "unexported field|undefined" + x.rune = 'a' // ERROR "unexported field|undefined" + x.byte = 20 // ERROR "unexported field|undefined" +} diff --git a/go/test/fixedbugs/bug465.dir/a.go b/go/test/fixedbugs/bug465.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3e5d012e6a1097061c81f04ef6a12f54652c7c4f --- /dev/null +++ b/go/test/fixedbugs/bug465.dir/a.go @@ -0,0 +1,76 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct{ A, B int } + +type A []int + +type M map[int]int + +func F1() int { + if (T{1, 2}) == (T{3, 4}) { + return 1 + } + return 0 +} + +func F2() int { + if (M{1: 2}) == nil { + return 1 + } + return 0 +} + +func F3() int { + if nil == (A{}) { + return 1 + } + return 0 +} + +func F4() int { + if a := (A{}); a == nil { + return 1 + } + return 0 +} + +func F5() int { + for k, v := range (M{1: 2}) { + return v - k + } + return 0 +} + +func F6() int { + switch a := (T{1, 1}); a == (T{1, 2}) { + default: + return 1 + } + return 0 +} + +func F7() int { + for m := (M{}); len(m) < (T{1, 2}).A; m[1] = (A{1})[0] { + return 1 + } + return 0 +} + +func F8() int { + if a := (&T{1, 1}); a != nil { + return 1 + } + return 0 +} + +func F9() int { + var a *T + if a = (&T{1, 1}); a != nil { + return 1 + } + return 0 +} diff --git a/go/test/fixedbugs/bug465.dir/b.go b/go/test/fixedbugs/bug465.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..db7f7315e6ab093f912b540791787a4612d9901f --- /dev/null +++ b/go/test/fixedbugs/bug465.dir/b.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + for _, f := range []func() int{ + a.F1, a.F2, a.F3, a.F4, + a.F5, a.F6, a.F7, a.F8, a.F9} { + if f() > 1 { + panic("f() > 1") + } + } +} diff --git a/go/test/fixedbugs/bug466.dir/a.go b/go/test/fixedbugs/bug466.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e27699c2ef51ff6ad40c00ff43c17a508bbd0b46 --- /dev/null +++ b/go/test/fixedbugs/bug466.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +const N = 2+3i + +func Func() []complex128 { + return []complex128{1, complex(2, 3), complex(4, 5)} +} + +func Mul(z complex128) complex128 { + return z * (3 + 4i) +} diff --git a/go/test/fixedbugs/bug466.dir/b.go b/go/test/fixedbugs/bug466.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..04e3626c7524d145c0eefe174db9481b00b46639 --- /dev/null +++ b/go/test/fixedbugs/bug466.dir/b.go @@ -0,0 +1,30 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + s := a.Func() + if s[0] != 1 { + println(s[0]) + panic("s[0] != 1") + } + if s[1] != 2+3i { + println(s[1]) + panic("s[1] != 2+3i") + } + if s[2] != 4+5i { + println(s[2]) + panic("s[2] != 4+5i") + } + + x := 1 + 2i + y := a.Mul(x) + if y != (1+2i)*(3+4i) { + println(y) + panic("y != (1+2i)*(3+4i)") + } +} diff --git a/go/test/fixedbugs/bug467.dir/p1.go b/go/test/fixedbugs/bug467.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..538b554f8e3970b1a043231e172470b27679725e --- /dev/null +++ b/go/test/fixedbugs/bug467.dir/p1.go @@ -0,0 +1,5 @@ +package p1 + +type SockaddrUnix int + +func (s SockaddrUnix) Error() string { return "blah" } diff --git a/go/test/fixedbugs/bug467.dir/p2.go b/go/test/fixedbugs/bug467.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..d80d3a30b185d927e9f1f22eaa5d01bb4f604d52 --- /dev/null +++ b/go/test/fixedbugs/bug467.dir/p2.go @@ -0,0 +1,5 @@ +package p2 + +import "./p1" + +func SockUnix() error { var s *p1.SockaddrUnix; return s } diff --git a/go/test/fixedbugs/bug467.dir/p3.go b/go/test/fixedbugs/bug467.dir/p3.go new file mode 100644 index 0000000000000000000000000000000000000000..c795646472fc0a460cb535868f3fa690d80ba8ec --- /dev/null +++ b/go/test/fixedbugs/bug467.dir/p3.go @@ -0,0 +1,7 @@ +package main + +import "./p2" + +func main() { + _ = p2.SockUnix() +} diff --git a/go/test/fixedbugs/bug468.dir/p1.go b/go/test/fixedbugs/bug468.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..cdda735e965704d46b6ea7612539603600bbed77 --- /dev/null +++ b/go/test/fixedbugs/bug468.dir/p1.go @@ -0,0 +1,7 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +type S struct { X, Y int } diff --git a/go/test/fixedbugs/bug468.dir/p2.go b/go/test/fixedbugs/bug468.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..dbb46931b825f2d64ca31e62b298946277cc6ae9 --- /dev/null +++ b/go/test/fixedbugs/bug468.dir/p2.go @@ -0,0 +1,25 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "reflect" + + "./p1" +) + +func main() { + var v1 = p1.S{1, 2} + var v2 = struct { X, Y int }{1, 2} + v1 = v2 + t1 := reflect.TypeOf(v1) + t2 := reflect.TypeOf(v2) + if !t1.AssignableTo(t2) { + panic(0) + } + if !t2.AssignableTo(t1) { + panic(1) + } +} diff --git a/go/test/fixedbugs/bug472.dir/p1.go b/go/test/fixedbugs/bug472.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..cda1aa7aa8c0f6377f636f4c3c62ceabb3b4857e --- /dev/null +++ b/go/test/fixedbugs/bug472.dir/p1.go @@ -0,0 +1,17 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +import "runtime" + +func E() func() int { return runtime.NumCPU } + +func F() func() { return runtime.Gosched } + +func G() func() string { return runtime.GOROOT } + +func H() func() { return runtime.GC } + +func I() func() string { return runtime.Version } diff --git a/go/test/fixedbugs/bug472.dir/p2.go b/go/test/fixedbugs/bug472.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..581ec400200fd1953566be9191c7f5f52b4e2994 --- /dev/null +++ b/go/test/fixedbugs/bug472.dir/p2.go @@ -0,0 +1,17 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p2 + +import "runtime" + +func E() func() int { return runtime.NumCPU } + +func F() func() { return runtime.GC } + +func G() func() string { return runtime.GOROOT } + +func H() func() { return runtime.Gosched } + +func I() func() string { return runtime.Version } diff --git a/go/test/fixedbugs/bug472.dir/z.go b/go/test/fixedbugs/bug472.dir/z.go new file mode 100644 index 0000000000000000000000000000000000000000..eb791bf443a3b33babcbf21c090c809ddfc12982 --- /dev/null +++ b/go/test/fixedbugs/bug472.dir/z.go @@ -0,0 +1,13 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + _ "./p1" + _ "./p2" +) + +func main() { +} diff --git a/go/test/fixedbugs/bug478.dir/a.go b/go/test/fixedbugs/bug478.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..b5a2dbcdb88a33e1e444d8aafbbcda8d801022c5 --- /dev/null +++ b/go/test/fixedbugs/bug478.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +type S1 struct{} + +func (s S1) f() {} diff --git a/go/test/fixedbugs/bug478.dir/b.go b/go/test/fixedbugs/bug478.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..cfd1d273d8e6fc087812cda17a5e822148a6a7f6 --- /dev/null +++ b/go/test/fixedbugs/bug478.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p2 + +import "./a" + +type S2 struct { + p1.S1 +} + +func (s S2) f() {} diff --git a/go/test/fixedbugs/bug479.dir/a.go b/go/test/fixedbugs/bug479.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..eddb4cf0781a17bc105baa5e25082c0a1b546d9e --- /dev/null +++ b/go/test/fixedbugs/bug479.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type S2 struct {} + +const C = unsafe.Sizeof(S2{}) + +type S1 struct { + S2 +} diff --git a/go/test/fixedbugs/bug479.dir/b.go b/go/test/fixedbugs/bug479.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..9f3f5e8f523d1af736ea290690bbfb6a731a12ef --- /dev/null +++ b/go/test/fixedbugs/bug479.dir/b.go @@ -0,0 +1,16 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +type S3 struct { + p.S1 +} + +func main() { + var i interface{} = S3{} + _ = i +} diff --git a/go/test/fixedbugs/bug480.dir/a.go b/go/test/fixedbugs/bug480.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..26a8d1166976a45d3a76128fcc99cd91eefc53d3 --- /dev/null +++ b/go/test/fixedbugs/bug480.dir/a.go @@ -0,0 +1,17 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type S interface{ + F() T +} + +type T struct { + S +} + +type U struct { + error +} diff --git a/go/test/fixedbugs/bug480.dir/b.go b/go/test/fixedbugs/bug480.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..5bd40f6205e32d261a4e53e6b098f788e14583ee --- /dev/null +++ b/go/test/fixedbugs/bug480.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var t a.T + +func F() error { + return a.U{} +} diff --git a/go/test/fixedbugs/bug488.dir/a.go b/go/test/fixedbugs/bug488.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..fc494207a1739907bd05d69af9568fba7e3036c5 --- /dev/null +++ b/go/test/fixedbugs/bug488.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var p2 = Printf // ERROR "undefined" diff --git a/go/test/fixedbugs/bug488.dir/b.go b/go/test/fixedbugs/bug488.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..f93328c8da4a04a4efaf6431358dc65a9b358ce5 --- /dev/null +++ b/go/test/fixedbugs/bug488.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import . "fmt" + +var p1 = Print diff --git a/go/test/fixedbugs/bug492.dir/a.go b/go/test/fixedbugs/bug492.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..90917e55e839ba82754b5543d3c7ac43f5e2e23c --- /dev/null +++ b/go/test/fixedbugs/bug492.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type s struct { + s string +} + +func F1(s s) { +} + +func F2() s { + return s{""} +} diff --git a/go/test/fixedbugs/bug492.dir/b.go b/go/test/fixedbugs/bug492.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..5b8c4f2a533eb8d68f24e2c323567a21aca1b33a --- /dev/null +++ b/go/test/fixedbugs/bug492.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + defer a.F1(a.F2()) +} diff --git a/go/test/fixedbugs/bug504.dir/a.go b/go/test/fixedbugs/bug504.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..ac0be937ab2d8cb08e688e364d1ab5cc8672d96f --- /dev/null +++ b/go/test/fixedbugs/bug504.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type MyInt = int diff --git a/go/test/fixedbugs/bug504.dir/b.go b/go/test/fixedbugs/bug504.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e8f8da9af88a42efb6c7a39501edc52a8af61415 --- /dev/null +++ b/go/test/fixedbugs/bug504.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() a.MyInt { + return 0 +} diff --git a/go/test/fixedbugs/bug504.dir/c.go b/go/test/fixedbugs/bug504.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..5a6e889905986aad5ae22b891bf579210d96bb3a --- /dev/null +++ b/go/test/fixedbugs/bug504.dir/c.go @@ -0,0 +1,9 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import "./b" + +var V = b.F() diff --git a/go/test/fixedbugs/bug504.dir/main.go b/go/test/fixedbugs/bug504.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..bdbd95c7a3143dabb19a9761bbeca1e0df0acbdf --- /dev/null +++ b/go/test/fixedbugs/bug504.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./c" + +func main() { + println(c.V) +} diff --git a/go/test/fixedbugs/bug506.dir/a.go b/go/test/fixedbugs/bug506.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..8e8a2005810fa1fa2a52f98c585d3d60de186b55 --- /dev/null +++ b/go/test/fixedbugs/bug506.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type internal struct { + f1 string + f2 float64 +} + +type S struct { + F struct { + I internal + } +} diff --git a/go/test/fixedbugs/bug506.dir/main.go b/go/test/fixedbugs/bug506.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..1b60e40d8d0a448852e5bcbc3542eed2b82f5b4b --- /dev/null +++ b/go/test/fixedbugs/bug506.dir/main.go @@ -0,0 +1,20 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + + "./a" +) + +var v = a.S{} + +func main() { + want := "{{ 0}}" + if got := fmt.Sprint(v.F); got != want { + panic(got) + } +} diff --git a/go/test/fixedbugs/bug507.dir/a.go b/go/test/fixedbugs/bug507.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..0929adcfb3168da785549f05ec3bd50ff9e195ae --- /dev/null +++ b/go/test/fixedbugs/bug507.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I interface { + M() +} + +type S struct { + I I +} diff --git a/go/test/fixedbugs/bug507.dir/b.go b/go/test/fixedbugs/bug507.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..bddce2dd8392d1fc61bb990c4d1f90216b3b87ef --- /dev/null +++ b/go/test/fixedbugs/bug507.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import . "./a" + +var V2 I diff --git a/go/test/fixedbugs/bug507.dir/c.go b/go/test/fixedbugs/bug507.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..e67f0fd74e82593e75c3e4421da843adca9e42f1 --- /dev/null +++ b/go/test/fixedbugs/bug507.dir/c.go @@ -0,0 +1,9 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var V1 = a.S{I: nil} diff --git a/go/test/fixedbugs/bug510.dir/a.go b/go/test/fixedbugs/bug510.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..db1cfef366d5500182ed07674a31347c0956b34a --- /dev/null +++ b/go/test/fixedbugs/bug510.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import "reflect" + +type A = map[int] bool + +func F() interface{} { + return reflect.New(reflect.TypeOf((*A)(nil))).Elem().Interface() +} diff --git a/go/test/fixedbugs/bug510.dir/b.go b/go/test/fixedbugs/bug510.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..56b0201858cac39d0776c5552c08882aebaba2cb --- /dev/null +++ b/go/test/fixedbugs/bug510.dir/b.go @@ -0,0 +1,14 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + _, ok := a.F().(*map[int]bool) + if !ok { + panic("bad type") + } +} diff --git a/go/test/fixedbugs/bug511.dir/a.go b/go/test/fixedbugs/bug511.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..33931a07a87bf032fb0899fa05e7d2f363a7a8b2 --- /dev/null +++ b/go/test/fixedbugs/bug511.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type S struct{} + +type A = S + +func (A) M() {} diff --git a/go/test/fixedbugs/bug511.dir/b.go b/go/test/fixedbugs/bug511.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..f8877d6afd04f6445f1076bdb19b54802c3e440b --- /dev/null +++ b/go/test/fixedbugs/bug511.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() { + a.S{}.M() +} diff --git a/go/test/fixedbugs/gcc67968.dir/a.go b/go/test/fixedbugs/gcc67968.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..9f51a7a8bc5913c1fe8c0543a4199d095220c11d --- /dev/null +++ b/go/test/fixedbugs/gcc67968.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T int + +func (a *T) Foo() [1]string { + var r [1]string + return r +} diff --git a/go/test/fixedbugs/gcc67968.dir/b.go b/go/test/fixedbugs/gcc67968.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..41b62d2088070279f643409cde8e4f02b113d3e7 --- /dev/null +++ b/go/test/fixedbugs/gcc67968.dir/b.go @@ -0,0 +1,12 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() (interface{}) { + var v *a.T + return v.Foo() +} diff --git a/go/test/fixedbugs/issue10066.dir/a.go b/go/test/fixedbugs/issue10066.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..8bb3b303ea603f4f82b9bf763fb0d0d04d6d9698 --- /dev/null +++ b/go/test/fixedbugs/issue10066.dir/a.go @@ -0,0 +1,11 @@ +package a + +import "log" + +func Do() { + Do2() +} + +func Do2() { + println(log.Ldate | log.Ltime | log.Lshortfile) +} diff --git a/go/test/fixedbugs/issue10066.dir/b.go b/go/test/fixedbugs/issue10066.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..46d2f55fed63e098ab46e2fe52a1ad612f56e37e --- /dev/null +++ b/go/test/fixedbugs/issue10066.dir/b.go @@ -0,0 +1,7 @@ +package b + +import "./a" + +func test() { + a.Do() +} diff --git a/go/test/fixedbugs/issue10219.dir/a.go b/go/test/fixedbugs/issue10219.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..c61d02b66a97450f4e678354dd093de6ab50b445 --- /dev/null +++ b/go/test/fixedbugs/issue10219.dir/a.go @@ -0,0 +1,24 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type m struct { + S string +} + +var g = struct { + m + P string +}{ + m{"a"}, + "", +} + +type S struct{} + +func (s *S) M(p string) { + r := g + r.P = p +} diff --git a/go/test/fixedbugs/issue10219.dir/b.go b/go/test/fixedbugs/issue10219.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..09d8911ff4aa77b4a59e0ad9feaf36c11a8843f9 --- /dev/null +++ b/go/test/fixedbugs/issue10219.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() *a.S { + return &a.S{} +} diff --git a/go/test/fixedbugs/issue10219.dir/c.go b/go/test/fixedbugs/issue10219.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..d331495df204d7adf9182c43d1fdd427a6c20844 --- /dev/null +++ b/go/test/fixedbugs/issue10219.dir/c.go @@ -0,0 +1,12 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import "./b" + +func F() { + s := b.F() + s.M("c") +} diff --git a/go/test/fixedbugs/issue10700.dir/other.go b/go/test/fixedbugs/issue10700.dir/other.go new file mode 100644 index 0000000000000000000000000000000000000000..12908b92053a37249d14a661d92f99f303d6c2a6 --- /dev/null +++ b/go/test/fixedbugs/issue10700.dir/other.go @@ -0,0 +1,10 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package other + +type Exported interface { + Do() + secret() +} diff --git a/go/test/fixedbugs/issue10700.dir/test.go b/go/test/fixedbugs/issue10700.dir/test.go new file mode 100644 index 0000000000000000000000000000000000000000..2dfc24af077cce048195d0dcb2570b294a76f27d --- /dev/null +++ b/go/test/fixedbugs/issue10700.dir/test.go @@ -0,0 +1,49 @@ +// errorcheck -0 -m -l + +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./other" + +type Imported interface { + Do() +} + +type HasAMethod struct { + x int +} + +func (me *HasAMethod) Do() { + println(me.x) +} + +func InMyCode(x *Imported, y *HasAMethod, z *other.Exported) { + x.Do() // ERROR "x\.Do undefined \(type \*Imported is pointer to interface, not interface\)|type that is pointer to interface" + x.do() // ERROR "x\.do undefined \(type \*Imported is pointer to interface, not interface\)|type that is pointer to interface" + (*x).Do() + x.Dont() // ERROR "x\.Dont undefined \(type \*Imported is pointer to interface, not interface\)|type that is pointer to interface" + (*x).Dont() // ERROR "\(\*x\)\.Dont undefined \(type Imported has no field or method Dont\)|reference to undefined field or method" + + y.Do() + y.do() // ERROR "y\.do undefined \(type \*HasAMethod has no field or method do, but does have Do\)|reference to undefined field or method" + (*y).Do() + (*y).do() // ERROR "\(\*y\)\.do undefined \(type HasAMethod has no field or method do, but does have Do\)|reference to undefined field or method" + y.Dont() // ERROR "y\.Dont undefined \(type \*HasAMethod has no field or method Dont\)|reference to undefined field or method" + (*y).Dont() // ERROR "\(\*y\)\.Dont undefined \(type HasAMethod has no field or method Dont\)|reference to undefined field or method" + + z.Do() // ERROR "z\.Do undefined \(type \*other\.Exported is pointer to interface, not interface\)|type that is pointer to interface" + z.do() // ERROR "z\.do undefined \(type \*other\.Exported is pointer to interface, not interface\)|type that is pointer to interface" + (*z).Do() + (*z).do() // ERROR "\(\*z\)\.do undefined \(type other.Exported has no field or method do, but does have Do\)|reference to undefined field or method" + z.Dont() // ERROR "z\.Dont undefined \(type \*other\.Exported is pointer to interface, not interface\)|type that is pointer to interface" + (*z).Dont() // ERROR "\(\*z\)\.Dont undefined \(type other\.Exported has no field or method Dont\)|reference to undefined field or method" + z.secret() // ERROR "z\.secret undefined \(type \*other\.Exported is pointer to interface, not interface\)|type that is pointer to interface" + (*z).secret() // ERROR "\(\*z\)\.secret undefined \(cannot refer to unexported field or method secret\)|reference to unexported field or method" + +} + +func main() { +} diff --git a/go/test/fixedbugs/issue11053.dir/p.go b/go/test/fixedbugs/issue11053.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..81b412aef13a9f459f288dcea92b2f165a2b6ddd --- /dev/null +++ b/go/test/fixedbugs/issue11053.dir/p.go @@ -0,0 +1,9 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func Int32(i int32) *int32 { + return &i +} diff --git a/go/test/fixedbugs/issue11053.dir/p_test.go b/go/test/fixedbugs/issue11053.dir/p_test.go new file mode 100644 index 0000000000000000000000000000000000000000..412352d7c5e1f36026ef84600a8a8763653d3cbb --- /dev/null +++ b/go/test/fixedbugs/issue11053.dir/p_test.go @@ -0,0 +1,51 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./p" + "fmt" +) + +type I interface { + Add(out *P) +} + +type P struct { + V *int32 +} + +type T struct{} + +var x int32 = 42 + +func Int32x(i int32) *int32 { + return &i +} + +func (T) Add(out *P) { + out.V = p.Int32(x) // inlined, p.i.2 moved to heap +} + +var PP P +var out *P = &PP + +func F(s I) interface{} { + s.Add(out) // not inlined. + return out +} + +var s T + +func main() { + println("Starting") + fmt.Sprint(new(int32)) + resp := F(s).(*P) + println("Before, *resp.V=", *resp.V) // Trashes *resp.V in process of printing. + println("After, *resp.V=", *resp.V) + if got, want := *resp.V, int32(42); got != want { + fmt.Printf("FAIL, got %v, want %v", got, want) + } +} diff --git a/go/test/fixedbugs/issue11656.dir/asm.go b/go/test/fixedbugs/issue11656.dir/asm.go new file mode 100644 index 0000000000000000000000000000000000000000..c64302bd505e4562cc4529d9f3ca13b927a8e6e4 --- /dev/null +++ b/go/test/fixedbugs/issue11656.dir/asm.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build ppc64 || ppc64le + +package main + +func syncIcache(p uintptr) diff --git a/go/test/fixedbugs/issue11656.dir/asm_generic.go b/go/test/fixedbugs/issue11656.dir/asm_generic.go new file mode 100644 index 0000000000000000000000000000000000000000..a8b8f6a5e4f2af436f2bbd65b4b64b94f7bfa9bc --- /dev/null +++ b/go/test/fixedbugs/issue11656.dir/asm_generic.go @@ -0,0 +1,10 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !ppc64 && !ppc64le + +package main + +func syncIcache(p uintptr) { +} diff --git a/go/test/fixedbugs/issue11656.dir/asm_ppc64.s b/go/test/fixedbugs/issue11656.dir/asm_ppc64.s new file mode 100644 index 0000000000000000000000000000000000000000..125a197ed8e1f74f18e181546555895e85b5a8c0 --- /dev/null +++ b/go/test/fixedbugs/issue11656.dir/asm_ppc64.s @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func syncIcache(p uintptr) +TEXT main·syncIcache(SB), NOSPLIT|NOFRAME, $0-0 + SYNC + MOVD (R3), R3 + ICBI (R3) + ISYNC + RET diff --git a/go/test/fixedbugs/issue11656.dir/asm_ppc64le.s b/go/test/fixedbugs/issue11656.dir/asm_ppc64le.s new file mode 100644 index 0000000000000000000000000000000000000000..125a197ed8e1f74f18e181546555895e85b5a8c0 --- /dev/null +++ b/go/test/fixedbugs/issue11656.dir/asm_ppc64le.s @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func syncIcache(p uintptr) +TEXT main·syncIcache(SB), NOSPLIT|NOFRAME, $0-0 + SYNC + MOVD (R3), R3 + ICBI (R3) + ISYNC + RET diff --git a/go/test/fixedbugs/issue11656.dir/issue11656.go b/go/test/fixedbugs/issue11656.dir/issue11656.go new file mode 100644 index 0000000000000000000000000000000000000000..a5a52df698ad9ca1d5db3f1fb538a6e44feb9353 --- /dev/null +++ b/go/test/fixedbugs/issue11656.dir/issue11656.go @@ -0,0 +1,75 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/binary" + "runtime" + "runtime/debug" + "unsafe" +) + +func main() { + debug.SetPanicOnFault(true) + defer func() { + if err := recover(); err == nil { + panic("not panicking") + } + pc, _, _, _ := runtime.Caller(10) + f := runtime.FuncForPC(pc) + if f == nil || f.Name() != "main.f" { + if f == nil { + println("no func for ", unsafe.Pointer(pc)) + } else { + println("found func:", f.Name()) + } + panic("cannot find main.f on stack") + } + }() + f(20) +} + +func f(n int) { + if n > 0 { + f(n - 1) + } + var f struct { + x uintptr + } + + // We want to force a seg fault, to get a crash at a PC value != 0. + // Not all systems make the data section non-executable. + ill := make([]byte, 64) + switch runtime.GOARCH { + case "386", "amd64": + ill = append(ill[:0], 0x89, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00) // MOVL AX, 0 + case "arm": + binary.LittleEndian.PutUint32(ill[0:4], 0xe3a00000) // MOVW $0, R0 + binary.LittleEndian.PutUint32(ill[4:8], 0xe5800000) // MOVW R0, (R0) + case "arm64": + binary.LittleEndian.PutUint32(ill, 0xf90003ff) // MOVD ZR, (ZR) + case "ppc64": + binary.BigEndian.PutUint32(ill, 0xf8000000) // MOVD R0, (R0) + case "ppc64le": + binary.LittleEndian.PutUint32(ill, 0xf8000000) // MOVD R0, (R0) + case "mips", "mips64": + binary.BigEndian.PutUint32(ill, 0xfc000000) // MOVV R0, (R0) + case "mipsle", "mips64le": + binary.LittleEndian.PutUint32(ill, 0xfc000000) // MOVV R0, (R0) + case "s390x": + ill = append(ill[:0], 0xa7, 0x09, 0x00, 0x00) // MOVD $0, R0 + ill = append(ill, 0xe3, 0x00, 0x00, 0x00, 0x00, 0x24) // MOVD R0, (R0) + case "riscv64": + binary.LittleEndian.PutUint32(ill, 0x00003023) // MOV X0, (X0) + default: + // Just leave it as 0 and hope for the best. + } + + f.x = uintptr(unsafe.Pointer(&ill[0])) + p := &f + fn := *(*func())(unsafe.Pointer(&p)) + syncIcache(f.x) + fn() +} diff --git a/go/test/fixedbugs/issue12677.dir/p.go b/go/test/fixedbugs/issue12677.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..e395071f8d545712eaa2b4d800abb5558c72d40a --- /dev/null +++ b/go/test/fixedbugs/issue12677.dir/p.go @@ -0,0 +1,8 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p +func Baz(f int) float64 { + return 1 / float64(int(1)<<(uint(f))) +} diff --git a/go/test/fixedbugs/issue12677.dir/q.go b/go/test/fixedbugs/issue12677.dir/q.go new file mode 100644 index 0000000000000000000000000000000000000000..fd39c8a9ca6bcef0f1453dacbbec979b142e89c2 --- /dev/null +++ b/go/test/fixedbugs/issue12677.dir/q.go @@ -0,0 +1,7 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package q +import "./p" +func f() { println(p.Baz(2)) } diff --git a/go/test/fixedbugs/issue13777.dir/burnin.go b/go/test/fixedbugs/issue13777.dir/burnin.go new file mode 100644 index 0000000000000000000000000000000000000000..512563975ed64fa6ac60d95c00bc40f37a5bb0f1 --- /dev/null +++ b/go/test/fixedbugs/issue13777.dir/burnin.go @@ -0,0 +1,19 @@ +package burnin + +type sendCmdFunc func(string) + +func sendCommand(c string) {} + +func NewSomething() { + // This works... + // var sendCmd sendCmdFunc + // sendCmd = sendCommand + + // So does this... + //sendCmd := sendCmdFunc(sendCommand) + + // This fails... + sendCmd := sendCommand + + _ = sendCmd +} diff --git a/go/test/fixedbugs/issue13777.dir/main.go b/go/test/fixedbugs/issue13777.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2512b93a81a0395093c685bd63d30a4914fe1487 --- /dev/null +++ b/go/test/fixedbugs/issue13777.dir/main.go @@ -0,0 +1,11 @@ +// build + +package main + +import ( + x "./burnin" +) + +func main() { + x.NewSomething() +} diff --git a/go/test/fixedbugs/issue14164.dir/a.go b/go/test/fixedbugs/issue14164.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..bf03051619817a7f5f421d99d467a9eea6f95b64 --- /dev/null +++ b/go/test/fixedbugs/issue14164.dir/a.go @@ -0,0 +1,47 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +// F is an exported function, small enough to be inlined. +// It defines a local interface with an unexported method +// f, which will appear with a package-qualified method +// name in the export data. +func F(x interface{}) bool { + _, ok := x.(interface { + f() + }) + return ok +} + +// Like F but with the unexported interface method f +// defined via an embedded interface t. The compiler +// always flattens embedded interfaces so there should +// be no difference between F and G. Alas, currently +// G is not inlineable (at least via export data), so +// the issue is moot, here. +func G(x interface{}) bool { + type t0 interface { + f() + } + _, ok := x.(interface { + t0 + }) + return ok +} + +// Like G but now the embedded interface is declared +// at package level. This function is inlineable via +// export data. The export data representation is like +// for F. +func H(x interface{}) bool { + _, ok := x.(interface { + t1 + }) + return ok +} + +type t1 interface { + f() +} diff --git a/go/test/fixedbugs/issue14164.dir/main.go b/go/test/fixedbugs/issue14164.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..bcc6a63c2071588a0bf6da9fd2c868e0877f7a62 --- /dev/null +++ b/go/test/fixedbugs/issue14164.dir/main.go @@ -0,0 +1,12 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +// Verify that we can import package "a" containing an inlineable +// function F that declares a local interface with a non-exported +// method f. +import _ "./a" + +func main() {} diff --git a/go/test/fixedbugs/issue14331.dir/a.go b/go/test/fixedbugs/issue14331.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..f1e57ef52785658234739ffeaf04053beb8607a4 --- /dev/null +++ b/go/test/fixedbugs/issue14331.dir/a.go @@ -0,0 +1,14 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var S struct { + Str string `tag` +} + +func F() string { + v := S + return v.Str +} diff --git a/go/test/fixedbugs/issue14331.dir/b.go b/go/test/fixedbugs/issue14331.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..a2280a362979639bdbeacd2409143433c8c05da6 --- /dev/null +++ b/go/test/fixedbugs/issue14331.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func G() string { + return a.F() +} diff --git a/go/test/fixedbugs/issue15071.dir/exp.go b/go/test/fixedbugs/issue15071.dir/exp.go new file mode 100644 index 0000000000000000000000000000000000000000..e6041e602da3262c288ef150909a041a57281dd3 --- /dev/null +++ b/go/test/fixedbugs/issue15071.dir/exp.go @@ -0,0 +1,24 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package exp + +func Exported(x int) int { + return inlined(x) +} + +func inlined(x int) int { + y := 0 + switch { + case x > 0: + y += 5 + return 0 + y + case x < 1: + y += 6 + fallthrough + default: + y += 7 + return 2 + y + } +} diff --git a/go/test/fixedbugs/issue15071.dir/main.go b/go/test/fixedbugs/issue15071.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..96790dae83ad17e21233045e3e9f77ec056fdbc1 --- /dev/null +++ b/go/test/fixedbugs/issue15071.dir/main.go @@ -0,0 +1,14 @@ +// run + +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "os" +import "./exp" + +func main() { + _ = exp.Exported(len(os.Args)) +} diff --git a/go/test/fixedbugs/issue15470.dir/a.go b/go/test/fixedbugs/issue15470.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..1fcf3ea6e010ca91edcf5c290f4e260753e277f4 --- /dev/null +++ b/go/test/fixedbugs/issue15470.dir/a.go @@ -0,0 +1,24 @@ +package a + +import "io" + +type T interface { + M0(_ int) + M1(x, _ int) // _ (blank) caused crash + M2() (x, _ int) +} + +type S struct{} + +func (S) M0(_ int) {} +func (S) M1(x, _ int) {} +func (S) M2() (x, _ int) { return } +func (_ S) M3() {} + +// Snippet from x/tools/godoc/analysis/analysis.go. +// Offending code from #5470. +type Link interface { + Start() int + End() int + Write(w io.Writer, _ int, start bool) // _ (blank) caused crash +} diff --git a/go/test/fixedbugs/issue15470.dir/b.go b/go/test/fixedbugs/issue15470.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..863ee9f522196ab4075f074f2faa8bf64ff2462a --- /dev/null +++ b/go/test/fixedbugs/issue15470.dir/b.go @@ -0,0 +1,3 @@ +package b + +import _ "./a" // must not fail diff --git a/go/test/fixedbugs/issue15514.dir/a.go b/go/test/fixedbugs/issue15514.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..663303b863fe8a579ba5e51d86d1acbad99f664e --- /dev/null +++ b/go/test/fixedbugs/issue15514.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A struct{ _ int32 } diff --git a/go/test/fixedbugs/issue15514.dir/b.go b/go/test/fixedbugs/issue15514.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..f0750d3a443178addbe68e3085eebf25f2566dce --- /dev/null +++ b/go/test/fixedbugs/issue15514.dir/b.go @@ -0,0 +1,7 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +func B() (_ struct{ _ int32 }) { return } diff --git a/go/test/fixedbugs/issue15514.dir/c.go b/go/test/fixedbugs/issue15514.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..dc2ef5bed526db568bc7b151768c1f9f3f2ffbfe --- /dev/null +++ b/go/test/fixedbugs/issue15514.dir/c.go @@ -0,0 +1,10 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import "./a" +import "./b" + +var _ a.A = b.B() // ERROR "cannot use b\.B|incompatible type" diff --git a/go/test/fixedbugs/issue15548.dir/a.go b/go/test/fixedbugs/issue15548.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3c593fc0f6a4c8da4fa457503fa14f3691f8b662 --- /dev/null +++ b/go/test/fixedbugs/issue15548.dir/a.go @@ -0,0 +1,17 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I0 interface { + I1 +} + +type T struct { + I1 +} + +type I1 interface { + M(*T) // removing * makes crash go away +} diff --git a/go/test/fixedbugs/issue15548.dir/b.go b/go/test/fixedbugs/issue15548.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b46f5adfddbd07848ecade50b14f45e36130c491 --- /dev/null +++ b/go/test/fixedbugs/issue15548.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var X a.T diff --git a/go/test/fixedbugs/issue15548.dir/c.go b/go/test/fixedbugs/issue15548.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..6d3f3be53ec2a465c95096d0692c1df7ccf5724b --- /dev/null +++ b/go/test/fixedbugs/issue15548.dir/c.go @@ -0,0 +1,10 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import ( + _ "./b" + _ "./a" +) diff --git a/go/test/fixedbugs/issue15572.dir/a.go b/go/test/fixedbugs/issue15572.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..1356601430471444af540e3220ddd90f7365355a --- /dev/null +++ b/go/test/fixedbugs/issue15572.dir/a.go @@ -0,0 +1,40 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct { +} + +func F() []T { + return []T{T{}} +} + +func Fi() []T { + return []T{{}} // element with implicit composite literal type +} + +func Fp() []*T { + return []*T{&T{}} +} + +func Fip() []*T { + return []*T{{}} // element with implicit composite literal type +} + +func Gp() map[int]*T { + return map[int]*T{0: &T{}} +} + +func Gip() map[int]*T { + return map[int]*T{0: {}} // element with implicit composite literal type +} + +func Hp() map[*T]int { + return map[*T]int{&T{}: 0} +} + +func Hip() map[*T]int { + return map[*T]int{{}: 0} // key with implicit composite literal type +} diff --git a/go/test/fixedbugs/issue15572.dir/b.go b/go/test/fixedbugs/issue15572.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..355accc88057bd3719659339be6a281d45cd620b --- /dev/null +++ b/go/test/fixedbugs/issue15572.dir/b.go @@ -0,0 +1,27 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() { + a.F() + a.Fi() +} + +func Fp() { + a.Fp() + a.Fip() +} + +func Gp() { + a.Gp() + a.Gip() +} + +func Hp() { + a.Hp() + a.Hip() +} diff --git a/go/test/fixedbugs/issue15609.dir/call.go b/go/test/fixedbugs/issue15609.dir/call.go new file mode 100644 index 0000000000000000000000000000000000000000..48f90fd607f9e7331f9478fe196e6eb27d61dda8 --- /dev/null +++ b/go/test/fixedbugs/issue15609.dir/call.go @@ -0,0 +1,7 @@ +//go:build !amd64 && !386 + +package main + +func jump() { + target() +} diff --git a/go/test/fixedbugs/issue15609.dir/call_386.s b/go/test/fixedbugs/issue15609.dir/call_386.s new file mode 100644 index 0000000000000000000000000000000000000000..751084c485ba99aa41d43e69bfa7895fe33dcaec --- /dev/null +++ b/go/test/fixedbugs/issue15609.dir/call_386.s @@ -0,0 +1,8 @@ +#include "textflag.h" + +DATA ·pointer(SB)/4, $·target(SB) +GLOBL ·pointer(SB),RODATA,$4 + +TEXT ·jump(SB),NOSPLIT,$4 + CALL *·pointer(SB) + RET diff --git a/go/test/fixedbugs/issue15609.dir/call_amd64.s b/go/test/fixedbugs/issue15609.dir/call_amd64.s new file mode 100644 index 0000000000000000000000000000000000000000..09fbe5dfc4abda7b480fcfd801ce8b105c9ce8cd --- /dev/null +++ b/go/test/fixedbugs/issue15609.dir/call_amd64.s @@ -0,0 +1,8 @@ +#include "textflag.h" + +DATA ·pointer(SB)/8, $·target(SB) +GLOBL ·pointer(SB),RODATA,$8 + +TEXT ·jump(SB),NOSPLIT,$8 + CALL *·pointer(SB) + RET diff --git a/go/test/fixedbugs/issue15609.dir/call_decl.go b/go/test/fixedbugs/issue15609.dir/call_decl.go new file mode 100644 index 0000000000000000000000000000000000000000..cdca44a6542f80cb5fc591c63e85f5da704941a4 --- /dev/null +++ b/go/test/fixedbugs/issue15609.dir/call_decl.go @@ -0,0 +1,5 @@ +//go:build amd64 || 386 + +package main + +func jump() diff --git a/go/test/fixedbugs/issue15609.dir/main.go b/go/test/fixedbugs/issue15609.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..4855e31e5ed8f2d4255a5802c4b934e847aca15a --- /dev/null +++ b/go/test/fixedbugs/issue15609.dir/main.go @@ -0,0 +1,14 @@ +package main + +var called bool + +func target() { + called = true +} + +func main() { + jump() + if !called { + panic("target not called") + } +} diff --git a/go/test/fixedbugs/issue15646.dir/a.go b/go/test/fixedbugs/issue15646.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..842f19685fd282c91976dc84875dc726a58d4fc0 --- /dev/null +++ b/go/test/fixedbugs/issue15646.dir/a.go @@ -0,0 +1,23 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct{} + +func (T) m() string { + return "m" +} + +func (*T) mp() string { + return "mp" +} + +func F() func(T) string { + return T.m // method expression +} + +func Fp() func(*T) string { + return (*T).mp // method expression +} diff --git a/go/test/fixedbugs/issue15646.dir/b.go b/go/test/fixedbugs/issue15646.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..3d011ba30195b8ea7c0d6546108e7465946f3ee7 --- /dev/null +++ b/go/test/fixedbugs/issue15646.dir/b.go @@ -0,0 +1,16 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" // import must succeed + +func main() { + if a.F()(a.T{}) != "m" { + panic(0) + } + if a.Fp()(nil) != "mp" { + panic(1) + } +} diff --git a/go/test/fixedbugs/issue15838.dir/a.go b/go/test/fixedbugs/issue15838.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..15b7f1dcfa8230a9e30e8b0f5996c94fcec31750 --- /dev/null +++ b/go/test/fixedbugs/issue15838.dir/a.go @@ -0,0 +1,61 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F1() { +L: + goto L +} + +func F2() { +L: + for { + break L + } +} + +func F3() { +L: + for { + continue L + } +} + +func F4() { + switch { + case true: + fallthrough + default: + } +} + +type T struct{} + +func (T) M1() { +L: + goto L +} + +func (T) M2() { +L: + for { + break L + } +} + +func (T) M3() { +L: + for { + continue L + } +} + +func (T) M4() { + switch { + case true: + fallthrough + default: + } +} diff --git a/go/test/fixedbugs/issue15838.dir/b.go b/go/test/fixedbugs/issue15838.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..9fd6efc33c9b8958576cdaa08961f55f3df3a087 --- /dev/null +++ b/go/test/fixedbugs/issue15838.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type T struct{ a.T } diff --git a/go/test/fixedbugs/issue15920.dir/a.go b/go/test/fixedbugs/issue15920.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..15f92355f730ff6035950c9db32dac0a9d561310 --- /dev/null +++ b/go/test/fixedbugs/issue15920.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Error error + +func F() Error { return nil } diff --git a/go/test/fixedbugs/issue15920.dir/b.go b/go/test/fixedbugs/issue15920.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..0a36c5c6ab80415c038d8e5cf25c03ef687d6da6 --- /dev/null +++ b/go/test/fixedbugs/issue15920.dir/b.go @@ -0,0 +1,7 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import _ "./a" diff --git a/go/test/fixedbugs/issue16133.dir/a1.go b/go/test/fixedbugs/issue16133.dir/a1.go new file mode 100644 index 0000000000000000000000000000000000000000..497cccf3633f957192c07ae58e63792754bc31d9 --- /dev/null +++ b/go/test/fixedbugs/issue16133.dir/a1.go @@ -0,0 +1,7 @@ +package a + +type X string + +func NewX() X { + return "" +} diff --git a/go/test/fixedbugs/issue16133.dir/a2.go b/go/test/fixedbugs/issue16133.dir/a2.go new file mode 100644 index 0000000000000000000000000000000000000000..497cccf3633f957192c07ae58e63792754bc31d9 --- /dev/null +++ b/go/test/fixedbugs/issue16133.dir/a2.go @@ -0,0 +1,7 @@ +package a + +type X string + +func NewX() X { + return "" +} diff --git a/go/test/fixedbugs/issue16133.dir/b.go b/go/test/fixedbugs/issue16133.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..be1bebf889e22ca6f78f7e068f37e9c19c5eb621 --- /dev/null +++ b/go/test/fixedbugs/issue16133.dir/b.go @@ -0,0 +1,7 @@ +package b + +import "./a2" + +type T struct { + X a.X +} diff --git a/go/test/fixedbugs/issue16133.dir/c.go b/go/test/fixedbugs/issue16133.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..b25fe5a9ddb52058e70da3e07217d98ec4bf85b0 --- /dev/null +++ b/go/test/fixedbugs/issue16133.dir/c.go @@ -0,0 +1,10 @@ +package p + +import ( + "./a1" + "./b" +) + +var _ = b.T{ + X: a.NewX(), // ERROR `cannot use "a1"\.NewX\(\)` +} diff --git a/go/test/fixedbugs/issue16317.dir/a.go b/go/test/fixedbugs/issue16317.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3a1b7e021d395d74791f00f066b262eff80fb42a --- /dev/null +++ b/go/test/fixedbugs/issue16317.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import "unsafe" + +func ConstUnsafePointer() unsafe.Pointer { + return unsafe.Pointer(uintptr(0)) +} diff --git a/go/test/fixedbugs/issue16317.dir/b.go b/go/test/fixedbugs/issue16317.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b81391866b254bb799deccc847d78193b3e733e1 --- /dev/null +++ b/go/test/fixedbugs/issue16317.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + _ = a.ConstUnsafePointer() +} diff --git a/go/test/fixedbugs/issue16616.dir/a.go b/go/test/fixedbugs/issue16616.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..0ffdbbe2681a7b058c69a4db326e19f8821cc7dd --- /dev/null +++ b/go/test/fixedbugs/issue16616.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type V struct{ i int } diff --git a/go/test/fixedbugs/issue16616.dir/b.go b/go/test/fixedbugs/issue16616.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..4f238b9a25838572ec7c03a9afc10805a706f30c --- /dev/null +++ b/go/test/fixedbugs/issue16616.dir/b.go @@ -0,0 +1,14 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var V struct{ i int } + +var U struct { + a.V + j int +} diff --git a/go/test/fixedbugs/issue16616.dir/issue16616.go b/go/test/fixedbugs/issue16616.dir/issue16616.go new file mode 100644 index 0000000000000000000000000000000000000000..0bfadb8c7459ca3615d8d079a73f9748d2b93934 --- /dev/null +++ b/go/test/fixedbugs/issue16616.dir/issue16616.go @@ -0,0 +1,26 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "reflect" + + _ "./a" + "./b" +) + +var V struct{ i int } + +func main() { + if got := reflect.ValueOf(b.V).Type().Field(0).PkgPath; got != "b" { + panic(`PkgPath=` + got + ` for first field of b.V, want "b"`) + } + if got := reflect.ValueOf(V).Type().Field(0).PkgPath; got != "main" { + panic(`PkgPath=` + got + ` for first field of V, want "main"`) + } + if got := reflect.ValueOf(b.U).Type().Field(0).PkgPath; got != "b" { + panic(`PkgPath=` + got + ` for first field of b.U, want "b"`) + } +} diff --git a/go/test/fixedbugs/issue18419.dir/other.go b/go/test/fixedbugs/issue18419.dir/other.go new file mode 100644 index 0000000000000000000000000000000000000000..27243d297bf517eb9a807e3fe46fca9fa649dc9b --- /dev/null +++ b/go/test/fixedbugs/issue18419.dir/other.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package other + +type Exported struct { + Member int +} + +func (e *Exported) member() int { return 1 } diff --git a/go/test/fixedbugs/issue18419.dir/test.go b/go/test/fixedbugs/issue18419.dir/test.go new file mode 100644 index 0000000000000000000000000000000000000000..da9639dd72e30d930f4dcf5fad37ee036afd2b56 --- /dev/null +++ b/go/test/fixedbugs/issue18419.dir/test.go @@ -0,0 +1,15 @@ +// errorcheck -0 -m -l + +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./other" + +func InMyCode(e *other.Exported) { + e.member() // ERROR "e\.member undefined .cannot refer to unexported field or method other\.\(\*Exported\)\.member.|unexported field or method" +} + +func main() {} diff --git a/go/test/fixedbugs/issue18895.dir/p.go b/go/test/fixedbugs/issue18895.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..b721f357d28996f260e2ec90ce595d5b9f26005f --- /dev/null +++ b/go/test/fixedbugs/issue18895.dir/p.go @@ -0,0 +1,14 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func F() { // ERROR "can inline" + var v t + v.m() // ERROR "inlining call" +} + +type t int + +func (t) m() {} // ERROR "can inline" diff --git a/go/test/fixedbugs/issue18895.dir/q.go b/go/test/fixedbugs/issue18895.dir/q.go new file mode 100644 index 0000000000000000000000000000000000000000..1e0f2f9dfebfe87a4cd968e8cfbc2735262fb4a0 --- /dev/null +++ b/go/test/fixedbugs/issue18895.dir/q.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package q + +import "./p" + +func x() { // ERROR "can inline x" + p.F() // ERROR "inlining call to .*\.F" "inlining call to .*\.m" +} diff --git a/go/test/fixedbugs/issue18911.dir/a.go b/go/test/fixedbugs/issue18911.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..d2221e761288a26d94b0104cbaa0bd4f9e07f538 --- /dev/null +++ b/go/test/fixedbugs/issue18911.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var X interface{} = struct{ x int }{} diff --git a/go/test/fixedbugs/issue18911.dir/b.go b/go/test/fixedbugs/issue18911.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..da2388b88d1b14d711fa726aecf55bf8575ed1d7 --- /dev/null +++ b/go/test/fixedbugs/issue18911.dir/b.go @@ -0,0 +1,21 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" +import "strings" + +func main() { + defer func() { + p, ok := recover().(error) + if ok && strings.Contains(p.Error(), "different packages") { + return + } + panic(p) + }() + + // expected to fail and report two identical looking (but different) types + _ = a.X.(struct{ x int }) +} diff --git a/go/test/fixedbugs/issue19028.dir/a.go b/go/test/fixedbugs/issue19028.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..361251d7505df9188d33cd961632fcb513b37496 --- /dev/null +++ b/go/test/fixedbugs/issue19028.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package reflect + +import "reflect" + +type Type reflect.Type diff --git a/go/test/fixedbugs/issue19028.dir/main.go b/go/test/fixedbugs/issue19028.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e2ee7b8ca1df2da8a26d4ae028b516e0f1b6dfdf --- /dev/null +++ b/go/test/fixedbugs/issue19028.dir/main.go @@ -0,0 +1,26 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "reflect" + fake "./a" // 2nd package with name "reflect" +) + +type T struct { + _ fake.Type +} + +func (T) f() {} +func (T) G() (_ int) { return } +func (T) H() (_, _ int) { return } + +func main() { + var x T + typ := reflect.TypeOf(x) + for i := 0; i < typ.NumMethod(); i++ { + _ = typ.Method(i) // must not crash + } +} diff --git a/go/test/fixedbugs/issue19261.dir/p.go b/go/test/fixedbugs/issue19261.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..1c44d8a33a3236f834dafa3c296f1a26e1898fc3 --- /dev/null +++ b/go/test/fixedbugs/issue19261.dir/p.go @@ -0,0 +1,24 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func F() { // ERROR "can inline F" + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +} + +func G() { + F() // ERROR "inlining call to F" + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +} diff --git a/go/test/fixedbugs/issue19261.dir/q.go b/go/test/fixedbugs/issue19261.dir/q.go new file mode 100644 index 0000000000000000000000000000000000000000..9f3550abc778da6a1e44688e03912f537984096d --- /dev/null +++ b/go/test/fixedbugs/issue19261.dir/q.go @@ -0,0 +1,17 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package q + +import "./p" + +func H() { + p.F() // ERROR "inlining call to p.F" + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +} diff --git a/go/test/fixedbugs/issue19467.dir/mysync.go b/go/test/fixedbugs/issue19467.dir/mysync.go new file mode 100644 index 0000000000000000000000000000000000000000..d0e6fe098937d12f5f7197dc1ed5534f2df920c3 --- /dev/null +++ b/go/test/fixedbugs/issue19467.dir/mysync.go @@ -0,0 +1,21 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mysync + +import "runtime" + +type WaitGroup struct { + Callers []uintptr +} + +func (wg *WaitGroup) Add(x int) { + wg.Callers = make([]uintptr, 32) + n := runtime.Callers(1, wg.Callers) + wg.Callers = wg.Callers[:n] +} + +func (wg *WaitGroup) Done() { + wg.Add(-1) +} diff --git a/go/test/fixedbugs/issue19467.dir/z.go b/go/test/fixedbugs/issue19467.dir/z.go new file mode 100644 index 0000000000000000000000000000000000000000..cfbf34869cb7cd199974b44a2061ddecd0c98675 --- /dev/null +++ b/go/test/fixedbugs/issue19467.dir/z.go @@ -0,0 +1,35 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "log" + "runtime" + + "./mysync" +) + +func main() { + var wg mysync.WaitGroup + wg.Done() + ci := runtime.CallersFrames(wg.Callers) + frames := make([]runtime.Frame, 0, 4) + for { + frame, more := ci.Next() + frames = append(frames, frame) + if !more { + break + } + } + expecting := []string{ + "test/mysync.(*WaitGroup).Add", + "test/mysync.(*WaitGroup).Done", + } + for i := 0; i < 2; i++ { + if frames[i].Function != expecting[i] { + log.Fatalf("frame %d: got %s, want %s", i, frames[i].Function, expecting[i]) + } + } +} diff --git a/go/test/fixedbugs/issue19507.dir/div_arm.s b/go/test/fixedbugs/issue19507.dir/div_arm.s new file mode 100644 index 0000000000000000000000000000000000000000..0bc33e92ce297f457ee8e72bd367762f0d39832b --- /dev/null +++ b/go/test/fixedbugs/issue19507.dir/div_arm.s @@ -0,0 +1,12 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +TEXT ·f(SB),0,$0-8 + MOVW x+0(FP), R1 + MOVW x+4(FP), R2 + DIVU R1, R2 + DIV R1, R2 + MODU R1, R2 + MOD R1, R2 + RET diff --git a/go/test/fixedbugs/issue19507.dir/main.go b/go/test/fixedbugs/issue19507.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e4e72be87ded8d639369de0f8212229a1248f2a2 --- /dev/null +++ b/go/test/fixedbugs/issue19507.dir/main.go @@ -0,0 +1,16 @@ +//go:build arm + +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Make sure we can compile assembly with DIV and MOD in it. +// They get rewritten to runtime calls on GOARM=5. + +package main + +func f(x, y uint32) + +func main() { + f(5, 8) +} diff --git a/go/test/fixedbugs/issue19548.dir/a.go b/go/test/fixedbugs/issue19548.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3b7cd4b0e23bbaf118aadbd41097efa5c77a0f36 --- /dev/null +++ b/go/test/fixedbugs/issue19548.dir/a.go @@ -0,0 +1,26 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Mode uint + +func (m Mode) String() string { return "mode string" } +func (m *Mode) Addr() *Mode { return m } + +type Stringer interface { + String() string +} + +var global Stringer +var m Mode + +func init() { + // force compilation of the (*Mode).String() wrapper + global = &m +} + +func String() string { + return global.String() + Mode(0).String() +} diff --git a/go/test/fixedbugs/issue19548.dir/b.go b/go/test/fixedbugs/issue19548.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e5e807f43de2318e0c6a09f1132a1bdec60e8c8c --- /dev/null +++ b/go/test/fixedbugs/issue19548.dir/b.go @@ -0,0 +1,24 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +type Value interface { + a.Stringer + Addr() *a.Mode +} + +var global a.Mode + +func f() int { + var v Value + v = &global + return int(v.String()[0]) +} + +func main() { + f() +} diff --git a/go/test/fixedbugs/issue19699.dir/a.go b/go/test/fixedbugs/issue19699.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..83be926fd8d6c6c663231509614c2093f445ff41 --- /dev/null +++ b/go/test/fixedbugs/issue19699.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() { +l1: + if false { + goto l1 + } +} diff --git a/go/test/fixedbugs/issue19699.dir/b.go b/go/test/fixedbugs/issue19699.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e727133bda0d7acf0b954ee09a22a93f09a21bc0 --- /dev/null +++ b/go/test/fixedbugs/issue19699.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.F() +} diff --git a/go/test/fixedbugs/issue19764.dir/a.go b/go/test/fixedbugs/issue19764.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..64538e5bdf056ca6ce6de5d90961c17a9a49416e --- /dev/null +++ b/go/test/fixedbugs/issue19764.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct{ _ int } +func (t T) M() {} + +type I interface { M() } + +func F() { + var t I = &T{} + t.M() // call to the wrapper (*T).M +} diff --git a/go/test/fixedbugs/issue19764.dir/b.go b/go/test/fixedbugs/issue19764.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..d39f125f37c75e259eb915448d4965175bfe87a1 --- /dev/null +++ b/go/test/fixedbugs/issue19764.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + var x a.I = &a.T{} + x.M() // call to the wrapper (*T).M + a.F() // make sure a.F is not dead, which also calls (*T).M inside package a +} diff --git a/go/test/fixedbugs/issue20014.dir/a/a.go b/go/test/fixedbugs/issue20014.dir/a/a.go new file mode 100644 index 0000000000000000000000000000000000000000..1e66326276a40157352dff2ab300a8e637ea3cf7 --- /dev/null +++ b/go/test/fixedbugs/issue20014.dir/a/a.go @@ -0,0 +1,21 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct { + X int `go:"track"` + Y int `go:"track"` + Z int // untracked +} + +func (t *T) GetX() int { + return t.X +} +func (t *T) GetY() int { + return t.Y +} +func (t *T) GetZ() int { + return t.Z +} diff --git a/go/test/fixedbugs/issue20014.dir/main.go b/go/test/fixedbugs/issue20014.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..098ac6b99a800650805803b609d70ce8bd63cb1d --- /dev/null +++ b/go/test/fixedbugs/issue20014.dir/main.go @@ -0,0 +1,60 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "sort" + "strings" + + "issue20014.dir/a" +) + +func main() { + samePackage() + crossPackage() + + // Print fields registered with field tracking. + var fields []string + for _, line := range strings.Split(fieldTrackInfo, "\n") { + if line != "" { + fields = append(fields, strings.Split(line, "\t")[0]) + } + } + sort.Strings(fields) // for stable output, regardless of optimizations + for _, field := range fields { + println(field) + } +} + +type T struct { + X int `go:"track"` + Y int `go:"track"` + Z int // untracked +} + +func (t *T) GetX() int { + return t.X +} +func (t *T) GetY() int { + return t.Y +} +func (t *T) GetZ() int { + return t.Z +} + +func samePackage() { + var t T + println(t.GetX()) + println(t.GetZ()) +} + +func crossPackage() { + var t a.T + println(t.GetX()) + println(t.GetZ()) +} + +// This global variable is set by the linker using the -k option. +var fieldTrackInfo string diff --git a/go/test/fixedbugs/issue20682.dir/p.go b/go/test/fixedbugs/issue20682.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..fc37136d906bf26069d1fb212cd8dd7f0b60456c --- /dev/null +++ b/go/test/fixedbugs/issue20682.dir/p.go @@ -0,0 +1,13 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "strings" + +type T struct{} + +func (T) M() { + strings.HasPrefix("", "") +} diff --git a/go/test/fixedbugs/issue20682.dir/q.go b/go/test/fixedbugs/issue20682.dir/q.go new file mode 100644 index 0000000000000000000000000000000000000000..9554569de0d9ae05c6f11f0668ab93c488b1eea4 --- /dev/null +++ b/go/test/fixedbugs/issue20682.dir/q.go @@ -0,0 +1,13 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package q + +import "./p" + +type T struct{} + +func (T) M() interface{} { + return &p.T{} +} diff --git a/go/test/fixedbugs/issue20682.dir/r.go b/go/test/fixedbugs/issue20682.dir/r.go new file mode 100644 index 0000000000000000000000000000000000000000..73dfe1b3af2cab0ad473d181db19b344f173817a --- /dev/null +++ b/go/test/fixedbugs/issue20682.dir/r.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package r + +import "./q" + +type T struct { + q.T +} diff --git a/go/test/fixedbugs/issue21120.dir/a.go b/go/test/fixedbugs/issue21120.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..f2ee2526717fa863ccc0f3a959bb0c2210a77bfd --- /dev/null +++ b/go/test/fixedbugs/issue21120.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type S struct { + x int +} + +func V() interface{} { + return S{0} +} diff --git a/go/test/fixedbugs/issue21120.dir/b.go b/go/test/fixedbugs/issue21120.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b00bd53a5d58ebacff622d1f80682a0b956fb559 --- /dev/null +++ b/go/test/fixedbugs/issue21120.dir/b.go @@ -0,0 +1,29 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "reflect" + +type X int + +func F1() string { + type x X + + s := struct { + *x + }{nil} + v := reflect.TypeOf(s) + return v.Field(0).PkgPath +} + +func F2() string { + type y X + + s := struct { + *y + }{nil} + v := reflect.TypeOf(s) + return v.Field(0).PkgPath +} diff --git a/go/test/fixedbugs/issue21120.dir/main.go b/go/test/fixedbugs/issue21120.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..1f1ec30e567200df91c8cd5339feb2aa03f22721 --- /dev/null +++ b/go/test/fixedbugs/issue21120.dir/main.go @@ -0,0 +1,25 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "os" + + "./a" + "./b" +) + +func main() { + // Make sure the reflect information for a.S is in the executable. + _ = a.V() + + b1 := b.F1() + b2 := b.F2() + if b1 != b2 { + fmt.Printf("%q (from b.F1()) != %q (from b.F2())\n", b1, b2) + os.Exit(1) + } +} diff --git a/go/test/fixedbugs/issue22877.dir/p.go b/go/test/fixedbugs/issue22877.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..fc86cb9e1ebbf5cf68dddc7be491625f01128058 --- /dev/null +++ b/go/test/fixedbugs/issue22877.dir/p.go @@ -0,0 +1,14 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +type S struct{ i int } +type SS = S + +func sub() + +func main() { + sub() +} diff --git a/go/test/fixedbugs/issue22877.dir/p.s b/go/test/fixedbugs/issue22877.dir/p.s new file mode 100644 index 0000000000000000000000000000000000000000..8b14358cdc90e672666a550e975b41c3ff7fd2ae --- /dev/null +++ b/go/test/fixedbugs/issue22877.dir/p.s @@ -0,0 +1,8 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "go_asm.h" + +TEXT ·sub(SB), 0, $0 + RET diff --git a/go/test/fixedbugs/issue22941.dir/a.go b/go/test/fixedbugs/issue22941.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..7a4ede438fabee33a59247a2a78cc6854165b619 --- /dev/null +++ b/go/test/fixedbugs/issue22941.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package q + +type P int diff --git a/go/test/fixedbugs/issue22941.dir/b.go b/go/test/fixedbugs/issue22941.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..87d59a6764a462ed51aedb25e730c763f0787659 --- /dev/null +++ b/go/test/fixedbugs/issue22941.dir/b.go @@ -0,0 +1,30 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import q "./a" + +type T struct { + X *q.P +} + +func F(in, out *T) { + *out = *in + if in.X != nil { + in, out := &in.X, &out.X + if *in == nil { + *out = nil + } else { + *out = new(q.P) + **out = **in + } + } + return +} + +//go:noinline +func G(x, y *T) { + F(x, y) +} diff --git a/go/test/fixedbugs/issue22941.dir/main.go b/go/test/fixedbugs/issue22941.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..84666adf0df67324eca22169f903966d6c4f302c --- /dev/null +++ b/go/test/fixedbugs/issue22941.dir/main.go @@ -0,0 +1,15 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import p "./b" + +var G int + +func main() { + if G == 101 { + p.G(nil, nil) + } +} diff --git a/go/test/fixedbugs/issue22962.dir/a.go b/go/test/fixedbugs/issue22962.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..7257d7dfabb9c642857240e37d16bc9b0ec3bac4 --- /dev/null +++ b/go/test/fixedbugs/issue22962.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() { + if x := 0; false { + _ = x + } +} diff --git a/go/test/fixedbugs/issue22962.dir/b.go b/go/test/fixedbugs/issue22962.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..4937ef577f37d5fb3b91908756c28d2400735681 --- /dev/null +++ b/go/test/fixedbugs/issue22962.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var V = func() { a.F() } diff --git a/go/test/fixedbugs/issue23179.dir/a.go b/go/test/fixedbugs/issue23179.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3d2816fc69d3c187c48518873278b8a3134e3788 --- /dev/null +++ b/go/test/fixedbugs/issue23179.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Large struct { + x [256]int +} + +func F(x int, _ int, _ bool, _ Large) int { + return x +} diff --git a/go/test/fixedbugs/issue23179.dir/b.go b/go/test/fixedbugs/issue23179.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..4bde498cd8713a4271e3fcfcc6099ff901be7af1 --- /dev/null +++ b/go/test/fixedbugs/issue23179.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func G(x int) int { + return a.F(x, 1, false, a.Large{}) +} diff --git a/go/test/fixedbugs/issue23311.dir/main.go b/go/test/fixedbugs/issue23311.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..fa4cf76b89a7a07faff2bdc5b0506625ca607344 --- /dev/null +++ b/go/test/fixedbugs/issue23311.dir/main.go @@ -0,0 +1,14 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import _ "unsafe" // for linkname + +//go:linkname f runtime.GC +func f() + +func main() { + f() +} diff --git a/go/test/fixedbugs/issue24693.dir/a.go b/go/test/fixedbugs/issue24693.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..8a845ed86ca3975d10fceb768bca7c11cc7d3b16 --- /dev/null +++ b/go/test/fixedbugs/issue24693.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct{} + +func (T) m() { println("FAIL") } + +type I interface{ m() } diff --git a/go/test/fixedbugs/issue24693.dir/b.go b/go/test/fixedbugs/issue24693.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..15ffa4f7ca55aed3b372fa31cc70930b89a56ea6 --- /dev/null +++ b/go/test/fixedbugs/issue24693.dir/b.go @@ -0,0 +1,38 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type T struct{ a.T } + +func (T) m() { println("ok") } + +// The compiler used to not pay attention to package for non-exported +// methods when statically constructing itabs. The consequence of this +// was that the call to b.F1(b.T{}) in c.go would create an itab using +// a.T.m instead of b.T.m. +func F1(i interface{ m() }) { i.m() } + +// The interface method calling convention depends on interface method +// sets being sorted in the same order across compilation units. In +// the test case below, at the call to b.F2(b.T{}) in c.go, the +// interface method set is sorted as { a.m(); b.m() }. +// +// However, while compiling package b, its package path is set to "", +// so the code produced for F2 uses { b.m(); a.m() } as the method set +// order. So again, it ends up calling the wrong method. +// +// Also, this function is marked noinline because it's critical to the +// test that the interface method call happen in this compilation +// unit, and the itab construction happens in c.go. +// +//go:noinline +func F2(i interface { + m() + a.I // embeds m() from package a +}) { + i.m() +} diff --git a/go/test/fixedbugs/issue24693.dir/c.go b/go/test/fixedbugs/issue24693.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..8c6e27b140d0dbf25f322a375dc2afeb742e0738 --- /dev/null +++ b/go/test/fixedbugs/issue24693.dir/c.go @@ -0,0 +1,12 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./b" + +func main() { + b.F1(b.T{}) + b.F2(b.T{}) +} diff --git a/go/test/fixedbugs/issue24761.dir/a.go b/go/test/fixedbugs/issue24761.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..1aa2317bd5b0830d5f7e939ee6df2991f60e1c4d --- /dev/null +++ b/go/test/fixedbugs/issue24761.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T2 struct{} + +func (t *T2) M2(a, b float64) { + variadic(a, b) +} + +func variadic(points ...float64) { + println(points) +} diff --git a/go/test/fixedbugs/issue24761.dir/b.go b/go/test/fixedbugs/issue24761.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..dd3d543a0fc33eda6d6a20d7a363b3ae5f4b17b1 --- /dev/null +++ b/go/test/fixedbugs/issue24761.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type T1 struct { + *a.T2 +} diff --git a/go/test/fixedbugs/issue24801.dir/a.go b/go/test/fixedbugs/issue24801.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..58e6240d8c165c097542dd082788a335d9802e05 --- /dev/null +++ b/go/test/fixedbugs/issue24801.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type main int + +var X main diff --git a/go/test/fixedbugs/issue24801.dir/main.go b/go/test/fixedbugs/issue24801.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5c7db7b4d1f97fcecf66dbde2088edd768c3f7fd --- /dev/null +++ b/go/test/fixedbugs/issue24801.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.X = 1 +} diff --git a/go/test/fixedbugs/issue25055.dir/a.go b/go/test/fixedbugs/issue25055.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..7fea195e2b021823be067ceb39adb0f732e00364 --- /dev/null +++ b/go/test/fixedbugs/issue25055.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var A chan *interface{} diff --git a/go/test/fixedbugs/issue25055.dir/b.go b/go/test/fixedbugs/issue25055.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..01efeae3e640221ac425b9a8a8d89f2de3bc885b --- /dev/null +++ b/go/test/fixedbugs/issue25055.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var _ = <-a.A diff --git a/go/test/fixedbugs/issue25984.dir/p.go b/go/test/fixedbugs/issue25984.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..306d6a489fd61d372c1c97b146fc940c3313f3da --- /dev/null +++ b/go/test/fixedbugs/issue25984.dir/p.go @@ -0,0 +1,15 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type m struct { + link *m +} + +var head *m + +func F(m *int) bool { + return head != nil +} diff --git a/go/test/fixedbugs/issue25984.dir/q.go b/go/test/fixedbugs/issue25984.dir/q.go new file mode 100644 index 0000000000000000000000000000000000000000..64d25870b7856c33cb04d0cc55f775b79011c02e --- /dev/null +++ b/go/test/fixedbugs/issue25984.dir/q.go @@ -0,0 +1,11 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package q + +import "./p" + +func G() { + p.F(nil) +} diff --git a/go/test/fixedbugs/issue26341.dir/a.go b/go/test/fixedbugs/issue26341.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd23c796ba89570d00ffca55c8b0f3e5c27b5b8 --- /dev/null +++ b/go/test/fixedbugs/issue26341.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type k int + +func (k) F() {} + +type M map[k]int diff --git a/go/test/fixedbugs/issue26341.dir/b.go b/go/test/fixedbugs/issue26341.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..30b8c25a5cf7c4526f6c64e0f43d653e6bab352d --- /dev/null +++ b/go/test/fixedbugs/issue26341.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func f() { + for k := range (a.M{}) { + k.F() + } +} diff --git "a/go/test/fixedbugs/issue27836.dir/\303\236foo.go" "b/go/test/fixedbugs/issue27836.dir/\303\236foo.go" new file mode 100644 index 0000000000000000000000000000000000000000..ea6be0f49fdcc5d537e7126e0e7a26e185939cc2 --- /dev/null +++ "b/go/test/fixedbugs/issue27836.dir/\303\236foo.go" @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package Þfoo + +var ÞbarV int = 101 + +func Þbar(x int) int { + defer func() { ÞbarV += 3 }() + return Þblix(x) +} + +func Þblix(x int) int { + defer func() { ÞbarV += 9 }() + return ÞbarV + x +} diff --git "a/go/test/fixedbugs/issue27836.dir/\303\236main.go" "b/go/test/fixedbugs/issue27836.dir/\303\236main.go" new file mode 100644 index 0000000000000000000000000000000000000000..596c620d80a321cf8c4e174ef3692d5914eef01c --- /dev/null +++ "b/go/test/fixedbugs/issue27836.dir/\303\236main.go" @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + + "./Þfoo" + Þblix "./Þfoo" +) + +func main() { + fmt.Printf("Þfoo.Þbar(33) returns %v\n", Þfoo.Þbar(33)) + fmt.Printf("Þblix.Þbar(33) returns %v\n", Þblix.Þbar(33)) +} diff --git a/go/test/fixedbugs/issue29610.dir/a.go b/go/test/fixedbugs/issue29610.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..ccbe451bca9cbfe427d0ba523e7442dd30d6b7ea --- /dev/null +++ b/go/test/fixedbugs/issue29610.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I interface { + M(init bool) +} + +var V I + +func init() { + V = nil +} diff --git a/go/test/fixedbugs/issue29610.dir/b.go b/go/test/fixedbugs/issue29610.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..c2016de3d05ca6ab7df42d7f20d45f5976004319 --- /dev/null +++ b/go/test/fixedbugs/issue29610.dir/b.go @@ -0,0 +1,17 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type S struct { + a.I +} + +var V a.I + +func init() { + V = S{} +} diff --git a/go/test/fixedbugs/issue29610.dir/main.go b/go/test/fixedbugs/issue29610.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..29437bfa618638b5f740d63a0a5893e4dce4e1d1 --- /dev/null +++ b/go/test/fixedbugs/issue29610.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./b" + +var v b.S + +func main() {} diff --git a/go/test/fixedbugs/issue29612.dir/main.go b/go/test/fixedbugs/issue29612.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..97415c445fa34792486e38d1b72594a3a5634a3e --- /dev/null +++ b/go/test/fixedbugs/issue29612.dir/main.go @@ -0,0 +1,49 @@ +// run + +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Do not panic on conversion to anonymous interface, which +// is similar-looking interface types in different packages. + +package main + +import ( + "fmt" + + ssa1 "issue29612.dir/p1/ssa" + ssa2 "issue29612.dir/p2/ssa" +) + +func main() { + v1 := &ssa1.T{} + _ = v1 + + v2 := &ssa2.T{} + ssa2.Works(v2) + ssa2.Panics(v2) // This call must not panic + + swt(v1, 1) + swt(v2, 2) +} + +//go:noinline +func swt(i interface{}, want int) { + var got int + switch i.(type) { + case *ssa1.T: + got = 1 + case *ssa2.T: + got = 2 + + case int8, int16, int32, int64: + got = 3 + case uint8, uint16, uint32, uint64: + got = 4 + } + + if got != want { + panic(fmt.Sprintf("switch %v: got %d, want %d", i, got, want)) + } +} diff --git a/go/test/fixedbugs/issue29612.dir/p1/ssa/ssa.go b/go/test/fixedbugs/issue29612.dir/p1/ssa/ssa.go new file mode 100644 index 0000000000000000000000000000000000000000..8f6eb97f8f8494abcbaa4dc055e589225a9b14b6 --- /dev/null +++ b/go/test/fixedbugs/issue29612.dir/p1/ssa/ssa.go @@ -0,0 +1,18 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ssa + +type T struct{} + +func (T) foo() {} + +type fooer interface { + foo() +} + +func Unused(v interface{}) { + v.(fooer).foo() + v.(interface{ foo() }).foo() +} diff --git a/go/test/fixedbugs/issue29612.dir/p2/ssa/ssa.go b/go/test/fixedbugs/issue29612.dir/p2/ssa/ssa.go new file mode 100644 index 0000000000000000000000000000000000000000..df57314b8ce01d82d2dbe8ba1ab21b84a6211f05 --- /dev/null +++ b/go/test/fixedbugs/issue29612.dir/p2/ssa/ssa.go @@ -0,0 +1,28 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ssa + +type T struct{} + +func (T) foo() {} + +type fooer interface { + foo() +} + +func Works(v interface{}) { + switch v.(type) { + case interface{}: + v.(fooer).foo() + } +} + +func Panics(v interface{}) { + switch v.(type) { + case interface{}: + v.(fooer).foo() + v.(interface{ foo() }).foo() + } +} diff --git a/go/test/fixedbugs/issue29919.dir/a.go b/go/test/fixedbugs/issue29919.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3b1dac40aab0ce3f0f07c47cd8d9e9491f80db6f --- /dev/null +++ b/go/test/fixedbugs/issue29919.dir/a.go @@ -0,0 +1,75 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Make sure tracebacks from initialization code are reported correctly. + +package a + +import ( + "fmt" + "runtime" + "strings" +) + +var x = f() // line 15 + +func f() int { + var b [4096]byte + n := runtime.Stack(b[:], false) // line 19 + s := string(b[:n]) + var pcs [10]uintptr + n = runtime.Callers(1, pcs[:]) // line 22 + + // Check the Stack results. + if debug { + println(s) + } + if strings.Contains(s, "autogenerated") { + panic("autogenerated code in traceback") + } + if !strings.Contains(s, "a.go:15") { + panic("missing a.go:15") + } + if !strings.Contains(s, "a.go:19") { + panic("missing a.go:19") + } + if !strings.Contains(s, "a.init") { + panic("missing a.init") + } + + // Check the CallersFrames results. + if debug { + iter := runtime.CallersFrames(pcs[:n]) + for { + f, more := iter.Next() + fmt.Printf("%s %s:%d\n", f.Function, f.File, f.Line) + if !more { + break + } + } + } + iter := runtime.CallersFrames(pcs[:n]) + f, more := iter.Next() + if f.Function != "test/a.f" || !strings.HasSuffix(f.File, "a.go") || f.Line != 22 { + panic(fmt.Sprintf("bad f %v\n", f)) + } + if !more { + panic("traceback truncated after f") + } + f, more = iter.Next() + if f.Function != "test/a.init" || !strings.HasSuffix(f.File, "a.go") || f.Line != 15 { + panic(fmt.Sprintf("bad init %v\n", f)) + } + if !more { + panic("traceback truncated after init") + } + f, _ = iter.Next() + if !strings.HasPrefix(f.Function, "runtime.") { + panic("runtime. driver missing") + } + + return 0 +} + +const debug = false diff --git a/go/test/fixedbugs/issue29919.dir/main.go b/go/test/fixedbugs/issue29919.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3e99ca891b55dce6ab6f75646e22d674fcafe705 --- /dev/null +++ b/go/test/fixedbugs/issue29919.dir/main.go @@ -0,0 +1,10 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import _ "./a" + +func main() { +} diff --git a/go/test/fixedbugs/issue30659.dir/a.go b/go/test/fixedbugs/issue30659.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3837e021c4817381de7aaa3a0e7f76987777fb09 --- /dev/null +++ b/go/test/fixedbugs/issue30659.dir/a.go @@ -0,0 +1,19 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I interface { + I2 +} +type I2 interface { + M() +} +type S struct{} + +func (*S) M() {} + +func New() I { + return &S{} +} diff --git a/go/test/fixedbugs/issue30659.dir/b.go b/go/test/fixedbugs/issue30659.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..272e520582e8f02c88e564b8e118aae99964a495 --- /dev/null +++ b/go/test/fixedbugs/issue30659.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import ( + "./a" +) + +func B(p1 a.I, p2 a.I2) int { + return 42 +} diff --git a/go/test/fixedbugs/issue30862.dir/a/a.go b/go/test/fixedbugs/issue30862.dir/a/a.go new file mode 100644 index 0000000000000000000000000000000000000000..c23f4de1efd1a91bdf42ab66e1dd3afe551fdafc --- /dev/null +++ b/go/test/fixedbugs/issue30862.dir/a/a.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var pl int + +type NoitfStruct struct { + F int + G int +} + +//go:nointerface +func (t *NoitfStruct) NoInterfaceMethod() {} diff --git a/go/test/fixedbugs/issue30862.dir/b/b.go b/go/test/fixedbugs/issue30862.dir/b/b.go new file mode 100644 index 0000000000000000000000000000000000000000..230221d5036248af1c1c80415a675cc55f8ee16e --- /dev/null +++ b/go/test/fixedbugs/issue30862.dir/b/b.go @@ -0,0 +1,29 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "issue30862.dir/a" + +type EmbedImported struct { + a.NoitfStruct +} + +func Test() []string { + bad := []string{} + x := interface{}(new(a.NoitfStruct)) + if _, ok := x.(interface { + NoInterfaceMethod() + }); ok { + bad = append(bad, "fail 1") + } + + x = interface{}(new(EmbedImported)) + if _, ok := x.(interface { + NoInterfaceMethod() + }); ok { + bad = append(bad, "fail 2") + } + return bad +} diff --git a/go/test/fixedbugs/issue30862.dir/main.go b/go/test/fixedbugs/issue30862.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..1489c5a34255fbb01b93700bd1150d90de93920a --- /dev/null +++ b/go/test/fixedbugs/issue30862.dir/main.go @@ -0,0 +1,28 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "os" + + "issue30862.dir/b" +) + +// Test case for issue 30862. + +// Be aware that unless GOEXPERIMENT=fieldtrack is set when building +// the compiler, this test will fail if executed with a regular GC +// compiler. + +func main() { + bad := b.Test() + if len(bad) > 0 { + for _, s := range bad { + fmt.Fprintf(os.Stderr, "test failed: %s\n", s) + } + os.Exit(1) + } +} diff --git a/go/test/fixedbugs/issue30907.dir/a.go b/go/test/fixedbugs/issue30907.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e1a5c0cc3b6fbea2d4d8fc9835ce7ee3b8c4bb33 --- /dev/null +++ b/go/test/fixedbugs/issue30907.dir/a.go @@ -0,0 +1,19 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type UUID string + +func New() UUID { + return Must(NewRandom()) +} + +func NewRandom() (UUID, error) { + return "", nil +} + +func Must(uuid UUID, err error) UUID { + return uuid +} diff --git a/go/test/fixedbugs/issue30907.dir/b.go b/go/test/fixedbugs/issue30907.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..f4f5fc4fdd12714522a02d41543bdd7e08aaf6df --- /dev/null +++ b/go/test/fixedbugs/issue30907.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "./a" + +func F() { + a.New() +} diff --git a/go/test/fixedbugs/issue30908.dir/a.go b/go/test/fixedbugs/issue30908.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..2f0abc3780c2a11fe8d0f560f9b7dac8ba229ecc --- /dev/null +++ b/go/test/fixedbugs/issue30908.dir/a.go @@ -0,0 +1,32 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import ( + "errors" + "strings" +) + +var G interface{} + +func Unmarshal(data []byte, o interface{}) error { + G = o + v, ok := o.(*map[string]interface{}) + if !ok { + return errors.New("eek") + } + vals := make(map[string]interface{}) + s := string(data) + items := strings.Split(s, " ") + var err error + for _, item := range items { + vals[item] = s + if item == "error" { + err = errors.New("ouch") + } + } + *v = vals + return err +} diff --git a/go/test/fixedbugs/issue30908.dir/b.go b/go/test/fixedbugs/issue30908.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..2f543985b4fc39ccd24eba19ffd7ea0a1252496f --- /dev/null +++ b/go/test/fixedbugs/issue30908.dir/b.go @@ -0,0 +1,35 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import ( + "io/ioutil" + + "./a" +) + +var G int + +// An inlinable function. To trigger the bug in question this needs +// to be inlined here within the package and also inlined into some +// other package that imports it. +func ReadValues(data []byte) (vals map[string]interface{}, err error) { + err = a.Unmarshal(data, &vals) + if len(vals) == 0 { + vals = map[string]interface{}{} + } + return +} + +// A local call to the function above, which triggers the "move to heap" +// of the output param. +func CallReadValues(filename string) (map[string]interface{}, error) { + defer func() { G++ }() + data, err := ioutil.ReadFile(filename) + if err != nil { + return map[string]interface{}{}, err + } + return ReadValues(data) +} diff --git a/go/test/fixedbugs/issue30908.dir/m.go b/go/test/fixedbugs/issue30908.dir/m.go new file mode 100644 index 0000000000000000000000000000000000000000..a170a6eed6fca31f4253f96ca5d29c8a725ab12d --- /dev/null +++ b/go/test/fixedbugs/issue30908.dir/m.go @@ -0,0 +1,21 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "os" + + "./b" +) + +func main() { + seed := "some things are better" + bsl := []byte(seed) + b.CallReadValues("/dev/null") + vals, err := b.ReadValues(bsl) + if vals["better"] != seed || err != nil { + os.Exit(1) + } +} diff --git a/go/test/fixedbugs/issue31053.dir/f1.go b/go/test/fixedbugs/issue31053.dir/f1.go new file mode 100644 index 0000000000000000000000000000000000000000..610f393818872d07b48650c0f7d6825033b36e30 --- /dev/null +++ b/go/test/fixedbugs/issue31053.dir/f1.go @@ -0,0 +1,18 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package f1 + +type Foo struct { + doneChan chan bool + Name string + fOO int + hook func() +} + +func (f *Foo) Exported() { +} + +func (f *Foo) unexported() { +} diff --git a/go/test/fixedbugs/issue31053.dir/main.go b/go/test/fixedbugs/issue31053.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3bc75d17d2d80b660d00fda696a2516333478bc8 --- /dev/null +++ b/go/test/fixedbugs/issue31053.dir/main.go @@ -0,0 +1,42 @@ +// errorcheck + +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "./f1" + +func main() { + f := f1.Foo{ + doneChan: nil, // ERROR "cannot refer to unexported field 'doneChan' in struct literal of type f1.Foo" + DoneChan: nil, // ERROR "unknown field 'DoneChan' in struct literal of type f1.Foo" + Name: "hey", + name: "there", // ERROR "unknown field 'name' in struct literal of type f1.Foo .but does have Name." + noSuchPrivate: true, // ERROR "unknown field 'noSuchPrivate' in struct literal of type f1.Foo" + NoSuchPublic: true, // ERROR "unknown field 'NoSuchPublic' in struct literal of type f1.Foo" + foo: true, // ERROR "unknown field 'foo' in struct literal of type f1.Foo" + hook: func() {}, // ERROR "cannot refer to unexported field 'hook' in struct literal of type f1.Foo" + unexported: func() {}, // ERROR "unknown field 'unexported' in struct literal of type f1.Foo" + Exported: func() {}, // ERROR "unknown field 'Exported' in struct literal of type f1.Foo" + } + f.doneChan = nil // ERROR "f.doneChan undefined .cannot refer to unexported field or method doneChan." + f.DoneChan = nil // ERROR "f.DoneChan undefined .type f1.Foo has no field or method DoneChan." + f.name = nil // ERROR "f.name undefined .type f1.Foo has no field or method name, but does have Name." + + _ = f.doneChan // ERROR "f.doneChan undefined .cannot refer to unexported field or method doneChan." + _ = f.DoneChan // ERROR "f.DoneChan undefined .type f1.Foo has no field or method DoneChan." + _ = f.Name + _ = f.name // ERROR "f.name undefined .type f1.Foo has no field or method name, but does have Name." + _ = f.noSuchPrivate // ERROR "f.noSuchPrivate undefined .type f1.Foo has no field or method noSuchPrivate." + _ = f.NoSuchPublic // ERROR "f.NoSuchPublic undefined .type f1.Foo has no field or method NoSuchPublic." + _ = f.foo // ERROR "f.foo undefined .type f1.Foo has no field or method foo." + _ = f.Exported + _ = f.exported // ERROR "f.exported undefined .type f1.Foo has no field or method exported, but does have Exported." + _ = f.Unexported // ERROR "f.Unexported undefined .type f1.Foo has no field or method Unexported." + _ = f.unexported // ERROR "f.unexported undefined .cannot refer to unexported field or method unexported." + f.unexported = 10 // ERROR "f.unexported undefined .cannot refer to unexported field or method unexported." + f.unexported() // ERROR "f.unexported undefined .cannot refer to unexported field or method unexported." + _ = f.hook // ERROR "f.hook undefined .cannot refer to unexported field or method hook." +} diff --git a/go/test/fixedbugs/issue31252.dir/a.go b/go/test/fixedbugs/issue31252.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..fa431502c087b88f118646f84cf5904fa8edeeaf --- /dev/null +++ b/go/test/fixedbugs/issue31252.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import "fmt" + +type IndexController struct{} + +func (this *IndexController) Index(m *string) { + fmt.Println(m) +} diff --git a/go/test/fixedbugs/issue31252.dir/b.go b/go/test/fixedbugs/issue31252.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..9bfc0ff92eabf7c8fc84b5d2eb3b95f216813edd --- /dev/null +++ b/go/test/fixedbugs/issue31252.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "fmt" + +type IndexController struct{} + +func (this *IndexController) Index(m *string) { + fmt.Println(m) +} diff --git a/go/test/fixedbugs/issue31252.dir/c.go b/go/test/fixedbugs/issue31252.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..98ecf6117720c6d115ccbe2d75ea3a23aa74df8a --- /dev/null +++ b/go/test/fixedbugs/issue31252.dir/c.go @@ -0,0 +1,26 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import ( + "./a" + "./b" +) + +type HandlerFunc func(*string) + +func RouterInit() { + //home API + homeIndex := &a.IndexController{} + GET("/home/index/index", homeIndex.Index) + //admin API + adminIndex := &b.IndexController{} + GET("/admin/index/index", adminIndex.Index) + return +} + +func GET(path string, handlers ...HandlerFunc) { + return +} diff --git a/go/test/fixedbugs/issue31252.dir/main.go b/go/test/fixedbugs/issue31252.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6c0c9ce5d2c380029ab9cedd19c947069ee88d9e --- /dev/null +++ b/go/test/fixedbugs/issue31252.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./c" + +func main() { + c.RouterInit() +} diff --git a/go/test/fixedbugs/issue31636.dir/a.go b/go/test/fixedbugs/issue31636.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e57e0d5fb7dd87d70de60e769b54e7ec2276822f --- /dev/null +++ b/go/test/fixedbugs/issue31636.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func init() { + println("a") +} diff --git a/go/test/fixedbugs/issue31636.dir/b.go b/go/test/fixedbugs/issue31636.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..990e68209b9903522f324bad2cdde5c270e3c5ce --- /dev/null +++ b/go/test/fixedbugs/issue31636.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +func init() { + println("b") +} diff --git a/go/test/fixedbugs/issue31636.dir/c.go b/go/test/fixedbugs/issue31636.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..e53529aa591271e84a714e128770eabdef8b92e8 --- /dev/null +++ b/go/test/fixedbugs/issue31636.dir/c.go @@ -0,0 +1,9 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +func init() { + println("c") +} diff --git a/go/test/fixedbugs/issue31636.dir/main.go b/go/test/fixedbugs/issue31636.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..bbc58369d3fcd6b640c682a2ac0ea679125ade5b --- /dev/null +++ b/go/test/fixedbugs/issue31636.dir/main.go @@ -0,0 +1,20 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +// We want the initializers of these packages to occur in source code +// order. See issue 31636. This is the behavior up to and including +// 1.13. For 1.14, we will move to a variant of lexicographic ordering +// which will require a change to the test output of this test. +import ( + _ "./c" + + _ "./b" + + _ "./a" +) + +func main() { +} diff --git a/go/test/fixedbugs/issue31637.dir/a.go b/go/test/fixedbugs/issue31637.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..71f392697c4967a2d384c56e0667636b109b9782 --- /dev/null +++ b/go/test/fixedbugs/issue31637.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type dO struct { + x int +} + +type EDO struct{} + +func (EDO) Apply(*dO) {} + +var X EDO diff --git a/go/test/fixedbugs/issue31637.dir/b.go b/go/test/fixedbugs/issue31637.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..ce83b000df8376167409ad531ff82456db1d10b5 --- /dev/null +++ b/go/test/fixedbugs/issue31637.dir/b.go @@ -0,0 +1,19 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +type No struct { + a.EDO +} + +func X() No { + return No{} +} + +func main() { + X() +} diff --git a/go/test/fixedbugs/issue31959.dir/a.go b/go/test/fixedbugs/issue31959.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..6c7ffa38c12b8268c54e371c3860313a847938cc --- /dev/null +++ b/go/test/fixedbugs/issue31959.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct{} + +func F() { + type T = int + println(T(0)) +} diff --git a/go/test/fixedbugs/issue31959.dir/main.go b/go/test/fixedbugs/issue31959.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6604e3abbdaa4c9d44ace2cc8a691bb15bef7f71 --- /dev/null +++ b/go/test/fixedbugs/issue31959.dir/main.go @@ -0,0 +1,21 @@ +// run + +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check import package contains type alias in function +// with the same name with an export type not panic + +package main + +import ( + "fmt" + + "./a" +) + +func main() { + fmt.Println(a.T{}) + a.F() +} diff --git a/go/test/fixedbugs/issue32595.dir/a.go b/go/test/fixedbugs/issue32595.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..8342dd5cbcff84c39e6fcdb142c6ddf94bdcd122 --- /dev/null +++ b/go/test/fixedbugs/issue32595.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func A() { + defer func() {}() +} diff --git a/go/test/fixedbugs/issue32595.dir/b.go b/go/test/fixedbugs/issue32595.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..9a13a575a87ff4b07da757e8b6e3ecb4e2aa3a34 --- /dev/null +++ b/go/test/fixedbugs/issue32595.dir/b.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "reflect" + +func B() { + t1 := reflect.TypeOf([0]byte{}) + t2 := reflect.TypeOf(new([0]byte)).Elem() + if t1 != t2 { + panic("[0]byte types do not match") + } +} diff --git a/go/test/fixedbugs/issue32595.dir/main.go b/go/test/fixedbugs/issue32595.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..979efe3a910fec6d8e8b4778605dbdaaad8d3010 --- /dev/null +++ b/go/test/fixedbugs/issue32595.dir/main.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "./b" +) + +func main() { + a.A() + b.B() +} diff --git a/go/test/fixedbugs/issue32778.dir/a.go b/go/test/fixedbugs/issue32778.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..1e6ac012334c507be36315a7b03cbeba47c42696 --- /dev/null +++ b/go/test/fixedbugs/issue32778.dir/a.go @@ -0,0 +1,18 @@ +// Copyright 2019 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package a + +import "strings" + +type Name string + +type FullName string + +func (n FullName) Name() Name { + if i := strings.LastIndexByte(string(n), '.'); i >= 0 { + return Name(n[i+1:]) + } + return Name(n) +} diff --git a/go/test/fixedbugs/issue32778.dir/b.go b/go/test/fixedbugs/issue32778.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..a0ee398d268c3ff7475652e68362fba66953b9b1 --- /dev/null +++ b/go/test/fixedbugs/issue32778.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package b + +import "./a" + +func Expo(fn a.FullName) a.Name { + return fn.Name() +} diff --git a/go/test/fixedbugs/issue32901.dir/a.go b/go/test/fixedbugs/issue32901.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..54ed7713f6432a729c6e72005e0025197d518189 --- /dev/null +++ b/go/test/fixedbugs/issue32901.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct { x int } + +func F() interface{} { + return [2]T{} +} + +func P() interface{} { + return &[2]T{} +} diff --git a/go/test/fixedbugs/issue32901.dir/b.go b/go/test/fixedbugs/issue32901.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..932d7b0afa53f05266e65476ce1f92e744a870d2 --- /dev/null +++ b/go/test/fixedbugs/issue32901.dir/b.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() interface{} { + return a.F() +} + +func P() interface{} { + return a.P() +} diff --git a/go/test/fixedbugs/issue32901.dir/c.go b/go/test/fixedbugs/issue32901.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..5f31c7ff028b6dc0d05af923e4e5d58d1edb419b --- /dev/null +++ b/go/test/fixedbugs/issue32901.dir/c.go @@ -0,0 +1,17 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import "./b" + +func F() interface{} { + go func(){}() // make it non-inlineable + return b.F() +} + +func P() interface{} { + go func(){}() // make it non-inlineable + return b.P() +} diff --git a/go/test/fixedbugs/issue32901.dir/main.go b/go/test/fixedbugs/issue32901.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..673c6ab3e0f894b886f459f1cd10ba38e52688bd --- /dev/null +++ b/go/test/fixedbugs/issue32901.dir/main.go @@ -0,0 +1,21 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "reflect" + + "./c" +) + +func main() { + x := c.F() + p := c.P() + t := reflect.PointerTo(reflect.TypeOf(x)) + tp := reflect.TypeOf(p) + if t != tp { + panic("FAIL") + } +} diff --git a/go/test/fixedbugs/issue32922.dir/a.go b/go/test/fixedbugs/issue32922.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..b13c4b404d13bb2fa3eae332000f9d963ee5f524 --- /dev/null +++ b/go/test/fixedbugs/issue32922.dir/a.go @@ -0,0 +1,18 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func A() int { + return p("count") +} + +func p(which string, args ...string) int { + switch which { + case "count", "something": + return 1 + default: + return 2 + } +} diff --git a/go/test/fixedbugs/issue32922.dir/b.go b/go/test/fixedbugs/issue32922.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..fdaf42d3dff4ebd35bd664e348956f5f3349759c --- /dev/null +++ b/go/test/fixedbugs/issue32922.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func B() int { + return 99 + a.A() +} diff --git a/go/test/fixedbugs/issue33013.dir/a.go b/go/test/fixedbugs/issue33013.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..056be88aeac9c7e9817e09c9ccfd69e05c74ae5f --- /dev/null +++ b/go/test/fixedbugs/issue33013.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type G interface { + UsesEmpty(p interface{}) int +} diff --git a/go/test/fixedbugs/issue33013.dir/b.go b/go/test/fixedbugs/issue33013.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f5cc0650551d98a762e1751d91f24a2e719fd7 --- /dev/null +++ b/go/test/fixedbugs/issue33013.dir/b.go @@ -0,0 +1,24 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type Service uint64 +type ServiceDesc struct { + X int + uc +} + +type uc interface { + f() a.G +} + +var q int + +func RS(svcd *ServiceDesc, server interface{}, qq uint8) *Service { + defer func() { q += int(qq) }() + return nil +} diff --git a/go/test/fixedbugs/issue33013.dir/c.go b/go/test/fixedbugs/issue33013.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..74425dfaae10fd77860b6ecc10d7e25ac7519af8 --- /dev/null +++ b/go/test/fixedbugs/issue33013.dir/c.go @@ -0,0 +1,19 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import ( + "./a" + "./b" +) + +type BI interface { + Something(s int64) int64 + Another(pxp a.G) int32 +} + +func BRS(sd *b.ServiceDesc, server BI, xyz int) *b.Service { + return b.RS(sd, server, 7) +} diff --git a/go/test/fixedbugs/issue33013.dir/d.go b/go/test/fixedbugs/issue33013.dir/d.go new file mode 100644 index 0000000000000000000000000000000000000000..c70c6647e8ccb4ae08d6dd4581548694549113f9 --- /dev/null +++ b/go/test/fixedbugs/issue33013.dir/d.go @@ -0,0 +1,16 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package d + +import ( + "./b" + "./c" +) + +var GA b.Service + +func C() { + c.BRS(nil, nil, 22) +} diff --git a/go/test/fixedbugs/issue33020.dir/a.go b/go/test/fixedbugs/issue33020.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..948f4fdf3b2af3fb006f47862ede5a8b8da90775 --- /dev/null +++ b/go/test/fixedbugs/issue33020.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var G1 int +var G2 int +var G3 int +var G4 int +var G5 int +var G6 int +var G7 int +var G8 int +var G9 int +var G10 int diff --git a/go/test/fixedbugs/issue33020.dir/b.go b/go/test/fixedbugs/issue33020.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..14a2a87041e0d869ac814210cdc3f41e5eff5e67 --- /dev/null +++ b/go/test/fixedbugs/issue33020.dir/b.go @@ -0,0 +1,22 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var N n + +type n struct{} + +func (r n) M1() int { return a.G1 } +func (r n) M2() int { return a.G2 } +func (r n) M3() int { return a.G3 } +func (r n) M4() int { return a.G4 } +func (r n) M5() int { return a.G5 } +func (r n) M6() int { return a.G6 } +func (r n) M7() int { return a.G7 } +func (r n) M8() int { return a.G8 } +func (r n) M9() int { return a.G9 } +func (r n) M10() int { return a.G10 } diff --git a/go/test/fixedbugs/issue33020a.dir/a.go b/go/test/fixedbugs/issue33020a.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..91764982dc456a26f42ffd042c8945ae7881deed --- /dev/null +++ b/go/test/fixedbugs/issue33020a.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type FArg func(args []string) error + +type Command struct { + Name string + Arg1 FArg + Arg2 func(args []string) error +} diff --git a/go/test/fixedbugs/issue33020a.dir/b.go b/go/test/fixedbugs/issue33020a.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..5b0f9d86d72acd9cb40ae5d3d8ba2606df8c0f40 --- /dev/null +++ b/go/test/fixedbugs/issue33020a.dir/b.go @@ -0,0 +1,14 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +var Cmd = &a.Command{ + Name: "test", +} + +func main() { +} diff --git a/go/test/fixedbugs/issue33158.dir/a.go b/go/test/fixedbugs/issue33158.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..28714e0c991e8936bea5d1dcf09b697ed71690fb --- /dev/null +++ b/go/test/fixedbugs/issue33158.dir/a.go @@ -0,0 +1,25 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var GS string + +func M() string { + if s := getname("Fred"); s != "" { + return s + } + if s := getname("Joe"); s != "" { + return s + } + + return string("Alex") +} + +// getname can be any function returning a string, just has to be non-inlinable. + +//go:noinline +func getname(s string) string { + return s + "foo" +} diff --git a/go/test/fixedbugs/issue33158.dir/b.go b/go/test/fixedbugs/issue33158.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..4174b417ec174f9cbde3457b6fbf679a09300c0e --- /dev/null +++ b/go/test/fixedbugs/issue33158.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func B() string { + return a.M() +} diff --git a/go/test/fixedbugs/issue33219.dir/a.go b/go/test/fixedbugs/issue33219.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..2d96301f9cfedbf07d92159b18e2ba0a6436c525 --- /dev/null +++ b/go/test/fixedbugs/issue33219.dir/a.go @@ -0,0 +1,17 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A interface { + M(i interface{}) interface{} +} + +var a1 A +var a2 A + +func V(p A, k, v interface{}) A { + defer func() { a1, a2 = a2, a1 }() + return a1 +} diff --git a/go/test/fixedbugs/issue33219.dir/b.go b/go/test/fixedbugs/issue33219.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..2a8f518bef5c3b00af88386961851ee6617e7f52 --- /dev/null +++ b/go/test/fixedbugs/issue33219.dir/b.go @@ -0,0 +1,25 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type Service uint64 + +var q *Service +var r *Service + +type f struct{} + +var fk f + +func No(s a.A, qq uint8) *Service { + defer func() { q, r = r, q }() + return q +} + +func Yes(s a.A, p *uint64) a.A { + return a.V(s, fk, p) +} diff --git a/go/test/fixedbugs/issue33219.dir/c.go b/go/test/fixedbugs/issue33219.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..a78fe69a9e948d2bcbcc78aab948b4f45019a794 --- /dev/null +++ b/go/test/fixedbugs/issue33219.dir/c.go @@ -0,0 +1,20 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import ( + "./a" + "./b" +) + +type BI interface { + Another(pxp a.A) int32 +} + +//go:noinline +func BRS(sd a.A, xyz int) *b.Service { + x := b.Yes(sd, nil) + return b.No(x, 1) +} diff --git a/go/test/fixedbugs/issue33739.dir/a.go b/go/test/fixedbugs/issue33739.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..7eb5b927c498872039e41bdd0a9588e48a5fd0e1 --- /dev/null +++ b/go/test/fixedbugs/issue33739.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() func() { + return f +} + +func f() {} diff --git a/go/test/fixedbugs/issue33739.dir/b.go b/go/test/fixedbugs/issue33739.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..d22fe34d668d97c1f69c1359a05dc8cb911ff2c7 --- /dev/null +++ b/go/test/fixedbugs/issue33739.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.F()() +} diff --git a/go/test/fixedbugs/issue33866.dir/a.go b/go/test/fixedbugs/issue33866.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..9c782c5eedf37c331a0b307fc43f22d5b3ac8fcf --- /dev/null +++ b/go/test/fixedbugs/issue33866.dir/a.go @@ -0,0 +1,18 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Builder struct { + x int +} + +func (tb Builder) Build() (out struct { + x interface{} + s string +}) { + out.x = nil + out.s = "hello!" + return +} diff --git a/go/test/fixedbugs/issue33866.dir/b.go b/go/test/fixedbugs/issue33866.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..aa2a32271c738a922412591472a8ae9308a93c71 --- /dev/null +++ b/go/test/fixedbugs/issue33866.dir/b.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type ( + ABuilder = a.Builder +) + +func Bfunc() ABuilder { + return ABuilder{} +} diff --git a/go/test/fixedbugs/issue34503.dir/a.go b/go/test/fixedbugs/issue34503.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..2c149135ad6d4bffb5116a2d27c90489d7b1e056 --- /dev/null +++ b/go/test/fixedbugs/issue34503.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import "unsafe" + +type HookFunc func(x uint64) + +var HookV unsafe.Pointer + +func Hook(x uint64) { + (*(*HookFunc)(HookV))(x) +} diff --git a/go/test/fixedbugs/issue34503.dir/b.go b/go/test/fixedbugs/issue34503.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..7ea02511b06e78d721781297352e6dfc99fd120a --- /dev/null +++ b/go/test/fixedbugs/issue34503.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func Bfunc() { + a.Hook(101) +} diff --git a/go/test/fixedbugs/issue34577.dir/a.go b/go/test/fixedbugs/issue34577.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..b6af5556b3c832d874471ff8261239cee65438e3 --- /dev/null +++ b/go/test/fixedbugs/issue34577.dir/a.go @@ -0,0 +1,27 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A struct { + x int +} + +type AI interface { + bar() +} + +type AC int + +func (ab AC) bar() { +} + +const ( + ACC = AC(101) +) + +//go:noinline +func W(a A, k, v interface{}) A { + return A{3} +} diff --git a/go/test/fixedbugs/issue34577.dir/b.go b/go/test/fixedbugs/issue34577.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..c61d7da78209709f7464924e49fa8b692dadc7bb --- /dev/null +++ b/go/test/fixedbugs/issue34577.dir/b.go @@ -0,0 +1,23 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type B struct { + s string +} + +func (b B) Func(x a.A) a.A { + return a.W(x, k, b) +} + +type ktype int + +const k ktype = 0 + +func Func2() a.AI { + return a.ACC +} diff --git a/go/test/fixedbugs/issue3552.dir/one.go b/go/test/fixedbugs/issue3552.dir/one.go new file mode 100644 index 0000000000000000000000000000000000000000..e594db7478bbf32af3fe9eef0232cdda23545d57 --- /dev/null +++ b/go/test/fixedbugs/issue3552.dir/one.go @@ -0,0 +1,28 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package one + +// Issue 3552 + +type T struct { int } + +func (t T) F() int { return t.int } + +type U struct { int int } + +func (u U) F() int { return u.int } + +type lint int + +type V struct { lint } + +func (v V) F() int { return int(v.lint) } + +type W struct { lint lint } + +func (w W) F() int { return int(w.lint) } + + + diff --git a/go/test/fixedbugs/issue3552.dir/two.go b/go/test/fixedbugs/issue3552.dir/two.go new file mode 100644 index 0000000000000000000000000000000000000000..2f330bfdf3b4bbe43bb9f2284ebd03913861ac88 --- /dev/null +++ b/go/test/fixedbugs/issue3552.dir/two.go @@ -0,0 +1,22 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Use the functions in one.go so that the inlined +// forms get type-checked. + +package two + +import "./one" + +func use() { + var t one.T + var u one.U + var v one.V + var w one.W + + _ = t.F() + _ = u.F() + _ = v.F() + _ = w.F() +} diff --git a/go/test/fixedbugs/issue35586.dir/a.go b/go/test/fixedbugs/issue35586.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..f509b25473bfc9a7b324143f2d9e1983bda123ec --- /dev/null +++ b/go/test/fixedbugs/issue35586.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func D(_ string, _ int) (uint64, string) { + return 101, "bad" +} diff --git a/go/test/fixedbugs/issue35586.dir/b.go b/go/test/fixedbugs/issue35586.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e0abb99fd41cb91d10666e9e663107e92435519b --- /dev/null +++ b/go/test/fixedbugs/issue35586.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F(addr string) (uint64, string) { + return a.D(addr, 32) +} diff --git a/go/test/fixedbugs/issue35739.dir/a.go b/go/test/fixedbugs/issue35739.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..b79503e99615116d64831b2804df6e84c8aad85b --- /dev/null +++ b/go/test/fixedbugs/issue35739.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type myError string + +func (e myError) Error() string { return string(e) } + +const myErrorVal myError = "error" + +func IsMyError(err error) bool { + return err == error(myErrorVal) +} diff --git a/go/test/fixedbugs/issue35739.dir/b.go b/go/test/fixedbugs/issue35739.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..8d22aac8d6b058b186e04da35aa7ae1f259b70c8 --- /dev/null +++ b/go/test/fixedbugs/issue35739.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F(err error) bool { + return a.IsMyError(err) +} diff --git a/go/test/fixedbugs/issue36085.dir/a.go b/go/test/fixedbugs/issue36085.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..07cabcd2cceeaa299c1cc3729464e20544a9d849 --- /dev/null +++ b/go/test/fixedbugs/issue36085.dir/a.go @@ -0,0 +1,3 @@ +package a + +type W = map[int32]interface{} diff --git a/go/test/fixedbugs/issue36085.dir/b.go b/go/test/fixedbugs/issue36085.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..0ebfe9fb6107d24e32c7c04d45df85c29901499c --- /dev/null +++ b/go/test/fixedbugs/issue36085.dir/b.go @@ -0,0 +1,8 @@ +package main + +import "./a" + +var w a.W +var X interface{} = &w + +func main() {} diff --git a/go/test/fixedbugs/issue37513.dir/main.go b/go/test/fixedbugs/issue37513.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..75106521b6b9e995a624e4fbc2a831e325c5b849 --- /dev/null +++ b/go/test/fixedbugs/issue37513.dir/main.go @@ -0,0 +1,27 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "bytes" + "fmt" + "os" + "os/exec" +) + +func main() { + if len(os.Args) > 1 { + // Generate a SIGILL. + sigill() + return + } + // Run ourselves with an extra argument. That process should SIGILL. + out, _ := exec.Command(os.Args[0], "foo").CombinedOutput() + want := "instruction bytes: 0xf 0xb 0xc3" + if !bytes.Contains(out, []byte(want)) { + fmt.Printf("got:\n%s\nwant:\n%s\n", string(out), want) + } +} +func sigill() diff --git a/go/test/fixedbugs/issue37513.dir/sigill_amd64.s b/go/test/fixedbugs/issue37513.dir/sigill_amd64.s new file mode 100644 index 0000000000000000000000000000000000000000..43260c21aed64afaf9c137bd1ae3ed23c15181ba --- /dev/null +++ b/go/test/fixedbugs/issue37513.dir/sigill_amd64.s @@ -0,0 +1,7 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +TEXT ·sigill(SB),0,$0-0 + UD2 // generates a SIGILL + RET diff --git a/go/test/fixedbugs/issue37837.dir/a.go b/go/test/fixedbugs/issue37837.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..49d830ffbc7c66feae7b65904347d30e6607ea52 --- /dev/null +++ b/go/test/fixedbugs/issue37837.dir/a.go @@ -0,0 +1,33 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F(i interface{}) int { // ERROR "can inline F" "i does not escape" + switch i.(type) { + case nil: + return 0 + case int: + return 1 + case float64: + return 2 + default: + return 3 + } +} + +func G(i interface{}) interface{} { // ERROR "can inline G" "leaking param: i" + switch i := i.(type) { + case nil: // ERROR "moved to heap: i" + return &i + case int: // ERROR "moved to heap: i" + return &i + case float64: // ERROR "moved to heap: i" + return &i + case string, []byte: // ERROR "moved to heap: i" + return &i + default: // ERROR "moved to heap: i" + return &i + } +} diff --git a/go/test/fixedbugs/issue37837.dir/b.go b/go/test/fixedbugs/issue37837.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..461f5c7a553e8fdc6e8ee90ccd0ab357f79cab46 --- /dev/null +++ b/go/test/fixedbugs/issue37837.dir/b.go @@ -0,0 +1,32 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + // Test that inlined type switches without short variable + // declarations work correctly. + check(0, a.F(nil)) // ERROR "inlining call to a.F" + check(1, a.F(0)) // ERROR "inlining call to a.F" "does not escape" + check(2, a.F(0.0)) // ERROR "inlining call to a.F" "does not escape" + check(3, a.F("")) // ERROR "inlining call to a.F" "does not escape" + + // Test that inlined type switches with short variable + // declarations work correctly. + _ = a.G(nil).(*interface{}) // ERROR "inlining call to a.G" + _ = a.G(1).(*int) // ERROR "inlining call to a.G" "does not escape" + _ = a.G(2.0).(*float64) // ERROR "inlining call to a.G" "does not escape" + _ = (*a.G("").(*interface{})).(string) // ERROR "inlining call to a.G" "does not escape" + _ = (*a.G(([]byte)(nil)).(*interface{})).([]byte) // ERROR "inlining call to a.G" "does not escape" + _ = (*a.G(true).(*interface{})).(bool) // ERROR "inlining call to a.G" "does not escape" +} + +//go:noinline +func check(want, got int) { + if want != got { + println("want", want, "but got", got) + } +} diff --git a/go/test/fixedbugs/issue40252.dir/a.go b/go/test/fixedbugs/issue40252.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..5519e9331aa0c6103444bfe8f30d03df07e5a134 --- /dev/null +++ b/go/test/fixedbugs/issue40252.dir/a.go @@ -0,0 +1,14 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I interface { + Func() +} + +func Call() { + f := I.Func + f(nil) +} diff --git a/go/test/fixedbugs/issue40252.dir/main.go b/go/test/fixedbugs/issue40252.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..93f5b706242ef723f7362d7eea2b9913ba6d25b6 --- /dev/null +++ b/go/test/fixedbugs/issue40252.dir/main.go @@ -0,0 +1,16 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + defer func() { + if recover() == nil { + panic("expected nil pointer dereference") + } + }() + a.Call() +} diff --git a/go/test/fixedbugs/issue42284.dir/a.go b/go/test/fixedbugs/issue42284.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e55f190d7ee5710732a04f2597915b6cb887ed11 --- /dev/null +++ b/go/test/fixedbugs/issue42284.dir/a.go @@ -0,0 +1,29 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I interface{ M() } +type T int + +func (T) M() {} // ERROR "can inline T.M" + +func E() I { // ERROR "can inline E" + return T(0) // ERROR "T\(0\) escapes to heap" +} + +func F(i I) I { // ERROR "can inline F" "leaking param: i to result ~r0 level=0" + i = nil + return i +} + +func g() { + h := E() // ERROR "inlining call to E" "T\(0\) does not escape" + h.M() // ERROR "devirtualizing h.M to T" "inlining call to T.M" + + i := F(T(0)) // ERROR "inlining call to F" "T\(0\) does not escape" + + // It is fine that we devirtualize here, as we add an additional nilcheck. + i.M() // ERROR "devirtualizing i.M to T" "inlining call to T.M" +} diff --git a/go/test/fixedbugs/issue42284.dir/b.go b/go/test/fixedbugs/issue42284.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..4a0b7cea102e8801eb36ce76ea08b4ed35b61ffb --- /dev/null +++ b/go/test/fixedbugs/issue42284.dir/b.go @@ -0,0 +1,17 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func g() { + h := a.E() // ERROR "inlining call to a.E" "T\(0\) does not escape" + h.M() // ERROR "devirtualizing h.M to a.T" "inlining call to a.T.M" + + i := a.F(a.T(0)) // ERROR "inlining call to a.F" "a.T\(0\) does not escape" + + // It is fine that we devirtualize here, as we add an additional nilcheck. + i.M() // ERROR "devirtualizing i.M to a.T" "inlining call to a.T.M" +} diff --git a/go/test/fixedbugs/issue42401.dir/a.go b/go/test/fixedbugs/issue42401.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..75f8e7f91fc35f6efb964a00874d3216489c8068 --- /dev/null +++ b/go/test/fixedbugs/issue42401.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var s string + +func init() { s = "a" } + +func Get() string { return s } diff --git a/go/test/fixedbugs/issue42401.dir/b.go b/go/test/fixedbugs/issue42401.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..fc675d82301881e94934c3b72f47ede071844f57 --- /dev/null +++ b/go/test/fixedbugs/issue42401.dir/b.go @@ -0,0 +1,25 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + _ "unsafe" + + "./a" +) + +//go:linkname s test/a.s +var s string + +func main() { + if a.Get() != "a" { + panic("FAIL") + } + + s = "b" + if a.Get() != "b" { + panic("FAIL") + } +} diff --git a/go/test/fixedbugs/issue4252.dir/a.go b/go/test/fixedbugs/issue4252.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..a587e28da7959a79a7da2333873548e916b5de7e --- /dev/null +++ b/go/test/fixedbugs/issue4252.dir/a.go @@ -0,0 +1,35 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// A package that redeclares common builtin names. +package a + +var true = 0 == 1 +var false = 0 == 0 +var nil = 1 + +const append = 42 + +type error bool +type int interface{} + +func len(interface{}) int32 { return 42 } + +func Test() { + var array [append]int + if true { + panic("unexpected builtin true instead of redeclared one") + } + if !false { + panic("unexpected builtin false instead of redeclared one") + } + if len(array) != 42 { + println(len(array)) + panic("unexpected call of builtin len") + } +} + +func InlinedFakeTrue() error { return error(true) } +func InlinedFakeFalse() error { return error(false) } +func InlinedFakeNil() int { return nil } diff --git a/go/test/fixedbugs/issue4252.dir/main.go b/go/test/fixedbugs/issue4252.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..02d9836e98da207fc2e35bdbed3658193fd6ef9d --- /dev/null +++ b/go/test/fixedbugs/issue4252.dir/main.go @@ -0,0 +1,20 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + if a.InlinedFakeTrue() { + panic("returned true was the real one") + } + if !a.InlinedFakeFalse() { + panic("returned false was the real one") + } + if a.InlinedFakeNil() == nil { + panic("returned nil was the real one") + } + a.Test() +} diff --git a/go/test/fixedbugs/issue43164.dir/a.go b/go/test/fixedbugs/issue43164.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..fa10e85061225433bd28ca229be1bd50924cfd85 --- /dev/null +++ b/go/test/fixedbugs/issue43164.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import . "strings" + +var _ = Index // use strings + +type t struct{ Index int } + +var _ = t{Index: 0} diff --git a/go/test/fixedbugs/issue43164.dir/b.go b/go/test/fixedbugs/issue43164.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b025927a059a8eb39e9f53ef1314d1e93b9f623d --- /dev/null +++ b/go/test/fixedbugs/issue43164.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import . "bytes" + +var _ = Index // use bytes + +var _ = t{Index: 0} diff --git a/go/test/fixedbugs/issue4326.dir/p1.go b/go/test/fixedbugs/issue4326.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..ab214befb4b82845b816c657e0581b416e0cb931 --- /dev/null +++ b/go/test/fixedbugs/issue4326.dir/p1.go @@ -0,0 +1,12 @@ +package p1 + +type O map[string]map[string]string + +func (opts O) RemoveOption(sect, opt string) bool { + if _, ok := opts[sect]; !ok { + return false + } + _, ok := opts[sect][opt] + delete(opts[sect], opt) + return ok +} diff --git a/go/test/fixedbugs/issue4326.dir/p2.go b/go/test/fixedbugs/issue4326.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..8e86266dd8d4adb2f8aec9218b26c7595cfcabec --- /dev/null +++ b/go/test/fixedbugs/issue4326.dir/p2.go @@ -0,0 +1,5 @@ +package p2 + +import "./p1" + +func NewO() p1.O { return nil } diff --git a/go/test/fixedbugs/issue4326.dir/q1.go b/go/test/fixedbugs/issue4326.dir/q1.go new file mode 100644 index 0000000000000000000000000000000000000000..f118eb09252a48c51942b1f602d637620afd1a12 --- /dev/null +++ b/go/test/fixedbugs/issue4326.dir/q1.go @@ -0,0 +1,8 @@ +package q1 + +func Deref(typ interface{}) interface{} { + if typ, ok := typ.(*int); ok { + return *typ + } + return typ +} diff --git a/go/test/fixedbugs/issue4326.dir/q2.go b/go/test/fixedbugs/issue4326.dir/q2.go new file mode 100644 index 0000000000000000000000000000000000000000..075e2b21e7a438ca7a7eccfedf1ad06e0275c1d8 --- /dev/null +++ b/go/test/fixedbugs/issue4326.dir/q2.go @@ -0,0 +1,11 @@ +package main + +import "./q1" + +func main() { + x := 1 + y := q1.Deref(&x) + if y != 1 { + panic("y != 1") + } +} diff --git a/go/test/fixedbugs/issue4326.dir/z.go b/go/test/fixedbugs/issue4326.dir/z.go new file mode 100644 index 0000000000000000000000000000000000000000..9b222e8b40276754272f39fadaf75b0f0d30d77b --- /dev/null +++ b/go/test/fixedbugs/issue4326.dir/z.go @@ -0,0 +1,7 @@ +package z + +import "./p2" + +func main() { + p2.NewO().RemoveOption("hello", "world") +} diff --git a/go/test/fixedbugs/issue43479.dir/a.go b/go/test/fixedbugs/issue43479.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..ed3e6a5d9b67ee317f5c52352599c787983c274f --- /dev/null +++ b/go/test/fixedbugs/issue43479.dir/a.go @@ -0,0 +1,27 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Here struct{ stuff int } +type Info struct{ Dir string } + +func New() Here { return Here{} } +func (h Here) Dir(p string) (Info, error) + +type I interface{ M(x string) } + +type T = struct { + Here + I +} + +var X T + +var A = (*T).Dir +var B = T.Dir +var C = X.Dir +var D = (*T).M +var E = T.M +var F = X.M diff --git a/go/test/fixedbugs/issue43479.dir/b.go b/go/test/fixedbugs/issue43479.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..02d16909cc527cc8f166d2b0086b16804553ef52 --- /dev/null +++ b/go/test/fixedbugs/issue43479.dir/b.go @@ -0,0 +1,38 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var Here = a.New() +var Dir = Here.Dir + +type T = struct { + a.Here + a.I +} + +var X T + +// Test exporting the type of method values for anonymous structs with +// promoted methods. +var A = a.A +var B = a.B +var C = a.C +var D = a.D +var E = a.E +var F = a.F +var G = (*a.T).Dir +var H = a.T.Dir +var I = a.X.Dir +var J = (*a.T).M +var K = a.T.M +var L = a.X.M +var M = (*T).Dir +var N = T.Dir +var O = X.Dir +var P = (*T).M +var Q = T.M +var R = X.M diff --git a/go/test/fixedbugs/issue43551.dir/a.go b/go/test/fixedbugs/issue43551.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..d890dd0c651caa1cdecd073de50512fd09b72575 --- /dev/null +++ b/go/test/fixedbugs/issue43551.dir/a.go @@ -0,0 +1,13 @@ +package a + +type S struct { + a Key +} + +func (s S) A() Key { + return s.a +} + +type Key struct { + key int64 +} diff --git a/go/test/fixedbugs/issue43551.dir/b.go b/go/test/fixedbugs/issue43551.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..ba062bf14cf12b9d613c224ea4cb636f6c7196d8 --- /dev/null +++ b/go/test/fixedbugs/issue43551.dir/b.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type S a.S +type Key a.Key + +func (s S) A() Key { + return Key(a.S(s).A()) +} diff --git a/go/test/fixedbugs/issue43633.dir/a.go b/go/test/fixedbugs/issue43633.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..946a37e87ef1a64d31943293e1d41f8e9b550f36 --- /dev/null +++ b/go/test/fixedbugs/issue43633.dir/a.go @@ -0,0 +1,28 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() bool { + { + x := false + _ = x + } + if false { + _ = func(x bool) {} + } + x := true + return x +} + +func G() func() bool { + x := true + return func() bool { + { + x := false + _ = x + } + return x + } +} diff --git a/go/test/fixedbugs/issue43633.dir/main.go b/go/test/fixedbugs/issue43633.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..320e00013c3130e69fb271e859cc9cbb37e93dad --- /dev/null +++ b/go/test/fixedbugs/issue43633.dir/main.go @@ -0,0 +1,18 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +var g = a.G() + +func main() { + if !a.F() { + panic("FAIL") + } + if !g() { + panic("FAIL") + } +} diff --git a/go/test/fixedbugs/issue4370.dir/p1.go b/go/test/fixedbugs/issue4370.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..d010e936534aebef4434f3e6a5393a1a97af4b7e --- /dev/null +++ b/go/test/fixedbugs/issue4370.dir/p1.go @@ -0,0 +1,20 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +type Magic int + +type T struct { + x interface{} +} + +func (t *T) M() bool { + _, ok := t.x.(Magic) + return ok +} + +func F(t *T) { + println(t) +} diff --git a/go/test/fixedbugs/issue4370.dir/p2.go b/go/test/fixedbugs/issue4370.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..0d3e23625ec245a215f87594218925f25fcb8f19 --- /dev/null +++ b/go/test/fixedbugs/issue4370.dir/p2.go @@ -0,0 +1,16 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p2 + +import "./p1" + +type T struct { + p1.T +} + +func F() { + var t T + p1.F(&t.T) +} diff --git a/go/test/fixedbugs/issue4370.dir/p3.go b/go/test/fixedbugs/issue4370.dir/p3.go new file mode 100644 index 0000000000000000000000000000000000000000..c275c6e222dd8b1b3f161b8898fcbcbec90abf98 --- /dev/null +++ b/go/test/fixedbugs/issue4370.dir/p3.go @@ -0,0 +1,13 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p3 + +import "./p2" + +func F() { + p2.F() + var t p2.T + println(t.T.M()) +} diff --git a/go/test/fixedbugs/issue43962.dir/a.go b/go/test/fixedbugs/issue43962.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..168b2063b4872373b43dfbc27e30757fc7af25d2 --- /dev/null +++ b/go/test/fixedbugs/issue43962.dir/a.go @@ -0,0 +1,5 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package init diff --git a/go/test/fixedbugs/issue43962.dir/b.go b/go/test/fixedbugs/issue43962.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..f55fea11c19347c42645532e7bc6e7afddd87b4d --- /dev/null +++ b/go/test/fixedbugs/issue43962.dir/b.go @@ -0,0 +1,7 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" // ERROR "cannot import package as init" diff --git a/go/test/fixedbugs/issue44325.dir/a.go b/go/test/fixedbugs/issue44325.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..5a22b455b7ea8559ce4a8ab737c1b8b3707a3ad3 --- /dev/null +++ b/go/test/fixedbugs/issue44325.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package a + +func FM() func() { + return func() { + _ = func() int { + return 0 + } + } +} diff --git a/go/test/fixedbugs/issue44325.dir/b.go b/go/test/fixedbugs/issue44325.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..c4d77e311a9a6e3bd7fcffbf296191264152e08d --- /dev/null +++ b/go/test/fixedbugs/issue44325.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package b + +import ( + "./a" +) + +func F() { + a.FM() +} diff --git a/go/test/fixedbugs/issue44330.dir/a.go b/go/test/fixedbugs/issue44330.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..9d3ab9fe80e0870a85984ddd7db74176c8fded8c --- /dev/null +++ b/go/test/fixedbugs/issue44330.dir/a.go @@ -0,0 +1,21 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package a + +type Table struct { + ColumnSeparator bool + RowSeparator bool + + // ColumnResizer is called on each Draw. Can be used for custom column sizing. + ColumnResizer func() +} + +func NewTable() *Table { + return &Table{ + ColumnSeparator: true, + RowSeparator: true, + ColumnResizer: func() {}, + } +} diff --git a/go/test/fixedbugs/issue44330.dir/b.go b/go/test/fixedbugs/issue44330.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..1d5742421bdf9f78909e7f279229d7906afb237f --- /dev/null +++ b/go/test/fixedbugs/issue44330.dir/b.go @@ -0,0 +1,23 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package main + +import ( + "./a" +) + +type Term struct { + top *a.Table +} + +//go:noinline +func NewFred() *Term { + table := a.NewTable() + return &Term{top: table} +} + +func main() { + NewFred() +} diff --git a/go/test/fixedbugs/issue44335.dir/a.go b/go/test/fixedbugs/issue44335.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..2c9c2178135114fb9ef136359fe9e3bfd27b75d2 --- /dev/null +++ b/go/test/fixedbugs/issue44335.dir/a.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file + +package a + +type W struct { + M func(string) string +} + +func FM(m string) func(W) { + return func(pw W) { + pw.M = func(string) string { + return m + } + } +} diff --git a/go/test/fixedbugs/issue44335.dir/b.go b/go/test/fixedbugs/issue44335.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e72c2abc6a546b4b104e11cde25e8f06d4384df3 --- /dev/null +++ b/go/test/fixedbugs/issue44335.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package b + +import "./a" + +func F() { + a.FM("") +} diff --git a/go/test/fixedbugs/issue44355.dir/a.go b/go/test/fixedbugs/issue44355.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..0f63c6fd983862d6409462cf1ecf23cae9f8f906 --- /dev/null +++ b/go/test/fixedbugs/issue44355.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package a + +func F() (_ *int) { return nil } diff --git a/go/test/fixedbugs/issue44355.dir/b.go b/go/test/fixedbugs/issue44355.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..09d5bde887a56773bc8d45645ee800232411f66b --- /dev/null +++ b/go/test/fixedbugs/issue44355.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package b + +import "./a" + +var _ = a.F() diff --git a/go/test/fixedbugs/issue44370.dir/a.go b/go/test/fixedbugs/issue44370.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..c5bf1bcbc72e77975720a44b70e30d71f673dc42 --- /dev/null +++ b/go/test/fixedbugs/issue44370.dir/a.go @@ -0,0 +1,20 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package a + +// A StoppableWaitGroup waits for a collection of goroutines to finish. +type StoppableWaitGroup struct { + // i is the internal counter which can store tolerate negative values + // as opposed the golang's library WaitGroup. + i *int64 +} + +// NewStoppableWaitGroup returns a new StoppableWaitGroup. When the 'Stop' is +// executed, following 'Add()' calls won't have any effect. +func NewStoppableWaitGroup() *StoppableWaitGroup { + return &StoppableWaitGroup{ + i: func() *int64 { i := int64(0); return &i }(), + } +} diff --git a/go/test/fixedbugs/issue44370.dir/b.go b/go/test/fixedbugs/issue44370.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..f0e0b4e55fd89cfa5c53aaf1a4e84c7e05272ed7 --- /dev/null +++ b/go/test/fixedbugs/issue44370.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in +// the LICENSE file. + +package b + +import "./a" + +func JoinClusterServices() { + _ = a.NewStoppableWaitGroup() +} diff --git a/go/test/fixedbugs/issue44732.dir/bar/bar.go b/go/test/fixedbugs/issue44732.dir/bar/bar.go new file mode 100644 index 0000000000000000000000000000000000000000..fc141616100e09767db3604d18dc82ba24d8370c --- /dev/null +++ b/go/test/fixedbugs/issue44732.dir/bar/bar.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bar + +import "issue44732.dir/foo" + +type Bar struct { + Foo *foo.Foo +} diff --git a/go/test/fixedbugs/issue44732.dir/foo/foo.go b/go/test/fixedbugs/issue44732.dir/foo/foo.go new file mode 100644 index 0000000000000000000000000000000000000000..c8afb0e880e5b467ee42d25232f6d8488f9b78e2 --- /dev/null +++ b/go/test/fixedbugs/issue44732.dir/foo/foo.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package foo + +type Foo struct { + updatecb func() +} + +func NewFoo() *Foo { + return &Foo{updatecb: nil} +} diff --git a/go/test/fixedbugs/issue44732.dir/main.go b/go/test/fixedbugs/issue44732.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..21208ecdd93d888284f0470fbc7cd9ad6b45c2e9 --- /dev/null +++ b/go/test/fixedbugs/issue44732.dir/main.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "issue44732.dir/bar" + "issue44732.dir/foo" +) + +func main() { + _ = bar.Bar{} + _ = foo.NewFoo() +} diff --git a/go/test/fixedbugs/issue4510.dir/f1.go b/go/test/fixedbugs/issue4510.dir/f1.go new file mode 100644 index 0000000000000000000000000000000000000000..1217106fca4db57046225ec3b0e982a74460c656 --- /dev/null +++ b/go/test/fixedbugs/issue4510.dir/f1.go @@ -0,0 +1,9 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "fmt" // GCCGO_ERROR "fmt redeclared|imported" + +var _ = fmt.Printf diff --git a/go/test/fixedbugs/issue4510.dir/f2.go b/go/test/fixedbugs/issue4510.dir/f2.go new file mode 100644 index 0000000000000000000000000000000000000000..1a67153771fa64fc8d11c54ed66999a0d7c65853 --- /dev/null +++ b/go/test/fixedbugs/issue4510.dir/f2.go @@ -0,0 +1,7 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func fmt() {} // GC_ERROR "fmt already declared through import of package" diff --git a/go/test/fixedbugs/issue45503.dir/a.go b/go/test/fixedbugs/issue45503.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..b45835bd85f60adf5406824655145f601e4a26e2 --- /dev/null +++ b/go/test/fixedbugs/issue45503.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type S struct{} + +func (s *S) M() { + s.m((*S).N) +} + +func (s *S) N() {} + +func (s *S) m(func(*S)) {} diff --git a/go/test/fixedbugs/issue45503.dir/b.go b/go/test/fixedbugs/issue45503.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..530c394eaf9d73225aae163a6bf7294e67d8cbb7 --- /dev/null +++ b/go/test/fixedbugs/issue45503.dir/b.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() { + s := a.S{} + s.M() +} diff --git a/go/test/fixedbugs/issue4590.dir/pkg1.go b/go/test/fixedbugs/issue4590.dir/pkg1.go new file mode 100644 index 0000000000000000000000000000000000000000..96cac0a5c1c0d8851ff2a73629bca222d2ea482a --- /dev/null +++ b/go/test/fixedbugs/issue4590.dir/pkg1.go @@ -0,0 +1,26 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkg1 + +type A interface { + Write() error +} + +type B interface { + Hello() + world() +} + +type C struct{} + +func (c C) Write() error { return nil } + +var T = struct{ A }{nil} +var U = struct{ B }{nil} +var V A = struct{ *C }{nil} +var W = interface { + Write() error + Hello() +}(nil) diff --git a/go/test/fixedbugs/issue4590.dir/pkg2.go b/go/test/fixedbugs/issue4590.dir/pkg2.go new file mode 100644 index 0000000000000000000000000000000000000000..98bc2a52fb96da1c2ad93177d86e50cd2681d323 --- /dev/null +++ b/go/test/fixedbugs/issue4590.dir/pkg2.go @@ -0,0 +1,15 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkg2 + +import "./pkg1" + +var T = struct{ pkg1.A }{nil} +var U = struct{ pkg1.B }{nil} +var V pkg1.A = struct{ *pkg1.C }{nil} +var W = interface { + Write() error + Hello() +}(nil) diff --git a/go/test/fixedbugs/issue4590.dir/prog.go b/go/test/fixedbugs/issue4590.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..32055b28e246add2113231eff5df77f9a8ade611 --- /dev/null +++ b/go/test/fixedbugs/issue4590.dir/prog.go @@ -0,0 +1,25 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./pkg1" + "./pkg2" +) + +func main() { + if pkg1.T != pkg2.T { + panic("pkg1.T != pkg2.T") + } + if pkg1.U != pkg2.U { + panic("pkg1.U != pkg2.U") + } + if pkg1.V != pkg2.V { + panic("pkg1.V != pkg2.V") + } + if pkg1.W != pkg2.W { + panic("pkg1.W != pkg2.W") + } +} diff --git a/go/test/fixedbugs/issue46653.dir/bad/bad.go b/go/test/fixedbugs/issue46653.dir/bad/bad.go new file mode 100644 index 0000000000000000000000000000000000000000..c1611b8347a3247deeb7f722920cf9e9e4049e7d --- /dev/null +++ b/go/test/fixedbugs/issue46653.dir/bad/bad.go @@ -0,0 +1,64 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func Bad() { + m := make(map[int64]A) + a := m[0] + if len(a.B.C1.D2.E2.F1) != 0 || + len(a.B.C1.D2.E2.F2) != 0 || + len(a.B.C1.D2.E2.F3) != 0 || + len(a.B.C1.D2.E2.F4) != 0 || + len(a.B.C1.D2.E2.F5) != 0 || + len(a.B.C1.D2.E2.F6) != 0 || + len(a.B.C1.D2.E2.F7) != 0 || + len(a.B.C1.D2.E2.F8) != 0 || + len(a.B.C1.D2.E2.F9) != 0 || + len(a.B.C1.D2.E2.F10) != 0 || + len(a.B.C1.D2.E2.F11) != 0 || + len(a.B.C1.D2.E2.F16) != 0 { + panic("bad") + } +} + +type A struct { + B +} + +type B struct { + C1 C + C2 C +} + +type C struct { + D1 D + D2 D +} + +type D struct { + E1 E + E2 E + E3 E + E4 E +} + +type E struct { + F1 string + F2 string + F3 string + F4 string + F5 string + F6 string + F7 string + F8 string + F9 string + F10 string + F11 string + F12 string + F13 string + F14 string + F15 string + F16 string +} diff --git a/go/test/fixedbugs/issue46653.dir/main.go b/go/test/fixedbugs/issue46653.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e2a96e54ec59949c82935946284613ffa62b669a --- /dev/null +++ b/go/test/fixedbugs/issue46653.dir/main.go @@ -0,0 +1,27 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + bad "issue46653.dir/bad" +) + +func main() { + bad.Bad() +} + +func neverCalled() L { + m := make(map[string]L) + return m[""] +} + +type L struct { + A Data + B Data +} + +type Data struct { + F1 [22][]string +} diff --git a/go/test/fixedbugs/issue47068.dir/a.go b/go/test/fixedbugs/issue47068.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..30a51c1edb24d10f163675426862f67060d6eb31 --- /dev/null +++ b/go/test/fixedbugs/issue47068.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func A() { + var m map[int]int = map[int]int{ + 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, + 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, + 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0} + if len(m) != 30 { + panic("unexpected map length") + } +} diff --git a/go/test/fixedbugs/issue47068.dir/b.go b/go/test/fixedbugs/issue47068.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..d341a4a395005cb9b5411ece09004ee9c2571118 --- /dev/null +++ b/go/test/fixedbugs/issue47068.dir/b.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "reflect" + +func B() { + t1 := reflect.TypeOf([30]int{}) + t2 := reflect.TypeOf(new([30]int)).Elem() + if t1 != t2 { + panic("[30]int types do not match") + } +} diff --git a/go/test/fixedbugs/issue47068.dir/main.go b/go/test/fixedbugs/issue47068.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..411e7db10382dcd6b3afe57b815269edf51a0e3b --- /dev/null +++ b/go/test/fixedbugs/issue47068.dir/main.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "./b" +) + +func main() { + a.A() + b.B() +} diff --git a/go/test/fixedbugs/issue47087.dir/a.go b/go/test/fixedbugs/issue47087.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..6093092aceea7a3838ba9846cf2a65cc60db9d38 --- /dev/null +++ b/go/test/fixedbugs/issue47087.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() interface{} { return struct{ _ []int }{} } + +var X = F() diff --git a/go/test/fixedbugs/issue47087.dir/b.go b/go/test/fixedbugs/issue47087.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..8f96d25a12bf2c26cca35cb036a482fb05f615ff --- /dev/null +++ b/go/test/fixedbugs/issue47087.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +func F() interface{} { return struct{ _ []int }{} } + +var X = F() diff --git a/go/test/fixedbugs/issue47087.dir/main.go b/go/test/fixedbugs/issue47087.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..16c1cc616d09bb16cf566621c71c8586c59f64e2 --- /dev/null +++ b/go/test/fixedbugs/issue47087.dir/main.go @@ -0,0 +1,19 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "./b" +) + +func main() { + if a.F() == b.F() { + panic("FAIL") + } + if a.X == b.X { + panic("FAIL") + } +} diff --git a/go/test/fixedbugs/issue47131.dir/a.go b/go/test/fixedbugs/issue47131.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..6e798d1d0c8e2dd7370416750e2fc5764346a9e9 --- /dev/null +++ b/go/test/fixedbugs/issue47131.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type MyInt int + +type MyIntAlias = MyInt + +func (mia *MyIntAlias) Get() int { + return int(*mia) +} diff --git a/go/test/fixedbugs/issue47131.dir/b.go b/go/test/fixedbugs/issue47131.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..c658127ca9d53c2495f12690437e095401f9a4c2 --- /dev/null +++ b/go/test/fixedbugs/issue47131.dir/b.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F2() int { + var mia a.MyIntAlias + return mia.Get() +} diff --git a/go/test/fixedbugs/issue47185.dir/bad/bad.go b/go/test/fixedbugs/issue47185.dir/bad/bad.go new file mode 100644 index 0000000000000000000000000000000000000000..1aa4fbb909522ae1409f0895e3f04c58a47d73ee --- /dev/null +++ b/go/test/fixedbugs/issue47185.dir/bad/bad.go @@ -0,0 +1,72 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +// Note that the use of CGO here is solely to trigger external +// linking, since that is required to trigger that bad behavior +// in this bug. + +// #include +import "C" + +func Bad() { + m := make(map[int64]A) + a := m[0] + if len(a.B.C1.D2.E2.F1) != 0 || + len(a.B.C1.D2.E2.F2) != 0 || + len(a.B.C1.D2.E2.F3) != 0 || + len(a.B.C1.D2.E2.F4) != 0 || + len(a.B.C1.D2.E2.F5) != 0 || + len(a.B.C1.D2.E2.F6) != 0 || + len(a.B.C1.D2.E2.F7) != 0 || + len(a.B.C1.D2.E2.F8) != 0 || + len(a.B.C1.D2.E2.F9) != 0 || + len(a.B.C1.D2.E2.F10) != 0 || + len(a.B.C1.D2.E2.F11) != 0 || + len(a.B.C1.D2.E2.F16) != 0 { + panic("bad") + } + C.malloc(100) +} + +type A struct { + B +} + +type B struct { + C1 C + C2 C +} + +type C struct { + D1 D + D2 D +} + +type D struct { + E1 E + E2 E + E3 E + E4 E +} + +type E struct { + F1 string + F2 string + F3 string + F4 string + F5 string + F6 string + F7 string + F8 string + F9 string + F10 string + F11 string + F12 string + F13 string + F14 string + F15 string + F16 string +} diff --git a/go/test/fixedbugs/issue47185.dir/main.go b/go/test/fixedbugs/issue47185.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..7b46e55d8b566349cf5a9315bbd19dcd84f5bee7 --- /dev/null +++ b/go/test/fixedbugs/issue47185.dir/main.go @@ -0,0 +1,28 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + bad "issue47185.dir/bad" +) + +func main() { + another() + bad.Bad() +} + +func another() L { + m := make(map[string]L) + return m[""] +} + +type L struct { + A Data + B Data +} + +type Data struct { + F1 [22][]string +} diff --git a/go/test/fixedbugs/issue47201.dir/a.go b/go/test/fixedbugs/issue47201.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..54b70790926cd3a2e80747c5fa6607465b3035c0 --- /dev/null +++ b/go/test/fixedbugs/issue47201.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + . "fmt" +) + +func test() { + Println("foo") +} diff --git a/go/test/fixedbugs/issue47201.dir/b.go b/go/test/fixedbugs/issue47201.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..ae3ff3f2b8143d280da4958a17a5a21852ffb978 --- /dev/null +++ b/go/test/fixedbugs/issue47201.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +func Println() {} // ERROR "Println redeclared in this block|Println already declared" + +func main() {} diff --git a/go/test/fixedbugs/issue47317.dir/a.s b/go/test/fixedbugs/issue47317.dir/a.s new file mode 100644 index 0000000000000000000000000000000000000000..b969ddb972c1d637b46992b2a77e72ffe1b807e9 --- /dev/null +++ b/go/test/fixedbugs/issue47317.dir/a.s @@ -0,0 +1,6 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +TEXT ·G(SB),4,$0 + RET diff --git a/go/test/fixedbugs/issue47317.dir/x.go b/go/test/fixedbugs/issue47317.dir/x.go new file mode 100644 index 0000000000000000000000000000000000000000..83b5542144d8cc6d57eadbec8027a4d093cab23b --- /dev/null +++ b/go/test/fixedbugs/issue47317.dir/x.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Issue 47317: ICE when calling ABI0 function via func value. + +package main + +func main() { F() } + +func F() interface{} { + g := G + g(1) + return G +} + +func G(x int) [2]int diff --git a/go/test/fixedbugs/issue48088.dir/a.go b/go/test/fixedbugs/issue48088.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..2bb879d557ed48e21eb64e0c62ee7c6c32e87655 --- /dev/null +++ b/go/test/fixedbugs/issue48088.dir/a.go @@ -0,0 +1,22 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T1 struct { + *T2 +} + +type T2 struct { +} + +func (t2 *T2) M() { +} + +func F() { + f(T1.M) +} + +func f(f func(T1)) { +} diff --git a/go/test/fixedbugs/issue48088.dir/b.go b/go/test/fixedbugs/issue48088.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..bdb1bb55c2d59ca94de267074fe80972b9bdda27 --- /dev/null +++ b/go/test/fixedbugs/issue48088.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() { + a.F() +} diff --git a/go/test/fixedbugs/issue4879.dir/a.go b/go/test/fixedbugs/issue4879.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..7ee7c4860475f1616d19f863266e2191fe705c38 --- /dev/null +++ b/go/test/fixedbugs/issue4879.dir/a.go @@ -0,0 +1,33 @@ +package a + +import ( + "unsafe" +) + +type Collection struct { + root unsafe.Pointer +} + +type nodeLoc struct{} + +type slice []int + +type maptype map[int]int + +func MakePrivateCollection() *Collection { + return &Collection{ + root: unsafe.Pointer(&nodeLoc{}), + } +} + +func MakePrivateCollection2() *Collection { + return &Collection{ + root: unsafe.Pointer(&slice{}), + } +} +func MakePrivateCollection3() *Collection { + return &Collection{ + root: unsafe.Pointer(&maptype{}), + } +} + diff --git a/go/test/fixedbugs/issue4879.dir/b.go b/go/test/fixedbugs/issue4879.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..d8fb5693db903e528eb8f5d9747753d19a999f66 --- /dev/null +++ b/go/test/fixedbugs/issue4879.dir/b.go @@ -0,0 +1,9 @@ +package b + +import "./a" + +func F() { + a.MakePrivateCollection() + a.MakePrivateCollection2() + a.MakePrivateCollection3() +} diff --git a/go/test/fixedbugs/issue49016.dir/a.go b/go/test/fixedbugs/issue49016.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..36639b73d424bfe1e34978a03963043efee0a8b9 --- /dev/null +++ b/go/test/fixedbugs/issue49016.dir/a.go @@ -0,0 +1,36 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Node interface { + Position() +} + +type noder struct{} + +func (noder) Position() {} + +type Scope map[int][]Node + +func (s Scope) M1() Scope { + if x, ok := s[0]; ok { + return x[0].(struct { + noder + Scope + }).Scope + } + return nil +} + +func (s Scope) M2() Scope { + if x, ok := s[0]; ok { + st, _ := x[0].(struct { + noder + Scope + }) + return st.Scope + } + return nil +} diff --git a/go/test/fixedbugs/issue49016.dir/b.go b/go/test/fixedbugs/issue49016.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..1dd63f87b6a3469f044f1ba6edf2d3f416d663c0 --- /dev/null +++ b/go/test/fixedbugs/issue49016.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +type t int + +func (t) m() {} + +func F1() interface{} { return struct{ t }{} } +func F2() interface{} { return *new(struct{ t }) } +func F3() interface{} { var x [1]struct{ t }; return x[0] } diff --git a/go/test/fixedbugs/issue49016.dir/c.go b/go/test/fixedbugs/issue49016.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..2cc6681b950aab3e74aa729e5cc50e72898f0bea --- /dev/null +++ b/go/test/fixedbugs/issue49016.dir/c.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import "./a" + +var _ = (&a.Scope{}).M1() diff --git a/go/test/fixedbugs/issue49016.dir/d.go b/go/test/fixedbugs/issue49016.dir/d.go new file mode 100644 index 0000000000000000000000000000000000000000..e933dc08e4bab921fc9ada3465eb15aa674f74f1 --- /dev/null +++ b/go/test/fixedbugs/issue49016.dir/d.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package d + +import "./a" + +var _ = (&a.Scope{}).M2() diff --git a/go/test/fixedbugs/issue49016.dir/e.go b/go/test/fixedbugs/issue49016.dir/e.go new file mode 100644 index 0000000000000000000000000000000000000000..5f43179c373b3d17b14121e52cc00c9567a46c67 --- /dev/null +++ b/go/test/fixedbugs/issue49016.dir/e.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package e + +import ( + "./b" +) + +var _ = b.F1() diff --git a/go/test/fixedbugs/issue49016.dir/f.go b/go/test/fixedbugs/issue49016.dir/f.go new file mode 100644 index 0000000000000000000000000000000000000000..2cd978eacef897771191633e84444bf6e3b37c11 --- /dev/null +++ b/go/test/fixedbugs/issue49016.dir/f.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package f + +import "./b" + +var _ = b.F2() diff --git a/go/test/fixedbugs/issue49016.dir/g.go b/go/test/fixedbugs/issue49016.dir/g.go new file mode 100644 index 0000000000000000000000000000000000000000..b90353fcff98862e8f0f99c1fe280ad4d052774d --- /dev/null +++ b/go/test/fixedbugs/issue49016.dir/g.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package g + +import "./b" + +var _ = b.F3() diff --git a/go/test/fixedbugs/issue49094.dir/a.go b/go/test/fixedbugs/issue49094.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..9ec0fd9f93e755de29da1aabc3a6d107c15f0535 --- /dev/null +++ b/go/test/fixedbugs/issue49094.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A struct{} + +func (a *A) f() bool { + return true +} diff --git a/go/test/fixedbugs/issue49094.dir/b.go b/go/test/fixedbugs/issue49094.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..f2361958ace346fa2709f19f5c500eead27fc0e5 --- /dev/null +++ b/go/test/fixedbugs/issue49094.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func M(r *a.A) string { + return "" +} diff --git a/go/test/fixedbugs/issue49094.dir/p.go b/go/test/fixedbugs/issue49094.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..581faf19ac778ccd55470b5994faa8cbb6d416f3 --- /dev/null +++ b/go/test/fixedbugs/issue49094.dir/p.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "./b" +) + +type S struct{} + +func (S) M() { + b.M(nil) +} diff --git a/go/test/fixedbugs/issue49143.dir/a.go b/go/test/fixedbugs/issue49143.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..5aefcd8780ca03a9481a1c5e3edd600dd462af9a --- /dev/null +++ b/go/test/fixedbugs/issue49143.dir/a.go @@ -0,0 +1,24 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import "sync" + +type Loader[K comparable, R any] struct { + batch *LoaderBatch[K, R] +} + +func (l *Loader[K, R]) Load() error { + l.batch.f() + return nil +} + +type LoaderBatch[K comparable, R any] struct { + once *sync.Once +} + +func (b *LoaderBatch[K, R]) f() { + b.once.Do(func() {}) +} diff --git a/go/test/fixedbugs/issue49143.dir/b.go b/go/test/fixedbugs/issue49143.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..48eecdbaaf53e899106b6016c33b76a97acdcd9f --- /dev/null +++ b/go/test/fixedbugs/issue49143.dir/b.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + + +type Loaders struct { + Loader *a.Loader[int, int] +} + +func NewLoaders() *Loaders { + return new(Loaders) +} diff --git a/go/test/fixedbugs/issue49143.dir/c.go b/go/test/fixedbugs/issue49143.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..89262e374aa1c44968f3ec83db55544475af693d --- /dev/null +++ b/go/test/fixedbugs/issue49143.dir/c.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import "./b" + +type Resolver struct{} + +type todoResolver struct{ *Resolver } + +func (r *todoResolver) F() { + b.NewLoaders().Loader.Load() +} diff --git a/go/test/fixedbugs/issue49143.dir/p.go b/go/test/fixedbugs/issue49143.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..f11d2f22eb371c0209c81f733e2258f3a24606e4 --- /dev/null +++ b/go/test/fixedbugs/issue49143.dir/p.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "./c" +) + +var _ = &c.Resolver{} diff --git a/go/test/fixedbugs/issue4932.dir/foo.go b/go/test/fixedbugs/issue4932.dir/foo.go new file mode 100644 index 0000000000000000000000000000000000000000..19b73a0e0384709495d09157370c4854e1fd910d --- /dev/null +++ b/go/test/fixedbugs/issue4932.dir/foo.go @@ -0,0 +1,7 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package foo + +type Op struct{} diff --git a/go/test/fixedbugs/issue4932.dir/state.go b/go/test/fixedbugs/issue4932.dir/state.go new file mode 100644 index 0000000000000000000000000000000000000000..c017b9649d474e3d827564ba9a9195f7c41dc61f --- /dev/null +++ b/go/test/fixedbugs/issue4932.dir/state.go @@ -0,0 +1,28 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package state + +import "./foo" + +func Public() { + var s Settings + s.op() +} + +type State struct{} + +func (s *State) x(*Settings) {} + +type Settings struct{} + +func (c *Settings) x() { + run([]foo.Op{{}}) +} + +func run([]foo.Op) {} + +func (s *Settings) op() foo.Op { + return foo.Op{} +} diff --git a/go/test/fixedbugs/issue4932.dir/state2.go b/go/test/fixedbugs/issue4932.dir/state2.go new file mode 100644 index 0000000000000000000000000000000000000000..50f75db2cea1006235c427a70b4c46c3ed8aecf6 --- /dev/null +++ b/go/test/fixedbugs/issue4932.dir/state2.go @@ -0,0 +1,9 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package state2 + +import "./state" + +type Foo *state.State diff --git a/go/test/fixedbugs/issue4964.dir/a.go b/go/test/fixedbugs/issue4964.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..216f352ca959e5fb4e30744b2e8839154665c89f --- /dev/null +++ b/go/test/fixedbugs/issue4964.dir/a.go @@ -0,0 +1,25 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var global, global2 *int + +type T struct { + Pointer *int +} + +//go:noinline +func Store(t *T) { + global = t.Pointer +} + +//go:noinline +func Store2(t *T) { + global2 = t.Pointer +} + +func Get() *int { + return global +} diff --git a/go/test/fixedbugs/issue4964.dir/b.go b/go/test/fixedbugs/issue4964.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..42a6f1d761a8c8451a68cbcc3df652b119032f1e --- /dev/null +++ b/go/test/fixedbugs/issue4964.dir/b.go @@ -0,0 +1,34 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func F() { + // store 1 in a.global + x, y := 1, 2 + t := a.T{Pointer: &x} + a.Store(&t) + _ = y +} + +func G() { + // store 4 in a.global2 + x, y := 3, 4 + t := a.T{Pointer: &y} + a.Store2(&t) + _ = x +} + +func main() { + F() + G() + p := a.Get() + n := *p + if n != 1 { + println(n, "!= 1") + panic("n != 1") + } +} diff --git a/go/test/fixedbugs/issue50788.dir/a.go b/go/test/fixedbugs/issue50788.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..0f786d494c9a77612272a520c022add42a165b0a --- /dev/null +++ b/go/test/fixedbugs/issue50788.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T[P any] struct { + _ P +} diff --git a/go/test/fixedbugs/issue50788.dir/b.go b/go/test/fixedbugs/issue50788.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..97ae20801985abdbb3bfc3dd07f2902b6c93771e --- /dev/null +++ b/go/test/fixedbugs/issue50788.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type T a.T[T] // ERROR "invalid recursive type T\n.*T refers to a\.T\n.*a\.T refers to T" diff --git a/go/test/fixedbugs/issue5105.dir/a.go b/go/test/fixedbugs/issue5105.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..f20abb98bfac7cc527bc2990a1d4e7fe4ccf40c8 --- /dev/null +++ b/go/test/fixedbugs/issue5105.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var A = [2]string{"hello", "world"} diff --git a/go/test/fixedbugs/issue5105.dir/b.go b/go/test/fixedbugs/issue5105.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b12e739e33a0db8e2758d003c58b029a035c2090 --- /dev/null +++ b/go/test/fixedbugs/issue5105.dir/b.go @@ -0,0 +1,15 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +var B = [2]string{"world", "hello"} + +func main() { + if a.A[0] != B[1] { + panic("bad hello") + } +} diff --git a/go/test/fixedbugs/issue5125.dir/bug.go b/go/test/fixedbugs/issue5125.dir/bug.go new file mode 100644 index 0000000000000000000000000000000000000000..2fdf0f9bb8b1630978110b9d9450b6c2b53629fb --- /dev/null +++ b/go/test/fixedbugs/issue5125.dir/bug.go @@ -0,0 +1,17 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug + +type Node interface { + Eval(s *Scene) +} + +type plug struct { + node Node +} + +type Scene struct { + changed map[plug]bool +} diff --git a/go/test/fixedbugs/issue5125.dir/main.go b/go/test/fixedbugs/issue5125.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..47acdeba8a9500b64573ab8f4fc57b71855d96d2 --- /dev/null +++ b/go/test/fixedbugs/issue5125.dir/main.go @@ -0,0 +1,10 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import _ "./bug" + +func main() { +} diff --git a/go/test/fixedbugs/issue51291.dir/a.go b/go/test/fixedbugs/issue51291.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..21e2cd6adfa1380c0bae41c2819bba34c6aeb8a1 --- /dev/null +++ b/go/test/fixedbugs/issue51291.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type TypeA string + +const StrA TypeA = "s" diff --git a/go/test/fixedbugs/issue51291.dir/b.go b/go/test/fixedbugs/issue51291.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..26b2c7872ed5db6788f8c2ba502e15067fbf9145 --- /dev/null +++ b/go/test/fixedbugs/issue51291.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type TypeB string + +const StrB TypeB = TypeB(a.StrA) diff --git a/go/test/fixedbugs/issue52128.dir/a.go b/go/test/fixedbugs/issue52128.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..0abf831c6fd13c5f8b00cdb3d6e2650f69642b76 --- /dev/null +++ b/go/test/fixedbugs/issue52128.dir/a.go @@ -0,0 +1,21 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I interface{} + +type F func() + +type s struct { + f F +} + +func NewWithF(f F) *s { + return &s{f: f} +} + +func NewWithFuncI(func() I) *s { + return &s{} +} diff --git a/go/test/fixedbugs/issue52128.dir/b.go b/go/test/fixedbugs/issue52128.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..86f6ed7e056229b3b1abc1cab23e7bc6a1b7026a --- /dev/null +++ b/go/test/fixedbugs/issue52128.dir/b.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import ( + "./a" +) + +type S struct{} + +func (s *S) M1() a.I { + return a.NewWithF(s.M2) +} + +func (s *S) M2() {} diff --git a/go/test/fixedbugs/issue52128.dir/p.go b/go/test/fixedbugs/issue52128.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..d3f3dbbfb9bc06efc683b92160e7f83582bc7459 --- /dev/null +++ b/go/test/fixedbugs/issue52128.dir/p.go @@ -0,0 +1,14 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "./a" + "./b" +) + +func f() { + a.NewWithFuncI((&b.S{}).M1) +} diff --git a/go/test/fixedbugs/issue52279.dir/lib.go b/go/test/fixedbugs/issue52279.dir/lib.go new file mode 100644 index 0000000000000000000000000000000000000000..e20de30bd5c02c8db29294e71af29a73c832dc8c --- /dev/null +++ b/go/test/fixedbugs/issue52279.dir/lib.go @@ -0,0 +1,23 @@ +package lib + +type FMap[K comparable, V comparable] map[K]V + +//go:noinline +func (m FMap[K, V]) Flip() FMap[V, K] { + out := make(FMap[V, K]) + return out +} + +type MyType uint8 + +const ( + FIRST MyType = 0 +) + +var typeStrs = FMap[MyType, string]{ + FIRST: "FIRST", +} + +func (self MyType) String() string { + return typeStrs[self] +} diff --git a/go/test/fixedbugs/issue52279.dir/main.go b/go/test/fixedbugs/issue52279.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8c7e069c5b924477770eeb51fabf5ea7bee7f27e --- /dev/null +++ b/go/test/fixedbugs/issue52279.dir/main.go @@ -0,0 +1,5 @@ +package main + +import "./lib" + +func main() { lib.FIRST.String() } diff --git a/go/test/fixedbugs/issue5259.dir/bug.go b/go/test/fixedbugs/issue5259.dir/bug.go new file mode 100644 index 0000000000000000000000000000000000000000..8512461686bcd5cc413e10c056f771102b6fe5dd --- /dev/null +++ b/go/test/fixedbugs/issue5259.dir/bug.go @@ -0,0 +1,17 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bug + +type S struct { + F func() +} + +type X interface { + Bar() +} + +func Foo(x X) *S { + return &S{F: x.Bar} +} diff --git a/go/test/fixedbugs/issue5259.dir/main.go b/go/test/fixedbugs/issue5259.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..ad1da78f5fca350a7b3f0e488c5e5a9a46b6444c --- /dev/null +++ b/go/test/fixedbugs/issue5259.dir/main.go @@ -0,0 +1,16 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./bug" + +type foo int + +func (f *foo) Bar() { +} + +func main() { + bug.Foo(new(foo)) +} diff --git a/go/test/fixedbugs/issue52590.dir/a.go b/go/test/fixedbugs/issue52590.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..20031e60c77170ca1d84a3d2b563257c299eb453 --- /dev/null +++ b/go/test/fixedbugs/issue52590.dir/a.go @@ -0,0 +1,68 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import "unsafe" + +func Append() { + _ = append(appendArgs()) +} + +func Delete() { + delete(deleteArgs()) +} + +func Print() { + print(ints()) +} + +func Println() { + println(ints()) +} + +func Complex() { + _ = complex(float64s()) +} + +func Copy() { + copy(slices()) +} + +func UnsafeAdd() { + _ = unsafe.Add(unsafeAdd()) +} + +func UnsafeSlice() { + _ = unsafe.Slice(unsafeSlice()) +} + +func appendArgs() ([]int, int) { + return []int{}, 0 +} + +func deleteArgs() (map[int]int, int) { + return map[int]int{}, 0 +} + +func ints() (int, int) { + return 1, 1 +} + +func float64s() (float64, float64) { + return 0, 0 +} + +func slices() ([]int, []int) { + return []int{}, []int{} +} + +func unsafeAdd() (unsafe.Pointer, int) { + return nil, 0 +} + +func unsafeSlice() (*byte, int) { + var p [10]byte + return &p[0], 0 +} diff --git a/go/test/fixedbugs/issue52590.dir/b.go b/go/test/fixedbugs/issue52590.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..264e8d10a6b6f135c0f757a9fa4077885ac644de --- /dev/null +++ b/go/test/fixedbugs/issue52590.dir/b.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func f() { + a.Append() + a.Delete() + a.Print() + a.Println() + a.Complex() + a.Copy() + a.UnsafeAdd() + a.UnsafeSlice() +} diff --git a/go/test/fixedbugs/issue5260.dir/a.go b/go/test/fixedbugs/issue5260.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..5a2c99f65c726b37edb241212b55ff960fb46857 --- /dev/null +++ b/go/test/fixedbugs/issue5260.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +const BOM = "\uFEFF" diff --git a/go/test/fixedbugs/issue5260.dir/b.go b/go/test/fixedbugs/issue5260.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..299b75e4a7cdd4a00c2d13390f604d29f0760e7b --- /dev/null +++ b/go/test/fixedbugs/issue5260.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + _ = a.BOM +} diff --git a/go/test/fixedbugs/issue52856.dir/a.go b/go/test/fixedbugs/issue52856.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..36af7e04cd0f8a5b060b2092e82b044b29b21446 --- /dev/null +++ b/go/test/fixedbugs/issue52856.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() any { + return struct{ int }{0} +} diff --git a/go/test/fixedbugs/issue52856.dir/main.go b/go/test/fixedbugs/issue52856.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..732368d3a7c79256f9e1f0da89c0eae1169d2792 --- /dev/null +++ b/go/test/fixedbugs/issue52856.dir/main.go @@ -0,0 +1,19 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func F() any { + return struct{ int }{0} +} + +func main() { + _, ok1 := F().(struct{ int }) + _, ok2 := a.F().(struct{ int }) + if !ok1 || ok2 { + panic(0) + } +} diff --git a/go/test/fixedbugs/issue52862.dir/a.go b/go/test/fixedbugs/issue52862.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..ef4ce2025c85b1669485a8ba60e1462340d59f7b --- /dev/null +++ b/go/test/fixedbugs/issue52862.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() complex128 { + return 0+0i +} diff --git a/go/test/fixedbugs/issue52862.dir/b.go b/go/test/fixedbugs/issue52862.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..739af663f72406b831ea752167201e07cadba983 --- /dev/null +++ b/go/test/fixedbugs/issue52862.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() complex128 { + return a.F() +} diff --git a/go/test/fixedbugs/issue5291.dir/pkg1.go b/go/test/fixedbugs/issue5291.dir/pkg1.go new file mode 100644 index 0000000000000000000000000000000000000000..b1c893ac83e63b0c2e4aff68926eb3120c95c5a9 --- /dev/null +++ b/go/test/fixedbugs/issue5291.dir/pkg1.go @@ -0,0 +1,34 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkg1 + +import ( + "runtime" +) + +type T2 *[]string + +type Data struct { + T1 *[]T2 +} + +func CrashCall() (err error) { + var d Data + + for count := 0; count < 10; count++ { + runtime.GC() + + len := 2 // crash when >=2 + x := make([]T2, len) + + d = Data{T1: &x} + + for j := 0; j < len; j++ { + y := make([]string, 1) + (*d.T1)[j] = &y + } + } + return nil +} diff --git a/go/test/fixedbugs/issue5291.dir/prog.go b/go/test/fixedbugs/issue5291.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..8301091bd8858ac4590a5c48674f6c75c014af82 --- /dev/null +++ b/go/test/fixedbugs/issue5291.dir/prog.go @@ -0,0 +1,17 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./pkg1" +) + +type message struct { // Presence of this creates a crash + data pkg1.Data +} + +func main() { + pkg1.CrashCall() +} diff --git a/go/test/fixedbugs/issue5470.dir/a.go b/go/test/fixedbugs/issue5470.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..302822d238707a9d05782550d512c66e147b5c40 --- /dev/null +++ b/go/test/fixedbugs/issue5470.dir/a.go @@ -0,0 +1,27 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Foo interface { + Hi() string +} + +func Test1() Foo { return make(tst1) } + +type tst1 map[string]bool + +func (r tst1) Hi() string { return "Hi!" } + +func Test2() Foo { return make(tst2, 0) } + +type tst2 []string + +func (r tst2) Hi() string { return "Hi!" } + +func Test3() Foo { return make(tst3) } + +type tst3 chan string + +func (r tst3) Hi() string { return "Hi!" } diff --git a/go/test/fixedbugs/issue5470.dir/b.go b/go/test/fixedbugs/issue5470.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..0801c149cfe26b0dc97c405cd929acac0a34dd08 --- /dev/null +++ b/go/test/fixedbugs/issue5470.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func main() { + a.Test1() + a.Test2() + a.Test3() +} diff --git a/go/test/fixedbugs/issue54912.dir/a.go b/go/test/fixedbugs/issue54912.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..b425223da989b41e16f0052e67b9cd57c1dafe48 --- /dev/null +++ b/go/test/fixedbugs/issue54912.dir/a.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that inlining a function literal that captures both a type +// switch case variable and another local variable works correctly. + +package a + +func F(p *int, x any) func() { + switch x := x.(type) { + case int: + return func() { + *p += x + } + } + return nil +} diff --git a/go/test/fixedbugs/issue54912.dir/main.go b/go/test/fixedbugs/issue54912.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..67b9012b36b5b79095e9d09a75097b22119da5c9 --- /dev/null +++ b/go/test/fixedbugs/issue54912.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "test/a" + +func main() { + a.F(new(int), 0)() +} diff --git a/go/test/fixedbugs/issue5614.dir/rethinkgo.go b/go/test/fixedbugs/issue5614.dir/rethinkgo.go new file mode 100644 index 0000000000000000000000000000000000000000..4ae66d679ea59fc47c07fe7c2b2ad6dd334d5382 --- /dev/null +++ b/go/test/fixedbugs/issue5614.dir/rethinkgo.go @@ -0,0 +1,16 @@ +package rethinkgo + +type Session struct { +} + +func (s *Session) Run(query Exp) *int { return nil } + +type List []interface{} + +type Exp struct { + args []interface{} +} + +func (e Exp) UseOutdated(useOutdated bool) Exp { + return Exp{args: List{e, useOutdated}} +} diff --git a/go/test/fixedbugs/issue5614.dir/x.go b/go/test/fixedbugs/issue5614.dir/x.go new file mode 100644 index 0000000000000000000000000000000000000000..7e4f3a7e6b9bb13944e4455ec03e4f9c065d5722 --- /dev/null +++ b/go/test/fixedbugs/issue5614.dir/x.go @@ -0,0 +1,7 @@ +package x + +import "./rethinkgo" + +var S *rethinkgo.Session + + diff --git a/go/test/fixedbugs/issue5614.dir/y.go b/go/test/fixedbugs/issue5614.dir/y.go new file mode 100644 index 0000000000000000000000000000000000000000..97cc93a79d5d7bdf6265122a5337c7861f2c5c3d --- /dev/null +++ b/go/test/fixedbugs/issue5614.dir/y.go @@ -0,0 +1,5 @@ +package y + +import "./x" + +var T = x.S diff --git a/go/test/fixedbugs/issue56280.dir/a.go b/go/test/fixedbugs/issue56280.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..289b06a7b3ab322473e0c22cf2dfcc2a29e81a70 --- /dev/null +++ b/go/test/fixedbugs/issue56280.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() { // ERROR "can inline F" + g(0) // ERROR "inlining call to g\[go.shape.int\]" +} + +func g[T any](_ T) {} // ERROR "can inline g\[int\]" "can inline g\[go.shape.int\]" "inlining call to g\[go.shape.int\]" diff --git a/go/test/fixedbugs/issue56280.dir/main.go b/go/test/fixedbugs/issue56280.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..06092b17f0068080978ce5ff8d013bf8e1e7a340 --- /dev/null +++ b/go/test/fixedbugs/issue56280.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "test/a" + +func main() { // ERROR "can inline main" + a.F() // ERROR "inlining call to a.F" "inlining call to a.g\[go.shape.int\]" +} diff --git a/go/test/fixedbugs/issue56778.dir/a.go b/go/test/fixedbugs/issue56778.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..d01aea4d1413bf03ae28a8ec76adc8e086e22a1b --- /dev/null +++ b/go/test/fixedbugs/issue56778.dir/a.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A struct { + New func() any +} + +func NewA(i int) *A { + return &A{ + New: func() any { + _ = i + return nil + }, + } +} diff --git a/go/test/fixedbugs/issue56778.dir/b.go b/go/test/fixedbugs/issue56778.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..d49f7e57080ba85e73d457b5b77ba5b8fc4531c1 --- /dev/null +++ b/go/test/fixedbugs/issue56778.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var _ = a.NewA(0) diff --git a/go/test/fixedbugs/issue5755.dir/a.go b/go/test/fixedbugs/issue5755.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..aa398e82b257c1b0213445d52377cc74f0640088 --- /dev/null +++ b/go/test/fixedbugs/issue5755.dir/a.go @@ -0,0 +1,60 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I interface { + F() +} + +type foo1 []byte +type foo2 []rune +type foo3 []uint8 +type foo4 []int32 +type foo5 string +type foo6 string +type foo7 string +type foo8 string +type foo9 string + +func (f foo1) F() { return } +func (f foo2) F() { return } +func (f foo3) F() { return } +func (f foo4) F() { return } +func (f foo5) F() { return } +func (f foo6) F() { return } +func (f foo7) F() { return } +func (f foo8) F() { return } +func (f foo9) F() { return } + +func Test1(s string) I { return foo1(s) } +func Test2(s string) I { return foo2(s) } +func Test3(s string) I { return foo3(s) } +func Test4(s string) I { return foo4(s) } +func Test5(s []byte) I { return foo5(s) } +func Test6(s []rune) I { return foo6(s) } +func Test7(s []uint8) I { return foo7(s) } +func Test8(s []int32) I { return foo8(s) } +func Test9(s int) I { return foo9(s) } + +type bar map[int]int + +func (b bar) F() { return } + +func TestBar() I { return bar{1: 2} } + +type baz int + +func IsBaz(x interface{}) bool { _, ok := x.(baz); return ok } + +type baz2 int + +func IsBaz2(x interface{}) bool { + switch x.(type) { + case baz2: + return true + default: + return false + } +} diff --git a/go/test/fixedbugs/issue5755.dir/main.go b/go/test/fixedbugs/issue5755.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6d515f26a637cc9e2572c9febda88cf5cf05629d --- /dev/null +++ b/go/test/fixedbugs/issue5755.dir/main.go @@ -0,0 +1,23 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.Test1("frumious") + a.Test2("frumious") + a.Test3("frumious") + a.Test4("frumious") + + a.Test5(nil) + a.Test6(nil) + a.Test7(nil) + a.Test8(nil) + a.Test9(0) + + a.TestBar() + a.IsBaz(nil) +} diff --git a/go/test/fixedbugs/issue58339.dir/a.go b/go/test/fixedbugs/issue58339.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..22cbe0c6f9d5342bcd74a4494461aedd2fafea10 --- /dev/null +++ b/go/test/fixedbugs/issue58339.dir/a.go @@ -0,0 +1,17 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func Assert(msgAndArgs ...any) { +} + +func Run() int { + Assert("%v") + return 0 +} + +func Run2() int { + return Run() +} diff --git a/go/test/fixedbugs/issue58339.dir/b.go b/go/test/fixedbugs/issue58339.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..1736ec7adb42e8d1363b85533514bbb40e5f2aff --- /dev/null +++ b/go/test/fixedbugs/issue58339.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var A = a.Run2() diff --git a/go/test/fixedbugs/issue58563.dir/a.go b/go/test/fixedbugs/issue58563.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..2b716c1b334a0586ca4a0ce28bd1c42ad5242137 --- /dev/null +++ b/go/test/fixedbugs/issue58563.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func Start() interface{ Stop() } { + return new(Stopper) +} + +type Stopper struct{} + +func (s *Stopper) Stop() {} diff --git a/go/test/fixedbugs/issue58563.dir/main.go b/go/test/fixedbugs/issue58563.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..18a90fcf056c0f515fc477aefdcefbb9a755ff96 --- /dev/null +++ b/go/test/fixedbugs/issue58563.dir/main.go @@ -0,0 +1,16 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "test/a" + +func main() { + stop := start() + defer stop() +} + +func start() func() { + return a.Start().Stop +} diff --git a/go/test/fixedbugs/issue5910.dir/a.go b/go/test/fixedbugs/issue5910.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..b236c15c7d39efc6d6005cbc60e1171252de1282 --- /dev/null +++ b/go/test/fixedbugs/issue5910.dir/a.go @@ -0,0 +1,22 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Package struct { + name string +} + +type Future struct { + result chan struct { + *Package + error + } +} + +func (t *Future) Result() (*Package, error) { + result := <-t.result + t.result <- result + return result.Package, result.error +} diff --git a/go/test/fixedbugs/issue5910.dir/main.go b/go/test/fixedbugs/issue5910.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..80ddfbbca3641a378951dbe4242b31a8076c7283 --- /dev/null +++ b/go/test/fixedbugs/issue5910.dir/main.go @@ -0,0 +1,12 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + f := new(a.Future) + f.Result() +} diff --git a/go/test/fixedbugs/issue5957.dir/a.go b/go/test/fixedbugs/issue5957.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..7411d5fcd54c0c2e2cb3761686054e2afcc4a408 --- /dev/null +++ b/go/test/fixedbugs/issue5957.dir/a.go @@ -0,0 +1,3 @@ +package surprise + +var X int diff --git a/go/test/fixedbugs/issue5957.dir/b.go b/go/test/fixedbugs/issue5957.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..9bc561b9ce5ac82dfaae964888a3ce2fde64e4e7 --- /dev/null +++ b/go/test/fixedbugs/issue5957.dir/b.go @@ -0,0 +1,2 @@ +package surprise2 + diff --git a/go/test/fixedbugs/issue5957.dir/c.go b/go/test/fixedbugs/issue5957.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..382e234537eb04574eb7acdaa60717a53d6b63d7 --- /dev/null +++ b/go/test/fixedbugs/issue5957.dir/c.go @@ -0,0 +1,12 @@ +package p + +import ( + "./a" // ERROR "imported and not used: \x22test/a\x22 as surprise|imported and not used: surprise|\x22test/a\x22 imported as surprise and not used" + "./b" // ERROR "imported and not used: \x22test/b\x22 as surprise2|imported and not used: surprise2|\x22test/b\x22 imported as surprise2 and not used" + b "./b" // ERROR "imported and not used: \x22test/b\x22$|imported and not used: surprise2|\x22test/b\x22 imported and not used" + foo "math" // ERROR "imported and not used: \x22math\x22 as foo|imported and not used: math|\x22math\x22 imported as foo and not used" + "fmt" // actually used + "strings" // ERROR "imported and not used: \x22strings\x22|imported and not used: strings|\x22strings\x22 imported and not used" +) + +var _ = fmt.Printf diff --git a/go/test/fixedbugs/issue59709.dir/aconfig.go b/go/test/fixedbugs/issue59709.dir/aconfig.go new file mode 100644 index 0000000000000000000000000000000000000000..01b3cf483ba11ba8f3e83c28f2085874d6866125 --- /dev/null +++ b/go/test/fixedbugs/issue59709.dir/aconfig.go @@ -0,0 +1,10 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package aconfig + +type Config struct { + name string + blah int +} diff --git a/go/test/fixedbugs/issue59709.dir/bresource.go b/go/test/fixedbugs/issue59709.dir/bresource.go new file mode 100644 index 0000000000000000000000000000000000000000..9fae0994b0c844903a556f42760d65e43e30e54e --- /dev/null +++ b/go/test/fixedbugs/issue59709.dir/bresource.go @@ -0,0 +1,27 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bresource + +type Resource[T any] struct { + name string + initializer Initializer[T] + cfg ResConfig + value T +} + +func Should[T any](r *Resource[T], e error) bool { + return r.cfg.ShouldRetry(e) +} + +type ResConfig struct { + ShouldRetry func(error) bool + TearDown func() +} + +type Initializer[T any] func(*int) (T, error) + +func New[T any](name string, f Initializer[T], cfg ResConfig) *Resource[T] { + return &Resource[T]{name: name, initializer: f, cfg: cfg} +} diff --git a/go/test/fixedbugs/issue59709.dir/cmem.go b/go/test/fixedbugs/issue59709.dir/cmem.go new file mode 100644 index 0000000000000000000000000000000000000000..43c4fe9901bff27029d04a1f220858f983ec0ba7 --- /dev/null +++ b/go/test/fixedbugs/issue59709.dir/cmem.go @@ -0,0 +1,37 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmem + +import ( + "./aconfig" + "./bresource" +) + +type MemT *int + +var G int + +type memResource struct { + x *int +} + +func (m *memResource) initialize(*int) (res *int, err error) { + return nil, nil +} + +func (m *memResource) teardown() { +} + +func NewResource(cfg *aconfig.Config) *bresource.Resource[*int] { + res := &memResource{ + x: &G, + } + + return bresource.New("Mem", res.initialize, bresource.ResConfig{ + // We always would want to retry the Memcache initialization. + ShouldRetry: func(error) bool { return true }, + TearDown: res.teardown, + }) +} diff --git a/go/test/fixedbugs/issue59709.dir/dcache.go b/go/test/fixedbugs/issue59709.dir/dcache.go new file mode 100644 index 0000000000000000000000000000000000000000..ea6321974e9c33cc80701098dea2741a06ad6cde --- /dev/null +++ b/go/test/fixedbugs/issue59709.dir/dcache.go @@ -0,0 +1,39 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package dcache + +import ( + "./aconfig" + "./bresource" + "./cmem" +) + +type Module struct { + cfg *aconfig.Config + err error + last any +} + +//go:noinline +func TD() { +} + +func (m *Module) Configure(x string) error { + if m.err != nil { + return m.err + } + res := cmem.NewResource(m.cfg) + m.last = res + + return nil +} + +func (m *Module) Blurb(x string, e error) bool { + res, ok := m.last.(*bresource.Resource[*int]) + if !ok { + panic("bad") + } + return bresource.Should(res, e) +} diff --git a/go/test/fixedbugs/issue59709.dir/main.go b/go/test/fixedbugs/issue59709.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c699a01fc140838b61849687fb9ce5daa56e6c18 --- /dev/null +++ b/go/test/fixedbugs/issue59709.dir/main.go @@ -0,0 +1,17 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./dcache" +) + +func main() { + var m dcache.Module + m.Configure("x") + m.Configure("y") + var e error + m.Blurb("x", e) +} diff --git a/go/test/fixedbugs/issue60945.dir/a.go b/go/test/fixedbugs/issue60945.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..663a0cfc69e02aaa504d7b8419a734041d4187b3 --- /dev/null +++ b/go/test/fixedbugs/issue60945.dir/a.go @@ -0,0 +1,22 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type S struct{} + +func callClosure(closure func()) { + closure() +} + +func (s *S) M() { + callClosure(func() { + defer f(s.m) // prevent closures to be inlined. + }) +} + +func (s *S) m() {} + +//go:noinline +func f(a ...any) {} diff --git a/go/test/fixedbugs/issue60945.dir/b.go b/go/test/fixedbugs/issue60945.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e60d9dc7c1abd35b1841896270081a431a3029e5 --- /dev/null +++ b/go/test/fixedbugs/issue60945.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var _ = (&a.S{}).M diff --git a/go/test/fixedbugs/issue62498.dir/a.go b/go/test/fixedbugs/issue62498.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..68f97475ab62c58f432a2a4593b77d8fce94b4ce --- /dev/null +++ b/go/test/fixedbugs/issue62498.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func One(L any) { + func() { + defer F(L) + }() +} + +func F(any) {} diff --git a/go/test/fixedbugs/issue62498.dir/main.go b/go/test/fixedbugs/issue62498.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e55a24fb3a081ef9ffb15a4439a052a2998e4c07 --- /dev/null +++ b/go/test/fixedbugs/issue62498.dir/main.go @@ -0,0 +1,18 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.One(nil) + Two(nil) +} + +func Two(L any) { + func() { + defer a.F(L) + }() +} diff --git a/go/test/fixedbugs/issue6295.dir/p0.go b/go/test/fixedbugs/issue6295.dir/p0.go new file mode 100644 index 0000000000000000000000000000000000000000..d4d4da7b3531b5942d730cc414cf00587b7daa52 --- /dev/null +++ b/go/test/fixedbugs/issue6295.dir/p0.go @@ -0,0 +1,13 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p0 + +type T0 interface { + m0() +} + +type S0 struct{} + +func (S0) m0() {} diff --git a/go/test/fixedbugs/issue6295.dir/p1.go b/go/test/fixedbugs/issue6295.dir/p1.go new file mode 100644 index 0000000000000000000000000000000000000000..26efae7409653bd2c8538c885ab74eea20c437f0 --- /dev/null +++ b/go/test/fixedbugs/issue6295.dir/p1.go @@ -0,0 +1,26 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p1 + +import "./p0" + +type T1 interface { + p0.T0 + m1() +} + +type S1 struct { + p0.S0 +} + +func (S1) m1() {} + +func NewT0() p0.T0 { + return S1{} +} + +func NewT1() T1 { + return S1{} +} diff --git a/go/test/fixedbugs/issue6295.dir/p2.go b/go/test/fixedbugs/issue6295.dir/p2.go new file mode 100644 index 0000000000000000000000000000000000000000..f5b6ffd0a1320123ac337b090e8d1c93291b5004 --- /dev/null +++ b/go/test/fixedbugs/issue6295.dir/p2.go @@ -0,0 +1,19 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./p0" + "./p1" +) + +var ( + _ p0.T0 = p0.S0{} + _ p0.T0 = p1.S1{} + _ p0.T0 = p1.NewT0() + _ p0.T0 = p1.NewT1() // same as p1.S1{} +) + +func main() {} diff --git a/go/test/fixedbugs/issue6513.dir/a.go b/go/test/fixedbugs/issue6513.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e5536feb61a46058f50ff3c6e5e595769f947f4a --- /dev/null +++ b/go/test/fixedbugs/issue6513.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T struct{ int } diff --git a/go/test/fixedbugs/issue6513.dir/b.go b/go/test/fixedbugs/issue6513.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..ce3d52ec1ab78e92f90ef6baaeefb4e7415d7e4a --- /dev/null +++ b/go/test/fixedbugs/issue6513.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type U struct{ a.T } diff --git a/go/test/fixedbugs/issue6513.dir/main.go b/go/test/fixedbugs/issue6513.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8d8c02b9076e21b8ef5058a17737d9daf8b63beb --- /dev/null +++ b/go/test/fixedbugs/issue6513.dir/main.go @@ -0,0 +1,16 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "./b" +) + +func main() { + var t a.T + var u b.U + _, _ = t, u +} diff --git a/go/test/fixedbugs/issue65957.dir/a.go b/go/test/fixedbugs/issue65957.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..284ec4af9f2df586e16291ff57b1124c4360e3fb --- /dev/null +++ b/go/test/fixedbugs/issue65957.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var s any + +//go:noinline +func F() { + s = new([4]int32) +} diff --git a/go/test/fixedbugs/issue65957.dir/main.go b/go/test/fixedbugs/issue65957.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..89b8a28234513120c7a6c8a135e16fe436306711 --- /dev/null +++ b/go/test/fixedbugs/issue65957.dir/main.go @@ -0,0 +1,19 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "reflect" +) + +var s = []rune{0, 1, 2, 3} + +func main() { + m := map[any]int{} + k := reflect.New(reflect.ArrayOf(4, reflect.TypeOf(int32(0)))).Elem().Interface() + m[k] = 1 + a.F() +} diff --git a/go/test/fixedbugs/issue6789.dir/a.go b/go/test/fixedbugs/issue6789.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..9c90e0740cda5865e09de1f323b7e825dff2218c --- /dev/null +++ b/go/test/fixedbugs/issue6789.dir/a.go @@ -0,0 +1,14 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type unexported struct { + a int + b bool +} + +type Struct struct { + unexported +} diff --git a/go/test/fixedbugs/issue6789.dir/b.go b/go/test/fixedbugs/issue6789.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b6a6fc317f53d4895ad1f6ec8d9b2f73dbcd5e98 --- /dev/null +++ b/go/test/fixedbugs/issue6789.dir/b.go @@ -0,0 +1,12 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +type s a.Struct + +func main() { +} diff --git a/go/test/fixedbugs/issue68526.dir/a/a.go b/go/test/fixedbugs/issue68526.dir/a/a.go new file mode 100644 index 0000000000000000000000000000000000000000..6249eb59df032b621a679d4093a613364d2699e1 --- /dev/null +++ b/go/test/fixedbugs/issue68526.dir/a/a.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A[T any] = struct{ F T } + +type B = struct{ F int } + +func F() B { + type a[T any] = struct{ F T } + return a[int]{} +} diff --git a/go/test/fixedbugs/issue68526.dir/main.go b/go/test/fixedbugs/issue68526.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8b72ea37b69ebdf010b9ef9c54fcc04edebb2f6d --- /dev/null +++ b/go/test/fixedbugs/issue68526.dir/main.go @@ -0,0 +1,43 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + + "issue68526.dir/a" +) + +func main() { + unexported() + exported() +} + +func unexported() { + var want struct{ F int } + + if any(want) != any(a.B{}) || any(want) != any(a.F()) { + panic("zero value of alias and concrete type not identical") + } +} + +func exported() { + var ( + astr a.A[string] + aint a.A[int] + ) + + if any(astr) != any(struct{ F string }{}) || any(aint) != any(struct{ F int }{}) { + panic("zero value of alias and concrete type not identical") + } + + if any(astr) == any(aint) { + panic("zero value of struct{ F string } and struct{ F int } are not distinct") + } + + if got := fmt.Sprintf("%T", astr); got != "struct { F string }" { + panic(got) + } +} diff --git a/go/test/fixedbugs/issue7023.dir/a.go b/go/test/fixedbugs/issue7023.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..cdb54320955b837704264f9f87f88138ab3d89b4 --- /dev/null +++ b/go/test/fixedbugs/issue7023.dir/a.go @@ -0,0 +1,10 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func Foo() { + goto bar +bar: +} diff --git a/go/test/fixedbugs/issue7023.dir/b.go b/go/test/fixedbugs/issue7023.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..c6fe40dfa27307908672af3f9b2e7128b125cb99 --- /dev/null +++ b/go/test/fixedbugs/issue7023.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import ( + "./a" +) + +var f = a.Foo diff --git a/go/test/fixedbugs/issue74648.dir/a.s b/go/test/fixedbugs/issue74648.dir/a.s new file mode 100644 index 0000000000000000000000000000000000000000..39a8d7684c4eba8e88ee0948376d2e8eb2f42f39 --- /dev/null +++ b/go/test/fixedbugs/issue74648.dir/a.s @@ -0,0 +1,11 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +TEXT ·F(SB), $0 + JMP prealigned + INT $3 // should never be reached +prealigned: + PCALIGN $0x10 +aligned: + RET diff --git a/go/test/fixedbugs/issue74648.dir/x.go b/go/test/fixedbugs/issue74648.dir/x.go new file mode 100644 index 0000000000000000000000000000000000000000..afde832d4a593aa72d750c894b6a4e1399d1125f --- /dev/null +++ b/go/test/fixedbugs/issue74648.dir/x.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Issue 74648: wrong jump target when using PCALIGN. + +package main + +func F() + +func main() { + F() +} diff --git a/go/test/fixedbugs/issue7648.dir/a.go b/go/test/fixedbugs/issue7648.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..c76aaa675f62efd345f5dc4ea1ae5e8503211c36 --- /dev/null +++ b/go/test/fixedbugs/issue7648.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +const ( + sinPi4 = 0.70710678118654752440084436210484903928483593768847 + A = complex(sinPi4, -sinPi4) +) + diff --git a/go/test/fixedbugs/issue7648.dir/b.go b/go/test/fixedbugs/issue7648.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..7b336025ae47d8b4846ff5d640849ff36c350b21 --- /dev/null +++ b/go/test/fixedbugs/issue7648.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func f() { + println(a.A) +} diff --git a/go/test/fixedbugs/issue7995b.dir/x1.go b/go/test/fixedbugs/issue7995b.dir/x1.go new file mode 100644 index 0000000000000000000000000000000000000000..bafecf52a9ce0d71db4f0cc9f52aa78a1344da72 --- /dev/null +++ b/go/test/fixedbugs/issue7995b.dir/x1.go @@ -0,0 +1,12 @@ +package x1 + +import "fmt" + +var P int + +//go:noinline +func F(x *int) string { + P = 50 + *x = 100 + return fmt.Sprintln(P, *x) +} diff --git a/go/test/fixedbugs/issue7995b.dir/x2.go b/go/test/fixedbugs/issue7995b.dir/x2.go new file mode 100644 index 0000000000000000000000000000000000000000..eea23eabba2467b032cd48b65dec77edbc3f4564 --- /dev/null +++ b/go/test/fixedbugs/issue7995b.dir/x2.go @@ -0,0 +1,10 @@ +package main + +import "./x1" + +func main() { + s := x1.F(&x1.P) + if s != "100 100\n" { + println("BUG:", s) + } +} diff --git a/go/test/fixedbugs/issue8060.dir/a.go b/go/test/fixedbugs/issue8060.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..22ba69ee1beda0947fb5e1fffa93d302915c9a13 --- /dev/null +++ b/go/test/fixedbugs/issue8060.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +var A = []*[2][1]float64{} diff --git a/go/test/fixedbugs/issue8060.dir/b.go b/go/test/fixedbugs/issue8060.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..fc7eb251d0bc1d408b7c7e39434c452eda090f5d --- /dev/null +++ b/go/test/fixedbugs/issue8060.dir/b.go @@ -0,0 +1,13 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var X = a.A + +func b() { + _ = [3][1]float64{} +} diff --git a/go/test/fixedbugs/issue8280.dir/a.go b/go/test/fixedbugs/issue8280.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..588536e79a630eee74aa695819d38dba46f05681 --- /dev/null +++ b/go/test/fixedbugs/issue8280.dir/a.go @@ -0,0 +1,3 @@ +package a + +var Bar = func() (_ int) { return 0 } diff --git a/go/test/fixedbugs/issue8280.dir/b.go b/go/test/fixedbugs/issue8280.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..c46c554588b1a5911ef335c433dd9fdd473b1a2c --- /dev/null +++ b/go/test/fixedbugs/issue8280.dir/b.go @@ -0,0 +1,5 @@ +package b + +import "./a" + +var foo = a.Bar diff --git a/go/test/fixedbugs/issue9355.dir/a.go b/go/test/fixedbugs/issue9355.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..84500c8c01117593617d9599b0d7c46d94d4ee1b --- /dev/null +++ b/go/test/fixedbugs/issue9355.dir/a.go @@ -0,0 +1,16 @@ +package main + +var x struct { + a, b, c int64 + d struct{ p, q, r int32 } + e [8]byte + f [4]struct{ p, q, r int32 } +} + +var y = &x.b +var z = &x.d.q + +var b [10]byte +var c = &b[5] + +var w = &x.f[3].r diff --git a/go/test/fixedbugs/issue9537.dir/a.go b/go/test/fixedbugs/issue9537.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..818c9eb4ab81a45677d50f1d5924df915746ca89 --- /dev/null +++ b/go/test/fixedbugs/issue9537.dir/a.go @@ -0,0 +1,25 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type X struct { + T [32]byte +} + +func (x *X) Get() []byte { + t := x.T + return t[:] +} + +func (x *X) RetPtr(i int) *int { + i++ + return &i +} + +func (x *X) RetRPtr(i int) (r1 int, r2 *int) { + r1 = i + 1 + r2 = &r1 + return +} diff --git a/go/test/fixedbugs/issue9537.dir/b.go b/go/test/fixedbugs/issue9537.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..52e64c81f1f6e926e8b350e46c93ef0108ae1c28 --- /dev/null +++ b/go/test/fixedbugs/issue9537.dir/b.go @@ -0,0 +1,43 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "bytes" + + "./a" +) + +type X struct { + *a.X +} + +type Intf interface { + Get() []byte + RetPtr(int) *int + RetRPtr(int) (int, *int) +} + +func main() { + x := &a.X{T: [32]byte{1, 2, 3, 4}} + var ix Intf = X{x} + t1 := ix.Get() + t2 := x.Get() + if !bytes.Equal(t1, t2) { + panic(t1) + } + + p1 := ix.RetPtr(5) + p2 := x.RetPtr(7) + if *p1 != 6 || *p2 != 8 { + panic(*p1) + } + + r1, r2 := ix.RetRPtr(10) + r3, r4 := x.RetRPtr(13) + if r1 != 11 || *r2 != 11 || r3 != 14 || *r4 != 14 { + panic("bad RetRPtr") + } +} diff --git a/go/test/fixedbugs/issue9608.dir/issue9608.go b/go/test/fixedbugs/issue9608.dir/issue9608.go new file mode 100644 index 0000000000000000000000000000000000000000..ca82ded4cd0d2b4283a8c97c4b807f6d455873a4 --- /dev/null +++ b/go/test/fixedbugs/issue9608.dir/issue9608.go @@ -0,0 +1,82 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +func fail() // unimplemented, to test dead code elimination + +// Test dead code elimination in if statements +func init() { + if false { + fail() + } + if 0 == 1 { + fail() + } +} + +// Test dead code elimination in ordinary switch statements +func init() { + const x = 0 + switch x { + case 1: + fail() + } + + switch 1 { + case x: + fail() + } + + switch { + case false: + fail() + } + + const a = "a" + switch a { + case "b": + fail() + } + + const snowman = '☃' + switch snowman { + case '☀': + fail() + } + + const zero = float64(0.0) + const one = float64(1.0) + switch one { + case -1.0: + fail() + case zero: + fail() + } + + switch 1.0i { + case 1: + fail() + case -1i: + fail() + } + + const no = false + switch no { + case true: + fail() + } + + // Test dead code elimination in large ranges. + switch 5 { + case 3, 4, 5, 6, 7: + case 0, 1, 2: + fail() + default: + fail() + } +} + +func main() { +} diff --git a/go/test/interface/embed1.dir/embed0.go b/go/test/interface/embed1.dir/embed0.go new file mode 100644 index 0000000000000000000000000000000000000000..4aed391b634a0069024e686b0af7629bf198a003 --- /dev/null +++ b/go/test/interface/embed1.dir/embed0.go @@ -0,0 +1,28 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that embedded interface types can have local methods. + +package p + +type T int + +func (t T) m() {} + +type I interface{ m() } +type J interface{ I } + +func main() { + var i I + var j J + var t T + i = t + j = t + _ = i + _ = j + i = j + _ = i + j = i + _ = j +} diff --git a/go/test/interface/embed1.dir/embed1.go b/go/test/interface/embed1.dir/embed1.go new file mode 100644 index 0000000000000000000000000000000000000000..7dfb1dbc0ad416533286bfdeb1083b32a067622c --- /dev/null +++ b/go/test/interface/embed1.dir/embed1.go @@ -0,0 +1,43 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that embedded interface types can have local methods. + +package main + +import "./embed0" + +type T int +func (t T) m() {} + +type I interface { m() } +type J interface { I } + +type PI interface { p.I } +type PJ interface { p.J } + +func main() { + var i I + var j J + var t T + i = t + j = t + _ = i + _ = j + i = j + _ = i + j = i + _ = j + var pi PI + var pj PJ + var pt p.T + pi = pt + pj = pt + _ = pi + _ = pj + pi = pj + _ = pi + pj = pi + _ = pj +} diff --git a/go/test/interface/embed3.dir/embed0.go b/go/test/interface/embed3.dir/embed0.go new file mode 100644 index 0000000000000000000000000000000000000000..614609e74aefe73a54795a3ea97e603854b48367 --- /dev/null +++ b/go/test/interface/embed3.dir/embed0.go @@ -0,0 +1,21 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type I1 interface { + Foo(int) +} + +type I2 interface { + foo(int) +} + +type M1 int + +func (M1) foo() {} + +type M2 int + +func (M2) foo(int) {} diff --git a/go/test/interface/embed3.dir/embed1.go b/go/test/interface/embed3.dir/embed1.go new file mode 100644 index 0000000000000000000000000000000000000000..d042482e941c540cd07cf4d05e3c0a3696a9eaec --- /dev/null +++ b/go/test/interface/embed3.dir/embed1.go @@ -0,0 +1,78 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./embed0" + +type X1 struct{} + +func (X1) Foo() {} + +type X2 struct{} + +func (X2) foo() {} + +type X3 struct{} + +func (X3) foo(int) {} + +type X4 struct{ p.M1 } + +type X5 struct{ p.M1 } + +func (X5) foo(int) {} + +type X6 struct{ p.M2 } + +type X7 struct{ p.M2 } + +func (X7) foo() {} + +type X8 struct{ p.M2 } + +func (X8) foo(int) {} + +func main() { + var i1 interface{} = X1{} + check(func() { _ = i1.(p.I1) }, "interface conversion: main.X1 is not p.I1: missing method Foo") + + var i2 interface{} = X2{} + check(func() { _ = i2.(p.I2) }, "interface conversion: main.X2 is not p.I2: missing method foo") + + var i3 interface{} = X3{} + check(func() { _ = i3.(p.I2) }, "interface conversion: main.X3 is not p.I2: missing method foo") + + var i4 interface{} = X4{} + check(func() { _ = i4.(p.I2) }, "interface conversion: main.X4 is not p.I2: missing method foo") + + var i5 interface{} = X5{} + check(func() { _ = i5.(p.I2) }, "interface conversion: main.X5 is not p.I2: missing method foo") + + var i6 interface{} = X6{} + check(func() { _ = i6.(p.I2) }, "") + + var i7 interface{} = X7{} + check(func() { _ = i7.(p.I2) }, "") + + var i8 interface{} = X8{} + check(func() { _ = i8.(p.I2) }, "") +} + +func check(f func(), msg string) { + defer func() { + v := recover() + if v == nil { + if msg == "" { + return + } + panic("did not panic") + } + got := v.(error).Error() + if msg != got { + panic("want '" + msg + "', got '" + got + "'") + } + }() + f() +} diff --git a/go/test/interface/private.dir/private1.go b/go/test/interface/private.dir/private1.go new file mode 100644 index 0000000000000000000000000000000000000000..75eee51f5a0509c287cc0a7f8682f09c777a0589 --- /dev/null +++ b/go/test/interface/private.dir/private1.go @@ -0,0 +1,18 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Imported by private.go, which should not be able to see the private method. + +package p + +type Exported interface { + private() +} + +type Implementation struct{} + +func (p *Implementation) private() {} + +var X = new(Implementation) + diff --git a/go/test/interface/private.dir/prog.go b/go/test/interface/private.dir/prog.go new file mode 100644 index 0000000000000000000000000000000000000000..abea7d625c762b0f465a7c31d91ef9e3342414fa --- /dev/null +++ b/go/test/interface/private.dir/prog.go @@ -0,0 +1,33 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that unexported methods are not visible outside the package. +// Does not compile. + +package main + +import "./private1" + +type Exported interface { + private() +} + +type Implementation struct{} + +func (p *Implementation) private() {} + +func main() { + var x Exported + x = new(Implementation) + x.private() + + var px p.Exported + px = p.X + + px.private() // ERROR "private" + + px = new(Implementation) // ERROR "private" + + x = px // ERROR "private" +} diff --git a/go/test/interface/recursive1.dir/recursive1.go b/go/test/interface/recursive1.dir/recursive1.go new file mode 100644 index 0000000000000000000000000000000000000000..8498cb5d7512081a8758dddef699df43801d8c2a --- /dev/null +++ b/go/test/interface/recursive1.dir/recursive1.go @@ -0,0 +1,15 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Mutually recursive type definitions imported and used by recursive1.go. + +package p + +type I1 interface { + F() I2 +} + +type I2 interface { + I1 +} diff --git a/go/test/interface/recursive1.dir/recursive2.go b/go/test/interface/recursive1.dir/recursive2.go new file mode 100644 index 0000000000000000000000000000000000000000..29385df76df17a93b1b459a3e8e18aa2eed7ae75 --- /dev/null +++ b/go/test/interface/recursive1.dir/recursive2.go @@ -0,0 +1,20 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that the mutually recursive types in recursive1.go made it +// intact and with the same meaning, by assigning to or using them. + +package main + +import "./recursive1" + +func main() { + var i1 p.I1 + var i2 p.I2 + i1 = i2 + i2 = i1 + i1 = i2.F() + i2 = i1.F() + _, _ = i1, i2 +} diff --git a/go/test/internal/runtime/sys/README b/go/test/internal/runtime/sys/README new file mode 100644 index 0000000000000000000000000000000000000000..919e0bb03f45df157c9518fe5853ebd659b8b58e --- /dev/null +++ b/go/test/internal/runtime/sys/README @@ -0,0 +1,7 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +The internal/runtime/sys directory contains tests that specifically need to be +compiled as-if in the internal/runtime/sys package. For error-check tests, +these require the additional flags -+ and -p=internal/runtime/sys. diff --git a/go/test/internal/runtime/sys/inlinegcpc.go b/go/test/internal/runtime/sys/inlinegcpc.go new file mode 100644 index 0000000000000000000000000000000000000000..7cadc639d101697b5c25af83609a25f0fdcccc4c --- /dev/null +++ b/go/test/internal/runtime/sys/inlinegcpc.go @@ -0,0 +1,29 @@ +// errorcheck -0 -+ -p=internal/runtime/sys -m + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sys + +// A function that calls sys.GetCallerPC or sys.GetCallerSP +// cannot be inlined, no matter how small it is. + +func GetCallerPC() uintptr +func GetCallerSP() uintptr + +func pc() uintptr { + return GetCallerPC() + 1 +} + +func cpc() uintptr { // ERROR "can inline cpc" + return pc() + 2 +} + +func sp() uintptr { + return GetCallerSP() + 3 +} + +func csp() uintptr { // ERROR "can inline csp" + return sp() + 4 +} diff --git a/go/test/typeparam/issue49241.dir/a.go b/go/test/typeparam/issue49241.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..34c99657d49b9594393b02ba792de821102e8418 --- /dev/null +++ b/go/test/typeparam/issue49241.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T[P any] struct { + x P +} + +type U struct { + a,b int +} diff --git a/go/test/typeparam/issue49241.dir/b.go b/go/test/typeparam/issue49241.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e5f1e1290eb8ddd17ccf444e63cae7ba38c44c9a --- /dev/null +++ b/go/test/typeparam/issue49241.dir/b.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +//go:noinline +func F() interface{} { + return a.T[int]{} +} + +//go:noinline +func G() interface{} { + return struct{ X, Y a.U }{} +} diff --git a/go/test/typeparam/issue49241.dir/c.go b/go/test/typeparam/issue49241.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..34ea7c3ffae86f2c17af762047fcdee613975d66 --- /dev/null +++ b/go/test/typeparam/issue49241.dir/c.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import "./a" + +//go:noinline +func F() interface{} { + return a.T[int]{} +} + +//go:noinline +func G() interface{} { + return struct{ X, Y a.U }{} +} diff --git a/go/test/typeparam/issue49241.dir/main.go b/go/test/typeparam/issue49241.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..58bb8a017f16f3882c978e986846593b5dac18ee --- /dev/null +++ b/go/test/typeparam/issue49241.dir/main.go @@ -0,0 +1,21 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./b" + "./c" +) + +func main() { + if b.G() != c.G() { + println(b.G(), c.G()) + panic("bad") + } + if b.F() != c.F() { + println(b.F(), c.F()) + panic("bad") + } +} diff --git a/go/test/typeparam/issue49246.dir/a.go b/go/test/typeparam/issue49246.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..97459ee7481de590169e3453c77399aa1f4807b1 --- /dev/null +++ b/go/test/typeparam/issue49246.dir/a.go @@ -0,0 +1,20 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type R[T any] struct{ v T } + +func (r R[T]) Self() R[T] { return R[T]{} } + +type Fn[T any] func() R[T] + +func X() (r R[int]) { return r.Self() } + +func Y[T any](a Fn[T]) Fn[int] { + return func() (r R[int]) { + // No crash: return R[int]{} + return r.Self() + } +} diff --git a/go/test/typeparam/issue49246.dir/b.go b/go/test/typeparam/issue49246.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..5141b72fd4ddceb5d2ec320481bec4e7f95546fb --- /dev/null +++ b/go/test/typeparam/issue49246.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func Crash() { a.Y(a.X)() } diff --git a/go/test/typeparam/issue49497.dir/a.go b/go/test/typeparam/issue49497.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..86062d446ffff60a62f53625b1b287919a2638bb --- /dev/null +++ b/go/test/typeparam/issue49497.dir/a.go @@ -0,0 +1,26 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F[T any]() A[T] { + var x A[T] + return x +} + +type A[T any] struct { + b B[T] +} + +func (a A[T]) M() C[T] { + return C[T]{ + B: a.b, + } +} + +type B[T any] struct{} + +type C[T any] struct { + B B[T] +} diff --git a/go/test/typeparam/issue49497.dir/main.go b/go/test/typeparam/issue49497.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e74dae08598ced8e8b1d8eeba9bd082b5bc4a520 --- /dev/null +++ b/go/test/typeparam/issue49497.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.F[string]() +} diff --git a/go/test/typeparam/issue49524.dir/a.go b/go/test/typeparam/issue49524.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..f40075e953ee6ae0b15f7f2492169ec43c1996b8 --- /dev/null +++ b/go/test/typeparam/issue49524.dir/a.go @@ -0,0 +1,8 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F[T any]() { +} diff --git a/go/test/typeparam/issue49524.dir/main.go b/go/test/typeparam/issue49524.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8787e7ea69b365137ef2964dd460333eb208ec0c --- /dev/null +++ b/go/test/typeparam/issue49524.dir/main.go @@ -0,0 +1,11 @@ +package main + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import "./a" + +func main() { + a.F[int]() +} diff --git a/go/test/typeparam/issue49536.dir/a.go b/go/test/typeparam/issue49536.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..a95ad60812cbaa3683174fb6fdefa0606e9547a1 --- /dev/null +++ b/go/test/typeparam/issue49536.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F() interface{} { return new(T[int]) } + +type T[P any] int + +func (x *T[P]) One() int { return x.Two() } +func (x *T[P]) Two() int { return 0 } diff --git a/go/test/typeparam/issue49536.dir/b.go b/go/test/typeparam/issue49536.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b08a77b9de1c2d64d6ac1958ecc588e2f6237716 --- /dev/null +++ b/go/test/typeparam/issue49536.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var _ = a.F() diff --git a/go/test/typeparam/issue49659.dir/a.go b/go/test/typeparam/issue49659.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..718bc0c5fce5d7dbd7c305e082a9280b0a780338 --- /dev/null +++ b/go/test/typeparam/issue49659.dir/a.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A[T any] struct { + a int +} + +func (a A[T]) F() { + _ = &a.a +} diff --git a/go/test/typeparam/issue49659.dir/b.go b/go/test/typeparam/issue49659.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..4818a42a486f373e6cf863fdd4bea25aee9e0cf4 --- /dev/null +++ b/go/test/typeparam/issue49659.dir/b.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type B[T any] struct { + v a.A[T] +} + +func (b B[T]) F() { + b.v.F() +} diff --git a/go/test/typeparam/issue49667.dir/a.go b/go/test/typeparam/issue49667.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3b1889f699272da8af5b7cd06a29fe589f7e5cef --- /dev/null +++ b/go/test/typeparam/issue49667.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A[T any] struct { +} + +func (a A[T]) F() { + _ = a +} diff --git a/go/test/typeparam/issue49667.dir/b.go b/go/test/typeparam/issue49667.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..81cdb80036dc14ce87cf0988bb10015aabcee68c --- /dev/null +++ b/go/test/typeparam/issue49667.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type B[T any] struct { + _ a.A[T] +} diff --git a/go/test/typeparam/issue49667.dir/main.go b/go/test/typeparam/issue49667.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f9fa60f3f533a0a952cd7ff22f3efce8b59861ca --- /dev/null +++ b/go/test/typeparam/issue49667.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./b" + +func main() { + var _ b.B[int] +} diff --git a/go/test/typeparam/issue49893.dir/a.go b/go/test/typeparam/issue49893.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..bc810cd3dd5300752cd3b36322aecc983b68c245 --- /dev/null +++ b/go/test/typeparam/issue49893.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Option[T any] interface { + ToSeq() Seq[T] +} + +type Seq[T any] []T + +func (r Seq[T]) Find(p func(v T) bool) Option[T] { + panic("") +} diff --git a/go/test/typeparam/issue49893.dir/b.go b/go/test/typeparam/issue49893.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..b86b53666489149a7c31a1e60adc0d96e96644cd --- /dev/null +++ b/go/test/typeparam/issue49893.dir/b.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type Ap1[A, B any] struct { + opt a.Option[A] +} + +type Ap2[A, B any] struct { + opt a.Option[A] +} diff --git a/go/test/typeparam/issue49893.dir/main.go b/go/test/typeparam/issue49893.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..447212d027648f1fee31e1fe35c823f16f04a6ae --- /dev/null +++ b/go/test/typeparam/issue49893.dir/main.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./b" + "fmt" +) + +func main() { + opt := b.Ap1[string, string]{} + fmt.Println(opt) +} diff --git a/go/test/typeparam/issue50121.dir/a.go b/go/test/typeparam/issue50121.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..ca11b6b27a2d1a6dc3eafb188b3dd4335bf6bfa1 --- /dev/null +++ b/go/test/typeparam/issue50121.dir/a.go @@ -0,0 +1,26 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import ( + "math/rand" +) + +type Integer interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +type Builder[T Integer] struct{} + +func (r Builder[T]) New() T { + return T(rand.Int()) +} + +var IntBuilder = Builder[int]{} + +func BuildInt() int { + return IntBuilder.New() +} diff --git a/go/test/typeparam/issue50121.dir/main.go b/go/test/typeparam/issue50121.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3978ef4fba8353eb58201a769ab2aa1909a73613 --- /dev/null +++ b/go/test/typeparam/issue50121.dir/main.go @@ -0,0 +1,18 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" +) + +//go:noinline +func BuildInt() int { + return a.BuildInt() +} + +func main() { + BuildInt() +} diff --git a/go/test/typeparam/issue50121b.dir/a.go b/go/test/typeparam/issue50121b.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..4ddbb6ea847765f0b8d3dd1a990a1dff3f950280 --- /dev/null +++ b/go/test/typeparam/issue50121b.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Integer interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +type Builder[T Integer] struct{} + +func (r Builder[T]) New() T { + return T(42) +} diff --git a/go/test/typeparam/issue50121b.dir/b.go b/go/test/typeparam/issue50121b.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..efa6cbbc307e378bc66d8a6dc6b3c70aa22d12ac --- /dev/null +++ b/go/test/typeparam/issue50121b.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import ( + "./a" +) + +var IntBuilder = a.Builder[int]{} diff --git a/go/test/typeparam/issue50121b.dir/c.go b/go/test/typeparam/issue50121b.dir/c.go new file mode 100644 index 0000000000000000000000000000000000000000..169135678dad1ec1600523268d5337fd7798019e --- /dev/null +++ b/go/test/typeparam/issue50121b.dir/c.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package c + +import ( + "./b" +) + +func BuildInt() int { + return b.IntBuilder.New() +} diff --git a/go/test/typeparam/issue50121b.dir/d.go b/go/test/typeparam/issue50121b.dir/d.go new file mode 100644 index 0000000000000000000000000000000000000000..93b40c921e04a77240a8a8cc07518c4a46edc623 --- /dev/null +++ b/go/test/typeparam/issue50121b.dir/d.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package d + +import ( + "./c" +) + +func BuildInt() int { + return c.BuildInt() +} diff --git a/go/test/typeparam/issue50121b.dir/main.go b/go/test/typeparam/issue50121b.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..33986018506d5964c51617bbe142051daf21e90f --- /dev/null +++ b/go/test/typeparam/issue50121b.dir/main.go @@ -0,0 +1,12 @@ +package main + +import ( + "./d" + "fmt" +) + +func main() { + if got, want := d.BuildInt(), 42; got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } +} diff --git a/go/test/typeparam/issue50437.dir/a.go b/go/test/typeparam/issue50437.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..4a136b52ae2d00539ac5aa587d5bc2839bdbb9a5 --- /dev/null +++ b/go/test/typeparam/issue50437.dir/a.go @@ -0,0 +1,43 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type MarshalOptions struct { + *typedArshalers[MarshalOptions] +} + +func Marshal(in interface{}) (out []byte, err error) { + return MarshalOptions{}.Marshal(in) +} + +func (mo MarshalOptions) Marshal(in interface{}) (out []byte, err error) { + err = mo.MarshalNext(in) + return nil, err +} + +func (mo MarshalOptions) MarshalNext(in interface{}) error { + a := new(arshaler) + a.marshal = func(MarshalOptions) error { return nil } + return a.marshal(mo) +} + +type arshaler struct { + marshal func(MarshalOptions) error +} + +type typedArshalers[Options any] struct { + m M +} + +func (a *typedArshalers[Options]) lookup(fnc func(Options) error) (func(Options) error, bool) { + a.m.Load(nil) + return fnc, false +} + +type M struct {} + +func (m *M) Load(key any) (value any, ok bool) { + return +} diff --git a/go/test/typeparam/issue50437.dir/b.go b/go/test/typeparam/issue50437.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..afddc3f3307493bbc47b47af165c95d9189f455c --- /dev/null +++ b/go/test/typeparam/issue50437.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func f() { + a.Marshal(map[int]int{}) +} diff --git a/go/test/typeparam/issue50481b.dir/b.go b/go/test/typeparam/issue50481b.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..d458357c51f2f670ca86e4dad258ec600e95d120 --- /dev/null +++ b/go/test/typeparam/issue50481b.dir/b.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "fmt" + +type Foo[T1 ~string, T2 ~int] struct { + ValueA T1 + ValueB T2 +} + +func (f *Foo[_, _]) String() string { + return fmt.Sprintf("%v %v", f.ValueA, f.ValueB) +} diff --git a/go/test/typeparam/issue50481b.dir/main.go b/go/test/typeparam/issue50481b.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6a5067c9fb2d862fd09c5a4c2106aeab39e47189 --- /dev/null +++ b/go/test/typeparam/issue50481b.dir/main.go @@ -0,0 +1,23 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that type substitution and export/import works correctly even for a method of +// a generic type that has multiple blank type params. + +package main + +import ( + "./b" + "fmt" +) + +func main() { + foo := &b.Foo[string, int]{ + ValueA: "i am a string", + ValueB: 123, + } + if got, want := fmt.Sprintln(foo), "i am a string 123\n"; got != want { + panic(fmt.Sprintf("got %s, want %s", got, want)) + } +} diff --git a/go/test/typeparam/issue50481c.dir/a.go b/go/test/typeparam/issue50481c.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..384ba23f989ed0a1a11c4b77d9a99869256fda0a --- /dev/null +++ b/go/test/typeparam/issue50481c.dir/a.go @@ -0,0 +1,30 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A interface { + int | int64 +} + +type B interface { + string +} + +type C interface { + String() string +} + +type Myint int + +func (i Myint) String() string { + return "aa" +} + +type T[P A, _ C, _ B] int + +func (v T[P, Q, R]) test() { + var r Q + r.String() +} diff --git a/go/test/typeparam/issue50481c.dir/main.go b/go/test/typeparam/issue50481c.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..178542bc380eb3657ffd39d59033d587c5824a33 --- /dev/null +++ b/go/test/typeparam/issue50481c.dir/main.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that type substitution works and export/import works correctly even for a +// generic type that has multiple blank type params. + +package main + +import ( + "./a" + "fmt" +) + +func main() { + var x a.T[int, a.Myint, string] + fmt.Printf("%v\n", x) +} diff --git a/go/test/typeparam/issue50485.dir/a.go b/go/test/typeparam/issue50485.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..97cf4d254951a29988d715bec1af8787923943b0 --- /dev/null +++ b/go/test/typeparam/issue50485.dir/a.go @@ -0,0 +1,238 @@ +package a + +import "fmt" + +type ImplicitOrd interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 | + ~string +} + +func LessGiven[T ImplicitOrd]() Ord[T] { + return LessFunc[T](func(a, b T) bool { + return a < b + }) +} + +type Eq[T any] interface { + Eqv(a T, b T) bool +} + +type Ord[T any] interface { + Eq[T] + Less(a T, b T) bool +} + +type LessFunc[T any] func(a, b T) bool + +func (r LessFunc[T]) Eqv(a, b T) bool { + return r(a, b) == false && r(b, a) == false +} + +func (r LessFunc[T]) Less(a, b T) bool { + return r(a, b) +} + +type Option[T any] struct { + v *T +} + +func (r Option[T]) IsDefined() bool { + return r.v != nil +} + +func (r Option[T]) IsEmpty() bool { + return !r.IsDefined() +} + +func (r Option[T]) Get() T { + return *r.v +} + +func (r Option[T]) String() string { + if r.IsDefined() { + return fmt.Sprintf("Some(%v)", r.v) + } else { + return "None" + } +} + +func (r Option[T]) OrElse(t T) T { + if r.IsDefined() { + return *r.v + } + return t +} + +func (r Option[T]) Recover(f func() T) Option[T] { + if r.IsDefined() { + return r + } + t := f() + return Option[T]{&t} +} + +type Func1[A1, R any] func(a1 A1) R + +type Func2[A1, A2, R any] func(a1 A1, a2 A2) R + +func (r Func2[A1, A2, R]) Curried() Func1[A1, Func1[A2, R]] { + return func(a1 A1) Func1[A2, R] { + return Func1[A2, R](func(a2 A2) R { + return r(a1, a2) + }) + } +} + +type HList interface { + sealed() +} + +// Header is constrains interface type, enforce Head type of Cons is HT +type Header[HT any] interface { + HList + Head() HT +} + +// Cons means H :: T +// zero value of Cons[H,T] is not allowed. +// so Cons defined as interface type +type Cons[H any, T HList] interface { + HList + Head() H + Tail() T +} + +type Nil struct { +} + +func (r Nil) Head() Nil { + return r +} + +func (r Nil) Tail() Nil { + return r +} + +func (r Nil) String() string { + return "Nil" +} + +func (r Nil) sealed() { + +} + +type hlistImpl[H any, T HList] struct { + head H + tail T +} + +func (r hlistImpl[H, T]) Head() H { + return r.head +} + +func (r hlistImpl[H, T]) Tail() T { + return r.tail +} + +func (r hlistImpl[H, T]) String() string { + return fmt.Sprintf("%v :: %v", r.head, r.tail) +} + +func (r hlistImpl[H, T]) sealed() { + +} + +func hlist[H any, T HList](h H, t T) Cons[H, T] { + return hlistImpl[H, T]{h, t} +} + +func Concat[H any, T HList](h H, t T) Cons[H, T] { + return hlist(h, t) +} + +func Empty() Nil { + return Nil{} +} +func Some[T any](v T) Option[T] { + return Option[T]{}.Recover(func() T { + return v + }) +} + +func None[T any]() Option[T] { + return Option[T]{} +} + +func Ap[T, U any](t Option[Func1[T, U]], a Option[T]) Option[U] { + return FlatMap(t, func(f Func1[T, U]) Option[U] { + return Map(a, f) + }) +} + +func Map[T, U any](opt Option[T], f func(v T) U) Option[U] { + return FlatMap(opt, func(v T) Option[U] { + return Some(f(v)) + }) +} + +func FlatMap[T, U any](opt Option[T], fn func(v T) Option[U]) Option[U] { + if opt.IsDefined() { + return fn(opt.Get()) + } + return None[U]() +} + +type ApplicativeFunctor1[H Header[HT], HT, A, R any] struct { + h Option[H] + fn Option[Func1[A, R]] +} + +func (r ApplicativeFunctor1[H, HT, A, R]) ApOption(a Option[A]) Option[R] { + return Ap(r.fn, a) +} + +func (r ApplicativeFunctor1[H, HT, A, R]) Ap(a A) Option[R] { + return r.ApOption(Some(a)) +} + +func Applicative1[A, R any](fn Func1[A, R]) ApplicativeFunctor1[Nil, Nil, A, R] { + return ApplicativeFunctor1[Nil, Nil, A, R]{Some(Empty()), Some(fn)} +} + +type ApplicativeFunctor2[H Header[HT], HT, A1, A2, R any] struct { + h Option[H] + fn Option[Func1[A1, Func1[A2, R]]] +} + +func (r ApplicativeFunctor2[H, HT, A1, A2, R]) ApOption(a Option[A1]) ApplicativeFunctor1[Cons[A1, H], A1, A2, R] { + + nh := FlatMap(r.h, func(hv H) Option[Cons[A1, H]] { + return Map(a, func(av A1) Cons[A1, H] { + return Concat(av, hv) + }) + }) + + return ApplicativeFunctor1[Cons[A1, H], A1, A2, R]{nh, Ap(r.fn, a)} +} +func (r ApplicativeFunctor2[H, HT, A1, A2, R]) Ap(a A1) ApplicativeFunctor1[Cons[A1, H], A1, A2, R] { + + return r.ApOption(Some(a)) +} + +func Applicative2[A1, A2, R any](fn Func2[A1, A2, R]) ApplicativeFunctor2[Nil, Nil, A1, A2, R] { + return ApplicativeFunctor2[Nil, Nil, A1, A2, R]{Some(Empty()), Some(fn.Curried())} +} +func OrdOption[T any](m Ord[T]) Ord[Option[T]] { + return LessFunc[Option[T]](func(t1 Option[T], t2 Option[T]) bool { + if !t1.IsDefined() && !t2.IsDefined() { + return false + } + return Applicative2(m.Less).ApOption(t1).ApOption(t2).OrElse(!t1.IsDefined()) + }) +} + +func Given[T ImplicitOrd]() Ord[T] { + return LessGiven[T]() +} diff --git a/go/test/typeparam/issue50485.dir/main.go b/go/test/typeparam/issue50485.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..7181b937fd6c0ef3676f2e9b1d7e3c42c98a9cda --- /dev/null +++ b/go/test/typeparam/issue50485.dir/main.go @@ -0,0 +1,9 @@ +package main + +import ( + "./a" +) + +func main() { + _ = a.OrdOption(a.Given[int]()) +} diff --git a/go/test/typeparam/issue50486.dir/goerror_fp.go b/go/test/typeparam/issue50486.dir/goerror_fp.go new file mode 100644 index 0000000000000000000000000000000000000000..fec9095f79678f6cb6f91c7fe06d62b84f72c948 --- /dev/null +++ b/go/test/typeparam/issue50486.dir/goerror_fp.go @@ -0,0 +1,75 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package goerror_fp + +type Seq[T any] []T + +func (r Seq[T]) Size() int { + return len(r) +} + +func (r Seq[T]) Append(items ...T) Seq[T] { + tail := Seq[T](items) + ret := make(Seq[T], r.Size()+tail.Size()) + + for i := range r { + ret[i] = r[i] + } + + for i := range tail { + ret[i+r.Size()] = tail[i] + } + + return ret +} + +func (r Seq[T]) Iterator() Iterator[T] { + idx := 0 + + return Iterator[T]{ + IsHasNext: func() bool { + return idx < r.Size() + }, + GetNext: func() T { + ret := r[idx] + idx++ + return ret + }, + } +} + +type Iterator[T any] struct { + IsHasNext func() bool + GetNext func() T +} + +func (r Iterator[T]) ToSeq() Seq[T] { + ret := Seq[T]{} + for r.HasNext() { + ret = append(ret, r.Next()) + } + return ret +} + +func (r Iterator[T]) Map(f func(T) any) Iterator[any] { + return MakeIterator(r.HasNext, func() any { + return f(r.Next()) + }) +} + +func (r Iterator[T]) HasNext() bool { + return r.IsHasNext() +} + +func (r Iterator[T]) Next() T { + return r.GetNext() +} + +func MakeIterator[T any](has func() bool, next func() T) Iterator[T] { + return Iterator[T]{ + IsHasNext: has, + GetNext: next, + } +} diff --git a/go/test/typeparam/issue50486.dir/main.go b/go/test/typeparam/issue50486.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c2c8eea73d7bcc9c2dad20945043caafa25e2d3c --- /dev/null +++ b/go/test/typeparam/issue50486.dir/main.go @@ -0,0 +1,16 @@ +package main + +import fp "./goerror_fp" + +func Fold[A, B any](zero B, a A, f func(B, A) B) B { + return f(zero, a) +} + +func main() { + + var v any = "hello" + Fold(fp.Seq[any]{}, v, func(seq fp.Seq[any], v any) fp.Seq[any] { + return seq.Append(v) + }) + +} diff --git a/go/test/typeparam/issue50552.dir/a.go b/go/test/typeparam/issue50552.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..89b9bcb87775ea5888ede70fadd1f39bbb24f315 --- /dev/null +++ b/go/test/typeparam/issue50552.dir/a.go @@ -0,0 +1,16 @@ +package a + +type Builder[T any] struct{} + +func (r Builder[T]) New() T { + var v T + return v +} + +func (r Builder[T]) New2() T { + return r.New() +} + +func BuildInt() int { + return Builder[int]{}.New() +} diff --git a/go/test/typeparam/issue50552.dir/main.go b/go/test/typeparam/issue50552.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..0ff2ed360877ac251ab957ba77b5beb6973e0c1a --- /dev/null +++ b/go/test/typeparam/issue50552.dir/main.go @@ -0,0 +1,20 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" +) + +func BuildInt() int { + return a.BuildInt() +} + +func main() { + if got, want := BuildInt(), 0; got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } +} diff --git a/go/test/typeparam/issue50561.dir/diameter.go b/go/test/typeparam/issue50561.dir/diameter.go new file mode 100644 index 0000000000000000000000000000000000000000..2bfe92405da520ff78bc5ef3925269ab90d7296f --- /dev/null +++ b/go/test/typeparam/issue50561.dir/diameter.go @@ -0,0 +1,86 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package diameter + +type Runnable interface { + Run() +} + +// RunnableFunc is converter which converts function to Runnable interface +type RunnableFunc func() + +// Run is Runnable.Run +func (r RunnableFunc) Run() { + r() +} + +type Executor interface { + ExecuteUnsafe(runnable Runnable) +} + +type Promise[T any] interface { + Future() Future[T] + Success(value T) bool + Failure(err error) bool + IsCompleted() bool + Complete(result Try[T]) bool +} + +type Future[T any] interface { + OnFailure(cb func(err error), ctx ...Executor) + OnSuccess(cb func(success T), ctx ...Executor) + Foreach(f func(v T), ctx ...Executor) + OnComplete(cb func(try Try[T]), ctx ...Executor) + IsCompleted() bool + // Value() Option[Try[T]] + Failed() Future[error] + Recover(f func(err error) T, ctx ...Executor) Future[T] + RecoverWith(f func(err error) Future[T], ctx ...Executor) Future[T] +} + +type Try[T any] struct { + v *T + err error +} + +func (r Try[T]) IsSuccess() bool { + return r.v != nil +} + +type ByteBuffer struct { + pos int + buf []byte + underflow error +} + +// InboundHandler is extends of uclient.NetInboundHandler +type InboundHandler interface { + OriginHost() string + OriginRealm() string +} + +type transactionID struct { + hopID uint32 + endID uint32 +} + +type roundTripper struct { + promise map[transactionID]Promise[*ByteBuffer] + host string + realm string +} + +func (r *roundTripper) OriginHost() string { + return r.host +} +func (r *roundTripper) OriginRealm() string { + return r.realm +} + +func NewInboundHandler(host string, realm string, productName string) InboundHandler { + ret := &roundTripper{promise: make(map[transactionID]Promise[*ByteBuffer]), host: host, realm: realm} + + return ret +} diff --git a/go/test/typeparam/issue50561.dir/main.go b/go/test/typeparam/issue50561.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3e656bde32dc81d1045700e2bb06fdc66e5190d5 --- /dev/null +++ b/go/test/typeparam/issue50561.dir/main.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./diameter" +) + +func main() { + diameter.NewInboundHandler("hello", "world", "hi") +} diff --git a/go/test/typeparam/issue50598.dir/a0.go b/go/test/typeparam/issue50598.dir/a0.go new file mode 100644 index 0000000000000000000000000000000000000000..61d353e462cd69fb821403344c5a97afe9bc87db --- /dev/null +++ b/go/test/typeparam/issue50598.dir/a0.go @@ -0,0 +1,23 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a0 + +type Builder[T any] struct{} + +func (r Builder[T]) New1() T { + var v T + return v +} + +func (r Builder[T]) New2() T { + var v T + return v +} + +type IntBuilder struct{} + +func (b IntBuilder) New() int { + return Builder[int]{}.New2() +} diff --git a/go/test/typeparam/issue50598.dir/a1.go b/go/test/typeparam/issue50598.dir/a1.go new file mode 100644 index 0000000000000000000000000000000000000000..36624b4bd67ac876b793c513eae0b16d709c8e15 --- /dev/null +++ b/go/test/typeparam/issue50598.dir/a1.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a1 + +import "./a0" + +func New() int { + return a0.IntBuilder{}.New() +} diff --git a/go/test/typeparam/issue50598.dir/a2.go b/go/test/typeparam/issue50598.dir/a2.go new file mode 100644 index 0000000000000000000000000000000000000000..c28be66f6bab288ff603c5eb355b38f0f829d43d --- /dev/null +++ b/go/test/typeparam/issue50598.dir/a2.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a2 + +import "./a0" + +func New() int { + return a0.Builder[int]{}.New1() +} diff --git a/go/test/typeparam/issue50598.dir/main.go b/go/test/typeparam/issue50598.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..b0b6844ccc2858ea6182a208f5b39f8a56ff353f --- /dev/null +++ b/go/test/typeparam/issue50598.dir/main.go @@ -0,0 +1,22 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + + "./a1" + "./a2" +) + +func New() int { + return a1.New() + a2.New() +} + +func main() { + if got, want := New(), 0; got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } +} diff --git a/go/test/typeparam/issue50841.dir/a.go b/go/test/typeparam/issue50841.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..37e023370187e345e031ffba266425ac03c94801 --- /dev/null +++ b/go/test/typeparam/issue50841.dir/a.go @@ -0,0 +1,22 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func Marshal[foobar any]() { + _ = NewEncoder[foobar]() +} + +func NewEncoder[foobar any]() *Encoder[foobar] { + return nil +} + +type Encoder[foobar any] struct { +} + +func (e *Encoder[foobar]) EncodeToken(t Token[foobar]) { + +} + +type Token[foobar any] any diff --git a/go/test/typeparam/issue50841.dir/b.go b/go/test/typeparam/issue50841.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..38e3de3a6bb6aa8970b787da3ab3c9d6b56272b0 --- /dev/null +++ b/go/test/typeparam/issue50841.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func F() { + a.Marshal[int]() +} diff --git a/go/test/typeparam/issue51219.dir/a.go b/go/test/typeparam/issue51219.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..29670df0d3a764eddd6a8fd293aa022bb27c736d --- /dev/null +++ b/go/test/typeparam/issue51219.dir/a.go @@ -0,0 +1,20 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +// Type I is the first basic test for the issue, which relates to a type that is recursive +// via a type constraint. (In this test, I -> IConstraint -> MyStruct -> I.) +type JsonRaw []byte + +type MyStruct struct { + x *I[JsonRaw] +} + +type IConstraint interface { + JsonRaw | MyStruct +} + +type I[T IConstraint] struct { +} diff --git a/go/test/typeparam/issue51219.dir/main.go b/go/test/typeparam/issue51219.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..14c6d179d2b38e32454840da1281c8a7d3252909 --- /dev/null +++ b/go/test/typeparam/issue51219.dir/main.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" +) + +func main() { + var x a.I[a.JsonRaw] + + fmt.Printf("%v\n", x) +} diff --git a/go/test/typeparam/issue51219b.dir/a.go b/go/test/typeparam/issue51219b.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..19049406a6d9e978ed683ae301675372c60641c3 --- /dev/null +++ b/go/test/typeparam/issue51219b.dir/a.go @@ -0,0 +1,37 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Interaction[DataT InteractionDataConstraint] struct { +} + +type InteractionDataConstraint interface { + []byte | + UserCommandInteractionData +} + +type UserCommandInteractionData struct { + resolvedInteractionWithOptions +} + +type resolvedInteractionWithOptions struct { + Resolved Resolved `json:"resolved,omitempty"` +} + +type Resolved struct { + Users ResolvedData[User] `json:"users,omitempty"` +} + +type ResolvedData[T ResolvedDataConstraint] map[uint64]T + +type ResolvedDataConstraint interface { + User | Message +} + +type User struct{} + +type Message struct { + Interaction *Interaction[[]byte] `json:"interaction,omitempty"` +} diff --git a/go/test/typeparam/issue51219b.dir/b.go b/go/test/typeparam/issue51219b.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..8413d666b7e2cd9fce155d9aeedc8897a5443dc2 --- /dev/null +++ b/go/test/typeparam/issue51219b.dir/b.go @@ -0,0 +1,14 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import ( + "./a" +) + +// InteractionRequest is an incoming request Interaction +type InteractionRequest[T a.InteractionDataConstraint] struct { + a.Interaction[T] +} diff --git a/go/test/typeparam/issue51219b.dir/p.go b/go/test/typeparam/issue51219b.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..9f8b840d48b1b748e0771ffedca213bbf83e9219 --- /dev/null +++ b/go/test/typeparam/issue51219b.dir/p.go @@ -0,0 +1,14 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "./b" +) + +// ResponseWriterMock mocks corde's ResponseWriter interface +type ResponseWriterMock struct { + x b.InteractionRequest[[]byte] +} diff --git a/go/test/typeparam/issue51250a.dir/a.go b/go/test/typeparam/issue51250a.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..12dd60a3d16b51630c20805168a77a04908dcfb2 --- /dev/null +++ b/go/test/typeparam/issue51250a.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type G[T any] struct { + x T +} diff --git a/go/test/typeparam/issue51250a.dir/b.go b/go/test/typeparam/issue51250a.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..114c9f80f702f42f04b3e837c592c136465a2ae6 --- /dev/null +++ b/go/test/typeparam/issue51250a.dir/b.go @@ -0,0 +1,24 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +type T struct { a int } + +var I interface{} = a.G[T]{} + +//go:noinline +func F(x interface{}) { + switch x.(type) { + case a.G[T]: + case int: + panic("bad") + case float64: + panic("bad") + default: + panic("bad") + } +} diff --git a/go/test/typeparam/issue51250a.dir/main.go b/go/test/typeparam/issue51250a.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..45288be482679de77f599fe2b94ef5b32dc9a382 --- /dev/null +++ b/go/test/typeparam/issue51250a.dir/main.go @@ -0,0 +1,24 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "./b" +) + +func main() { + switch b.I.(type) { + case a.G[b.T]: + case int: + panic("bad") + case float64: + panic("bad") + default: + panic("bad") + } + + b.F(a.G[b.T]{}) +} diff --git a/go/test/typeparam/issue51367.dir/a.go b/go/test/typeparam/issue51367.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..be0c3b0688bb91e68fdb3484c5f861b128e93a8f --- /dev/null +++ b/go/test/typeparam/issue51367.dir/a.go @@ -0,0 +1,14 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type A[T any] struct{} + +func (_ A[T]) Method() {} + +func DoSomething[P any]() { + a := A[*byte]{} + a.Method() +} diff --git a/go/test/typeparam/issue51367.dir/main.go b/go/test/typeparam/issue51367.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..1de8793d4db0c9c4de77a449a791f6e1675e33da --- /dev/null +++ b/go/test/typeparam/issue51367.dir/main.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" +) + +func main() { + a.DoSomething[byte]() +} diff --git a/go/test/typeparam/issue51423.dir/a.go b/go/test/typeparam/issue51423.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e824d0e1654d604204d9c6500d8a0d56834001e7 --- /dev/null +++ b/go/test/typeparam/issue51423.dir/a.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Comparator[T any] func(v1, v2 T) int + +func CompareInt[T ~int](a, b T) int { + if a < b { + return -1 + } + if a == b { + return 0 + } + return 1 +} diff --git a/go/test/typeparam/issue51423.dir/b.go b/go/test/typeparam/issue51423.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..2bad19fbdac9f62797a88fad53ded351023fe6d5 --- /dev/null +++ b/go/test/typeparam/issue51423.dir/b.go @@ -0,0 +1,11 @@ +package b + +import "./a" + +func C() a.Comparator[int] { + return a.CompareInt[int] +} + +func main() { + _ = C()(1, 2) +} diff --git a/go/test/typeparam/issue51836.dir/a.go b/go/test/typeparam/issue51836.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e9223c9aa8270f1b9b82a23e4fe3340c5882f2e6 --- /dev/null +++ b/go/test/typeparam/issue51836.dir/a.go @@ -0,0 +1,8 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T[K any] struct { +} diff --git a/go/test/typeparam/issue51836.dir/aa.go b/go/test/typeparam/issue51836.dir/aa.go new file mode 100644 index 0000000000000000000000000000000000000000..d774be282e5aa814078fa94af7272cf915cef254 --- /dev/null +++ b/go/test/typeparam/issue51836.dir/aa.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import ( + "./a" +) + +type T[K any] struct { + t a.T[K] +} diff --git a/go/test/typeparam/issue51836.dir/p.go b/go/test/typeparam/issue51836.dir/p.go new file mode 100644 index 0000000000000000000000000000000000000000..98197ae0fd9dac5df2e48a52f19a5de210343f2d --- /dev/null +++ b/go/test/typeparam/issue51836.dir/p.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + a "./aa" +) + +var Foo a.T[int] diff --git a/go/test/typeparam/issue52117.dir/a.go b/go/test/typeparam/issue52117.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e571ea94623cc707777c16ba0578af487e934254 --- /dev/null +++ b/go/test/typeparam/issue52117.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func Compare[T int | uint](a, b T) int { + return 0 +} + +type Slice[T int | uint] struct{} + +func (l Slice[T]) Comparator() func(v1, v2 T) int { + return Compare[T] +} diff --git a/go/test/typeparam/issue52117.dir/b.go b/go/test/typeparam/issue52117.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..3d3bf4ced9e2f8315391f6be2993848520ff2be0 --- /dev/null +++ b/go/test/typeparam/issue52117.dir/b.go @@ -0,0 +1,7 @@ +package b + +import "./a" + +func Test() { + var _ a.Slice[uint] +} diff --git a/go/test/typeparam/issue54302.dir/a.go b/go/test/typeparam/issue54302.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..52875ab5e15808181672567b8e48dd8f2f306c8c --- /dev/null +++ b/go/test/typeparam/issue54302.dir/a.go @@ -0,0 +1,20 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func A() { + B[int](new(G[int])) +} + +func B[T any](iface interface{ M(T) }) { + x, ok := iface.(*G[T]) + if !ok || iface != x { + panic("FAIL") + } +} + +type G[T any] struct{} + +func (*G[T]) M(T) {} diff --git a/go/test/typeparam/issue54302.dir/main.go b/go/test/typeparam/issue54302.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..b4c6cd142dcfc8572371a78c1c916d36d3c8e25b --- /dev/null +++ b/go/test/typeparam/issue54302.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.A() +} diff --git a/go/test/typeparam/listimp.dir/a.go b/go/test/typeparam/listimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..e9c46d6f325b8f7ab4358752faeb327a7ae9bbee --- /dev/null +++ b/go/test/typeparam/listimp.dir/a.go @@ -0,0 +1,53 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Ordered interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 | + ~string +} + +// List is a linked list of ordered values of type T. +type List[T Ordered] struct { + Next *List[T] + Val T +} + +func (l *List[T]) Largest() T { + var max T + for p := l; p != nil; p = p.Next { + if p.Val > max { + max = p.Val + } + } + return max +} + +type OrderedNum interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 +} + +// ListNum is a linked _List of ordered numeric values of type T. +type ListNum[T OrderedNum] struct { + Next *ListNum[T] + Val T +} + +const Clip = 5 + +// ClippedLargest returns the largest in the list of OrderNums, but a max of 5. +func (l *ListNum[T]) ClippedLargest() T { + var max T + for p := l; p != nil; p = p.Next { + if p.Val > max && p.Val < Clip { + max = p.Val + } + } + return max +} diff --git a/go/test/typeparam/listimp.dir/main.go b/go/test/typeparam/listimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..652a34a0828846ef93dc4475f30e5e6b62b7a11f --- /dev/null +++ b/go/test/typeparam/listimp.dir/main.go @@ -0,0 +1,52 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" +) + +func main() { + i3 := &a.List[int]{nil, 1} + i2 := &a.List[int]{i3, 3} + i1 := &a.List[int]{i2, 2} + if got, want := i1.Largest(), 3; got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + b3 := &a.List[byte]{nil, byte(1)} + b2 := &a.List[byte]{b3, byte(3)} + b1 := &a.List[byte]{b2, byte(2)} + if got, want := b1.Largest(), byte(3); got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + f3 := &a.List[float64]{nil, 13.5} + f2 := &a.List[float64]{f3, 1.2} + f1 := &a.List[float64]{f2, 4.5} + if got, want := f1.Largest(), 13.5; got != want { + panic(fmt.Sprintf("got %f, want %f", got, want)) + } + + s3 := &a.List[string]{nil, "dd"} + s2 := &a.List[string]{s3, "aa"} + s1 := &a.List[string]{s2, "bb"} + if got, want := s1.Largest(), "dd"; got != want { + panic(fmt.Sprintf("got %s, want %s", got, want)) + } + j3 := &a.ListNum[int]{nil, 1} + j2 := &a.ListNum[int]{j3, 32} + j1 := &a.ListNum[int]{j2, 2} + if got, want := j1.ClippedLargest(), 2; got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + g3 := &a.ListNum[float64]{nil, 13.5} + g2 := &a.ListNum[float64]{g3, 1.2} + g1 := &a.ListNum[float64]{g2, 4.5} + if got, want := g1.ClippedLargest(), 4.5; got != want { + panic(fmt.Sprintf("got %f, want %f", got, want)) + } +} diff --git a/go/test/typeparam/listimp2.dir/a.go b/go/test/typeparam/listimp2.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3a7dfc3999a0db856c877a5cc2c4f21c899e801c --- /dev/null +++ b/go/test/typeparam/listimp2.dir/a.go @@ -0,0 +1,298 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import ( + "fmt" +) + +// Element is an element of a linked list. +type Element[T any] struct { + // Next and previous pointers in the doubly-linked list of elements. + // To simplify the implementation, internally a list l is implemented + // as a ring, such that &l.root is both the next element of the last + // list element (l.Back()) and the previous element of the first list + // element (l.Front()). + next, prev *Element[T] + + // The list to which this element belongs. + list *List[T] + + // The value stored with this element. + Value T +} + +// Next returns the next list element or nil. +func (e *Element[T]) Next() *Element[T] { + if p := e.next; e.list != nil && p != &e.list.root { + return p + } + return nil +} + +// Prev returns the previous list element or nil. +func (e *Element[T]) Prev() *Element[T] { + if p := e.prev; e.list != nil && p != &e.list.root { + return p + } + return nil +} + +// List represents a doubly linked list. +// The zero value for List is an empty list ready to use. +type List[T any] struct { + root Element[T] // sentinel list element, only &root, root.prev, and root.next are used + len int // current list length excluding (this) sentinel element +} + +// Init initializes or clears list l. +func (l *List[T]) Init() *List[T] { + l.root.next = &l.root + l.root.prev = &l.root + l.len = 0 + return l +} + +// New returns an initialized list. +func New[T any]() *List[T] { return new(List[T]).Init() } + +// Len returns the number of elements of list l. +// The complexity is O(1). +func (l *List[_]) Len() int { return l.len } + +// Front returns the first element of list l or nil if the list is empty. +func (l *List[T]) Front() *Element[T] { + if l.len == 0 { + return nil + } + return l.root.next +} + +// Back returns the last element of list l or nil if the list is empty. +func (l *List[T]) Back() *Element[T] { + if l.len == 0 { + return nil + } + return l.root.prev +} + +// lazyInit lazily initializes a zero List value. +func (l *List[_]) lazyInit() { + if l.root.next == nil { + l.Init() + } +} + +// insert inserts e after at, increments l.len, and returns e. +func (l *List[T]) insert(e, at *Element[T]) *Element[T] { + e.prev = at + e.next = at.next + e.prev.next = e + e.next.prev = e + e.list = l + l.len++ + return e +} + +// insertValue is a convenience wrapper for insert(&Element[T]{Value: v}, at). +func (l *List[T]) insertValue(v T, at *Element[T]) *Element[T] { + return l.insert(&Element[T]{Value: v}, at) +} + +// remove removes e from its list, decrements l.len, and returns e. +func (l *List[T]) remove(e *Element[T]) *Element[T] { + e.prev.next = e.next + e.next.prev = e.prev + e.next = nil // avoid memory leaks + e.prev = nil // avoid memory leaks + e.list = nil + l.len-- + return e +} + +// move moves e to next to at and returns e. +func (l *List[T]) move(e, at *Element[T]) *Element[T] { + if e == at { + return e + } + e.prev.next = e.next + e.next.prev = e.prev + + e.prev = at + e.next = at.next + e.prev.next = e + e.next.prev = e + + return e +} + +// Remove removes e from l if e is an element of list l. +// It returns the element value e.Value. +// The element must not be nil. +func (l *List[T]) Remove(e *Element[T]) T { + if e.list == l { + // if e.list == l, l must have been initialized when e was inserted + // in l or l == nil (e is a zero Element) and l.remove will crash + l.remove(e) + } + return e.Value +} + +// PushFront inserts a new element e with value v at the front of list l and returns e. +func (l *List[T]) PushFront(v T) *Element[T] { + l.lazyInit() + return l.insertValue(v, &l.root) +} + +// PushBack inserts a new element e with value v at the back of list l and returns e. +func (l *List[T]) PushBack(v T) *Element[T] { + l.lazyInit() + return l.insertValue(v, l.root.prev) +} + +// InsertBefore inserts a new element e with value v immediately before mark and returns e. +// If mark is not an element of l, the list is not modified. +// The mark must not be nil. +func (l *List[T]) InsertBefore(v T, mark *Element[T]) *Element[T] { + if mark.list != l { + return nil + } + // see comment in List.Remove about initialization of l + return l.insertValue(v, mark.prev) +} + +// InsertAfter inserts a new element e with value v immediately after mark and returns e. +// If mark is not an element of l, the list is not modified. +// The mark must not be nil. +func (l *List[T]) InsertAfter(v T, mark *Element[T]) *Element[T] { + if mark.list != l { + return nil + } + // see comment in List.Remove about initialization of l + return l.insertValue(v, mark) +} + +// MoveToFront moves element e to the front of list l. +// If e is not an element of l, the list is not modified. +// The element must not be nil. +func (l *List[T]) MoveToFront(e *Element[T]) { + if e.list != l || l.root.next == e { + return + } + // see comment in List.Remove about initialization of l + l.move(e, &l.root) +} + +// MoveToBack moves element e to the back of list l. +// If e is not an element of l, the list is not modified. +// The element must not be nil. +func (l *List[T]) MoveToBack(e *Element[T]) { + if e.list != l || l.root.prev == e { + return + } + // see comment in List.Remove about initialization of l + l.move(e, l.root.prev) +} + +// MoveBefore moves element e to its new position before mark. +// If e or mark is not an element of l, or e == mark, the list is not modified. +// The element and mark must not be nil. +func (l *List[T]) MoveBefore(e, mark *Element[T]) { + if e.list != l || e == mark || mark.list != l { + return + } + l.move(e, mark.prev) +} + +// MoveAfter moves element e to its new position after mark. +// If e or mark is not an element of l, or e == mark, the list is not modified. +// The element and mark must not be nil. +func (l *List[T]) MoveAfter(e, mark *Element[T]) { + if e.list != l || e == mark || mark.list != l { + return + } + l.move(e, mark) +} + +// PushBackList inserts a copy of an other list at the back of list l. +// The lists l and other may be the same. They must not be nil. +func (l *List[T]) PushBackList(other *List[T]) { + l.lazyInit() + for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() { + l.insertValue(e.Value, l.root.prev) + } +} + +// PushFrontList inserts a copy of an other list at the front of list l. +// The lists l and other may be the same. They must not be nil. +func (l *List[T]) PushFrontList(other *List[T]) { + l.lazyInit() + for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() { + l.insertValue(e.Value, &l.root) + } +} + +// Transform runs a transform function on a list returning a new list. +func Transform[TElem1, TElem2 any](lst *List[TElem1], f func(TElem1) TElem2) *List[TElem2] { + ret := New[TElem2]() + for p := lst.Front(); p != nil; p = p.Next() { + ret.PushBack(f(p.Value)) + } + return ret +} + +func CheckListLen[T any](l *List[T], len int) bool { + if n := l.Len(); n != len { + panic(fmt.Sprintf("l.Len() = %d, want %d", n, len)) + return false + } + return true +} + +func CheckListPointers[T any](l *List[T], es []*Element[T]) { + root := &l.root + + if !CheckListLen(l, len(es)) { + return + } + + // zero length lists must be the zero value or properly initialized (sentinel circle) + if len(es) == 0 { + if l.root.next != nil && l.root.next != root || l.root.prev != nil && l.root.prev != root { + panic(fmt.Sprintf("l.root.next = %p, l.root.prev = %p; both should both be nil or %p", l.root.next, l.root.prev, root)) + } + return + } + // len(es) > 0 + + // check internal and external prev/next connections + for i, e := range es { + prev := root + Prev := (*Element[T])(nil) + if i > 0 { + prev = es[i-1] + Prev = prev + } + if p := e.prev; p != prev { + panic(fmt.Sprintf("elt[%d](%p).prev = %p, want %p", i, e, p, prev)) + } + if p := e.Prev(); p != Prev { + panic(fmt.Sprintf("elt[%d](%p).Prev() = %p, want %p", i, e, p, Prev)) + } + + next := root + Next := (*Element[T])(nil) + if i < len(es)-1 { + next = es[i+1] + Next = next + } + if n := e.next; n != next { + panic(fmt.Sprintf("elt[%d](%p).next = %p, want %p", i, e, n, next)) + } + if n := e.Next(); n != Next { + panic(fmt.Sprintf("elt[%d](%p).Next() = %p, want %p", i, e, n, Next)) + } + } +} diff --git a/go/test/typeparam/listimp2.dir/main.go b/go/test/typeparam/listimp2.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c3b936eada0033ffaecd6c832658f069d8d21357 --- /dev/null +++ b/go/test/typeparam/listimp2.dir/main.go @@ -0,0 +1,315 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" + "strconv" +) + +func TestList() { + l := a.New[string]() + a.CheckListPointers(l, []*(a.Element[string]){}) + + // Single element list + e := l.PushFront("a") + a.CheckListPointers(l, []*(a.Element[string]){e}) + l.MoveToFront(e) + a.CheckListPointers(l, []*(a.Element[string]){e}) + l.MoveToBack(e) + a.CheckListPointers(l, []*(a.Element[string]){e}) + l.Remove(e) + a.CheckListPointers(l, []*(a.Element[string]){}) + + // Bigger list + l2 := a.New[int]() + e2 := l2.PushFront(2) + e1 := l2.PushFront(1) + e3 := l2.PushBack(3) + e4 := l2.PushBack(600) + a.CheckListPointers(l2, []*(a.Element[int]){e1, e2, e3, e4}) + + l2.Remove(e2) + a.CheckListPointers(l2, []*(a.Element[int]){e1, e3, e4}) + + l2.MoveToFront(e3) // move from middle + a.CheckListPointers(l2, []*(a.Element[int]){e3, e1, e4}) + + l2.MoveToFront(e1) + l2.MoveToBack(e3) // move from middle + a.CheckListPointers(l2, []*(a.Element[int]){e1, e4, e3}) + + l2.MoveToFront(e3) // move from back + a.CheckListPointers(l2, []*(a.Element[int]){e3, e1, e4}) + l2.MoveToFront(e3) // should be no-op + a.CheckListPointers(l2, []*(a.Element[int]){e3, e1, e4}) + + l2.MoveToBack(e3) // move from front + a.CheckListPointers(l2, []*(a.Element[int]){e1, e4, e3}) + l2.MoveToBack(e3) // should be no-op + a.CheckListPointers(l2, []*(a.Element[int]){e1, e4, e3}) + + e2 = l2.InsertBefore(2, e1) // insert before front + a.CheckListPointers(l2, []*(a.Element[int]){e2, e1, e4, e3}) + l2.Remove(e2) + e2 = l2.InsertBefore(2, e4) // insert before middle + a.CheckListPointers(l2, []*(a.Element[int]){e1, e2, e4, e3}) + l2.Remove(e2) + e2 = l2.InsertBefore(2, e3) // insert before back + a.CheckListPointers(l2, []*(a.Element[int]){e1, e4, e2, e3}) + l2.Remove(e2) + + e2 = l2.InsertAfter(2, e1) // insert after front + a.CheckListPointers(l2, []*(a.Element[int]){e1, e2, e4, e3}) + l2.Remove(e2) + e2 = l2.InsertAfter(2, e4) // insert after middle + a.CheckListPointers(l2, []*(a.Element[int]){e1, e4, e2, e3}) + l2.Remove(e2) + e2 = l2.InsertAfter(2, e3) // insert after back + a.CheckListPointers(l2, []*(a.Element[int]){e1, e4, e3, e2}) + l2.Remove(e2) + + // Check standard iteration. + sum := 0 + for e := l2.Front(); e != nil; e = e.Next() { + sum += e.Value + } + if sum != 604 { + panic(fmt.Sprintf("sum over l = %d, want 604", sum)) + } + + // Clear all elements by iterating + var next *a.Element[int] + for e := l2.Front(); e != nil; e = next { + next = e.Next() + l2.Remove(e) + } + a.CheckListPointers(l2, []*(a.Element[int]){}) +} + +func checkList[T comparable](l *a.List[T], es []interface{}) { + if !a.CheckListLen(l, len(es)) { + return + } + + i := 0 + for e := l.Front(); e != nil; e = e.Next() { + le := e.Value + // Comparison between a generically-typed variable le and an interface. + if le != es[i] { + panic(fmt.Sprintf("elt[%d].Value = %v, want %v", i, le, es[i])) + } + i++ + } +} + +func TestExtending() { + l1 := a.New[int]() + l2 := a.New[int]() + + l1.PushBack(1) + l1.PushBack(2) + l1.PushBack(3) + + l2.PushBack(4) + l2.PushBack(5) + + l3 := a.New[int]() + l3.PushBackList(l1) + checkList(l3, []interface{}{1, 2, 3}) + l3.PushBackList(l2) + checkList(l3, []interface{}{1, 2, 3, 4, 5}) + + l3 = a.New[int]() + l3.PushFrontList(l2) + checkList(l3, []interface{}{4, 5}) + l3.PushFrontList(l1) + checkList(l3, []interface{}{1, 2, 3, 4, 5}) + + checkList(l1, []interface{}{1, 2, 3}) + checkList(l2, []interface{}{4, 5}) + + l3 = a.New[int]() + l3.PushBackList(l1) + checkList(l3, []interface{}{1, 2, 3}) + l3.PushBackList(l3) + checkList(l3, []interface{}{1, 2, 3, 1, 2, 3}) + + l3 = a.New[int]() + l3.PushFrontList(l1) + checkList(l3, []interface{}{1, 2, 3}) + l3.PushFrontList(l3) + checkList(l3, []interface{}{1, 2, 3, 1, 2, 3}) + + l3 = a.New[int]() + l1.PushBackList(l3) + checkList(l1, []interface{}{1, 2, 3}) + l1.PushFrontList(l3) + checkList(l1, []interface{}{1, 2, 3}) +} + +func TestRemove() { + l := a.New[int]() + e1 := l.PushBack(1) + e2 := l.PushBack(2) + a.CheckListPointers(l, []*(a.Element[int]){e1, e2}) + e := l.Front() + l.Remove(e) + a.CheckListPointers(l, []*(a.Element[int]){e2}) + l.Remove(e) + a.CheckListPointers(l, []*(a.Element[int]){e2}) +} + +func TestIssue4103() { + l1 := a.New[int]() + l1.PushBack(1) + l1.PushBack(2) + + l2 := a.New[int]() + l2.PushBack(3) + l2.PushBack(4) + + e := l1.Front() + l2.Remove(e) // l2 should not change because e is not an element of l2 + if n := l2.Len(); n != 2 { + panic(fmt.Sprintf("l2.Len() = %d, want 2", n)) + } + + l1.InsertBefore(8, e) + if n := l1.Len(); n != 3 { + panic(fmt.Sprintf("l1.Len() = %d, want 3", n)) + } +} + +func TestIssue6349() { + l := a.New[int]() + l.PushBack(1) + l.PushBack(2) + + e := l.Front() + l.Remove(e) + if e.Value != 1 { + panic(fmt.Sprintf("e.value = %d, want 1", e.Value)) + } + if e.Next() != nil { + panic(fmt.Sprintf("e.Next() != nil")) + } + if e.Prev() != nil { + panic(fmt.Sprintf("e.Prev() != nil")) + } +} + +func TestMove() { + l := a.New[int]() + e1 := l.PushBack(1) + e2 := l.PushBack(2) + e3 := l.PushBack(3) + e4 := l.PushBack(4) + + l.MoveAfter(e3, e3) + a.CheckListPointers(l, []*(a.Element[int]){e1, e2, e3, e4}) + l.MoveBefore(e2, e2) + a.CheckListPointers(l, []*(a.Element[int]){e1, e2, e3, e4}) + + l.MoveAfter(e3, e2) + a.CheckListPointers(l, []*(a.Element[int]){e1, e2, e3, e4}) + l.MoveBefore(e2, e3) + a.CheckListPointers(l, []*(a.Element[int]){e1, e2, e3, e4}) + + l.MoveBefore(e2, e4) + a.CheckListPointers(l, []*(a.Element[int]){e1, e3, e2, e4}) + e2, e3 = e3, e2 + + l.MoveBefore(e4, e1) + a.CheckListPointers(l, []*(a.Element[int]){e4, e1, e2, e3}) + e1, e2, e3, e4 = e4, e1, e2, e3 + + l.MoveAfter(e4, e1) + a.CheckListPointers(l, []*(a.Element[int]){e1, e4, e2, e3}) + e2, e3, e4 = e4, e2, e3 + + l.MoveAfter(e2, e3) + a.CheckListPointers(l, []*(a.Element[int]){e1, e3, e2, e4}) + e2, e3 = e3, e2 +} + +// Test PushFront, PushBack, PushFrontList, PushBackList with uninitialized a.List +func TestZeroList() { + var l1 = new(a.List[int]) + l1.PushFront(1) + checkList(l1, []interface{}{1}) + + var l2 = new(a.List[int]) + l2.PushBack(1) + checkList(l2, []interface{}{1}) + + var l3 = new(a.List[int]) + l3.PushFrontList(l1) + checkList(l3, []interface{}{1}) + + var l4 = new(a.List[int]) + l4.PushBackList(l2) + checkList(l4, []interface{}{1}) +} + +// Test that a list l is not modified when calling InsertBefore with a mark that is not an element of l. +func TestInsertBeforeUnknownMark() { + var l a.List[int] + l.PushBack(1) + l.PushBack(2) + l.PushBack(3) + l.InsertBefore(1, new(a.Element[int])) + checkList(&l, []interface{}{1, 2, 3}) +} + +// Test that a list l is not modified when calling InsertAfter with a mark that is not an element of l. +func TestInsertAfterUnknownMark() { + var l a.List[int] + l.PushBack(1) + l.PushBack(2) + l.PushBack(3) + l.InsertAfter(1, new(a.Element[int])) + checkList(&l, []interface{}{1, 2, 3}) +} + +// Test that a list l is not modified when calling MoveAfter or MoveBefore with a mark that is not an element of l. +func TestMoveUnknownMark() { + var l1 a.List[int] + e1 := l1.PushBack(1) + + var l2 a.List[int] + e2 := l2.PushBack(2) + + l1.MoveAfter(e1, e2) + checkList(&l1, []interface{}{1}) + checkList(&l2, []interface{}{2}) + + l1.MoveBefore(e1, e2) + checkList(&l1, []interface{}{1}) + checkList(&l2, []interface{}{2}) +} + +// Test the Transform function. +func TestTransform() { + l1 := a.New[int]() + l1.PushBack(1) + l1.PushBack(2) + l2 := a.Transform(l1, strconv.Itoa) + checkList(l2, []interface{}{"1", "2"}) +} + +func main() { + TestList() + TestExtending() + TestRemove() + TestIssue4103() + TestIssue6349() + TestMove() + TestZeroList() + TestInsertBeforeUnknownMark() + TestInsertAfterUnknownMark() + TestTransform() +} diff --git a/go/test/typeparam/mapimp.dir/a.go b/go/test/typeparam/mapimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..cbfa80ac6b1d338bf40a4d6c76da0f3f419c60b2 --- /dev/null +++ b/go/test/typeparam/mapimp.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +// Map calls the function f on every element of the slice s, +// returning a new slice of the results. +func Mapper[F, T any](s []F, f func(F) T) []T { + r := make([]T, len(s)) + for i, v := range s { + r[i] = f(v) + } + return r +} diff --git a/go/test/typeparam/mapimp.dir/main.go b/go/test/typeparam/mapimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8a56ce2bfb391f7e48938eb574fd1ce0a3644b76 --- /dev/null +++ b/go/test/typeparam/mapimp.dir/main.go @@ -0,0 +1,28 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" + "reflect" + "strconv" +) + +func main() { + got := a.Mapper([]int{1, 2, 3}, strconv.Itoa) + want := []string{"1", "2", "3"} + if !reflect.DeepEqual(got, want) { + panic(fmt.Sprintf("got %s, want %s", got, want)) + } + + fgot := a.Mapper([]float64{2.5, 2.3, 3.5}, func(f float64) string { + return strconv.FormatFloat(f, 'f', -1, 64) + }) + fwant := []string{"2.5", "2.3", "3.5"} + if !reflect.DeepEqual(fgot, fwant) { + panic(fmt.Sprintf("got %s, want %s", fgot, fwant)) + } +} diff --git a/go/test/typeparam/mapsimp.dir/a.go b/go/test/typeparam/mapsimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..696e2a568014a9b0edb23cb9438557d2e2914526 --- /dev/null +++ b/go/test/typeparam/mapsimp.dir/a.go @@ -0,0 +1,108 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +// SliceEqual reports whether two slices are equal: the same length and all +// elements equal. All floating point NaNs are considered equal. +func SliceEqual[Elem comparable](s1, s2 []Elem) bool { + if len(s1) != len(s2) { + return false + } + for i, v1 := range s1 { + v2 := s2[i] + if v1 != v2 { + isNaN := func(f Elem) bool { return f != f } + if !isNaN(v1) || !isNaN(v2) { + return false + } + } + } + return true +} + +// Keys returns the keys of the map m. +// The keys will be an indeterminate order. +func Keys[K comparable, V any](m map[K]V) []K { + r := make([]K, 0, len(m)) + for k := range m { + r = append(r, k) + } + return r +} + +// Values returns the values of the map m. +// The values will be in an indeterminate order. +func Values[K comparable, V any](m map[K]V) []V { + r := make([]V, 0, len(m)) + for _, v := range m { + r = append(r, v) + } + return r +} + +// Equal reports whether two maps contain the same key/value pairs. +// Values are compared using ==. +func Equal[K, V comparable](m1, m2 map[K]V) bool { + if len(m1) != len(m2) { + return false + } + for k, v1 := range m1 { + if v2, ok := m2[k]; !ok || v1 != v2 { + return false + } + } + return true +} + +// Copy returns a copy of m. +func Copy[K comparable, V any](m map[K]V) map[K]V { + r := make(map[K]V, len(m)) + for k, v := range m { + r[k] = v + } + return r +} + +// Add adds all key/value pairs in m2 to m1. Keys in m2 that are already +// present in m1 will be overwritten with the value in m2. +func Add[K comparable, V any](m1, m2 map[K]V) { + for k, v := range m2 { + m1[k] = v + } +} + +// Sub removes all keys in m2 from m1. Keys in m2 that are not present +// in m1 are ignored. The values in m2 are ignored. +func Sub[K comparable, V any](m1, m2 map[K]V) { + for k := range m2 { + delete(m1, k) + } +} + +// Intersect removes all keys from m1 that are not present in m2. +// Keys in m2 that are not in m1 are ignored. The values in m2 are ignored. +func Intersect[K comparable, V any](m1, m2 map[K]V) { + for k := range m1 { + if _, ok := m2[k]; !ok { + delete(m1, k) + } + } +} + +// Filter deletes any key/value pairs from m for which f returns false. +func Filter[K comparable, V any](m map[K]V, f func(K, V) bool) { + for k, v := range m { + if !f(k, v) { + delete(m, k) + } + } +} + +// TransformValues applies f to each value in m. The keys remain unchanged. +func TransformValues[K comparable, V any](m map[K]V, f func(V) V) { + for k, v := range m { + m[k] = f(v) + } +} diff --git a/go/test/typeparam/mapsimp.dir/main.go b/go/test/typeparam/mapsimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..45f7d39f931e009444e51f1e14728930b407d9cf --- /dev/null +++ b/go/test/typeparam/mapsimp.dir/main.go @@ -0,0 +1,156 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" + "math" + "sort" +) + +var m1 = map[int]int{1: 2, 2: 4, 4: 8, 8: 16} +var m2 = map[int]string{1: "2", 2: "4", 4: "8", 8: "16"} + +func TestKeys() { + want := []int{1, 2, 4, 8} + + got1 := a.Keys(m1) + sort.Ints(got1) + if !a.SliceEqual(got1, want) { + panic(fmt.Sprintf("a.Keys(%v) = %v, want %v", m1, got1, want)) + } + + got2 := a.Keys(m2) + sort.Ints(got2) + if !a.SliceEqual(got2, want) { + panic(fmt.Sprintf("a.Keys(%v) = %v, want %v", m2, got2, want)) + } +} + +func TestValues() { + got1 := a.Values(m1) + want1 := []int{2, 4, 8, 16} + sort.Ints(got1) + if !a.SliceEqual(got1, want1) { + panic(fmt.Sprintf("a.Values(%v) = %v, want %v", m1, got1, want1)) + } + + got2 := a.Values(m2) + want2 := []string{"16", "2", "4", "8"} + sort.Strings(got2) + if !a.SliceEqual(got2, want2) { + panic(fmt.Sprintf("a.Values(%v) = %v, want %v", m2, got2, want2)) + } +} + +func TestEqual() { + if !a.Equal(m1, m1) { + panic(fmt.Sprintf("a.Equal(%v, %v) = false, want true", m1, m1)) + } + if a.Equal(m1, nil) { + panic(fmt.Sprintf("a.Equal(%v, nil) = true, want false", m1)) + } + if a.Equal(nil, m1) { + panic(fmt.Sprintf("a.Equal(nil, %v) = true, want false", m1)) + } + if !a.Equal[int, int](nil, nil) { + panic("a.Equal(nil, nil) = false, want true") + } + if ms := map[int]int{1: 2}; a.Equal(m1, ms) { + panic(fmt.Sprintf("a.Equal(%v, %v) = true, want false", m1, ms)) + } + + // Comparing NaN for equality is expected to fail. + mf := map[int]float64{1: 0, 2: math.NaN()} + if a.Equal(mf, mf) { + panic(fmt.Sprintf("a.Equal(%v, %v) = true, want false", mf, mf)) + } +} + +func TestCopy() { + m2 := a.Copy(m1) + if !a.Equal(m1, m2) { + panic(fmt.Sprintf("a.Copy(%v) = %v, want %v", m1, m2, m1)) + } + m2[16] = 32 + if a.Equal(m1, m2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = true, want false", m1, m2)) + } +} + +func TestAdd() { + mc := a.Copy(m1) + a.Add(mc, mc) + if !a.Equal(mc, m1) { + panic(fmt.Sprintf("a.Add(%v, %v) = %v, want %v", m1, m1, mc, m1)) + } + a.Add(mc, map[int]int{16: 32}) + want := map[int]int{1: 2, 2: 4, 4: 8, 8: 16, 16: 32} + if !a.Equal(mc, want) { + panic(fmt.Sprintf("a.Add result = %v, want %v", mc, want)) + } +} + +func TestSub() { + mc := a.Copy(m1) + a.Sub(mc, mc) + if len(mc) > 0 { + panic(fmt.Sprintf("a.Sub(%v, %v) = %v, want empty map", m1, m1, mc)) + } + mc = a.Copy(m1) + a.Sub(mc, map[int]int{1: 0}) + want := map[int]int{2: 4, 4: 8, 8: 16} + if !a.Equal(mc, want) { + panic(fmt.Sprintf("a.Sub result = %v, want %v", mc, want)) + } +} + +func TestIntersect() { + mc := a.Copy(m1) + a.Intersect(mc, mc) + if !a.Equal(mc, m1) { + panic(fmt.Sprintf("a.Intersect(%v, %v) = %v, want %v", m1, m1, mc, m1)) + } + a.Intersect(mc, map[int]int{1: 0, 2: 0}) + want := map[int]int{1: 2, 2: 4} + if !a.Equal(mc, want) { + panic(fmt.Sprintf("a.Intersect result = %v, want %v", mc, want)) + } +} + +func TestFilter() { + mc := a.Copy(m1) + a.Filter(mc, func(int, int) bool { return true }) + if !a.Equal(mc, m1) { + panic(fmt.Sprintf("a.Filter(%v, true) = %v, want %v", m1, mc, m1)) + } + a.Filter(mc, func(k, v int) bool { return k < 3 }) + want := map[int]int{1: 2, 2: 4} + if !a.Equal(mc, want) { + panic(fmt.Sprintf("a.Filter result = %v, want %v", mc, want)) + } +} + +func TestTransformValues() { + mc := a.Copy(m1) + a.TransformValues(mc, func(i int) int { return i / 2 }) + want := map[int]int{1: 1, 2: 2, 4: 4, 8: 8} + if !a.Equal(mc, want) { + panic(fmt.Sprintf("a.TransformValues result = %v, want %v", mc, want)) + } +} + +func main() { + TestKeys() + TestValues() + TestEqual() + TestCopy() + TestAdd() + TestSub() + TestIntersect() + TestFilter() + TestTransformValues() +} diff --git a/go/test/typeparam/mdempsky/1.dir/a.go b/go/test/typeparam/mdempsky/1.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..a668eb52dc9dc13d0457e3a8ed3a8049cefac904 --- /dev/null +++ b/go/test/typeparam/mdempsky/1.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type T[_ any] int + +func F() { _ = new(T[int]) } diff --git a/go/test/typeparam/mdempsky/1.dir/b.go b/go/test/typeparam/mdempsky/1.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..af6fef3f6d8bad40de56f7c1803ef5990191abc7 --- /dev/null +++ b/go/test/typeparam/mdempsky/1.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { a.F() } diff --git a/go/test/typeparam/mdempsky/1.go b/go/test/typeparam/mdempsky/1.go new file mode 100644 index 0000000000000000000000000000000000000000..b83fbd7af16a576c16e0fc73b84f1ca0f618b756 --- /dev/null +++ b/go/test/typeparam/mdempsky/1.go @@ -0,0 +1,7 @@ +// compiledir + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ignored diff --git a/go/test/typeparam/mdempsky/10.dir/a.go b/go/test/typeparam/mdempsky/10.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..95e111d3470a1a7259d398b3d68ec26f70b6ed65 --- /dev/null +++ b/go/test/typeparam/mdempsky/10.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I[T any] interface{ M() T } diff --git a/go/test/typeparam/mdempsky/10.dir/b.go b/go/test/typeparam/mdempsky/10.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..0ef28fd02de3282e61ce2ebb2b0278db1ee4d9f3 --- /dev/null +++ b/go/test/typeparam/mdempsky/10.dir/b.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +var m = a.I[int].M + +var never bool + +func main() { + if never { + m(nil) + } +} diff --git a/go/test/typeparam/mdempsky/10.go b/go/test/typeparam/mdempsky/10.go new file mode 100644 index 0000000000000000000000000000000000000000..40df49f83bef07a3f4c5d8fd4000d97484c3f224 --- /dev/null +++ b/go/test/typeparam/mdempsky/10.go @@ -0,0 +1,7 @@ +// rundir + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ignored diff --git a/go/test/typeparam/mdempsky/12.dir/a.go b/go/test/typeparam/mdempsky/12.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..ee8be939a8fadd5985e56a491ae2d3e19928ef11 --- /dev/null +++ b/go/test/typeparam/mdempsky/12.dir/a.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type S[T any] struct { + F T +} + +var X = S[int]{} diff --git a/go/test/typeparam/mdempsky/12.dir/main.go b/go/test/typeparam/mdempsky/12.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2891322e298867275828c331830fa8bbd3fda114 --- /dev/null +++ b/go/test/typeparam/mdempsky/12.dir/main.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" +) + +func main() { + _ = a.X +} diff --git a/go/test/typeparam/mdempsky/12.go b/go/test/typeparam/mdempsky/12.go new file mode 100644 index 0000000000000000000000000000000000000000..0316402a78d0de8f3090a30064ebf2f543c68171 --- /dev/null +++ b/go/test/typeparam/mdempsky/12.go @@ -0,0 +1,9 @@ +// rundir + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Reported by Cuong Manh Le. + +package ignored diff --git a/go/test/typeparam/mdempsky/13.go b/go/test/typeparam/mdempsky/13.go new file mode 100644 index 0000000000000000000000000000000000000000..8e11352b5148407f2f857bc2a836fca7d5192f3c --- /dev/null +++ b/go/test/typeparam/mdempsky/13.go @@ -0,0 +1,84 @@ +// run + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +// Interface which will be used as a regular interface type and as a type bound. +type Mer interface{ + M() +} + +// Interface that is a superset of Mer. +type Mer2 interface { + M() + String() string +} + +func F[T Mer](t T) { + T.M(t) + t.M() +} + +type MyMer int + +func (MyMer) M() {} +func (MyMer) String() string { + return "aa" +} + +// Parameterized interface +type Abs[T any] interface { + Abs() T +} + +func G[T Abs[U], U any](t T) { + T.Abs(t) + t.Abs() +} + +type MyInt int +func (m MyInt) Abs() MyInt { + if m < 0 { + return -m + } + return m +} + +type Abs2 interface { + Abs() MyInt +} + + +func main() { + mm := MyMer(3) + ms := struct{ Mer }{Mer: mm } + + // Testing F with an interface type arg: Mer and Mer2 + F[Mer](mm) + F[Mer2](mm) + F[struct{ Mer }](ms) + F[*struct{ Mer }](&ms) + + ms2 := struct { MyMer }{MyMer: mm} + ms3 := struct { *MyMer }{MyMer: &mm} + + // Testing F with a concrete type arg + F[MyMer](mm) + F[*MyMer](&mm) + F[struct{ MyMer }](ms2) + F[struct{ *MyMer }](ms3) + F[*struct{ MyMer }](&ms2) + F[*struct{ *MyMer }](&ms3) + + // Testing G with a concrete type args + mi := MyInt(-3) + G[MyInt,MyInt](mi) + + // Interface Abs[MyInt] holding an mi. + intMi := Abs[MyInt](mi) + // First type arg here is Abs[MyInt], an interface type. + G[Abs[MyInt],MyInt](intMi) +} diff --git a/go/test/typeparam/mdempsky/14.go b/go/test/typeparam/mdempsky/14.go new file mode 100644 index 0000000000000000000000000000000000000000..4af990c49a4a1f5bd3fc055bda84ce258dc7cdb6 --- /dev/null +++ b/go/test/typeparam/mdempsky/14.go @@ -0,0 +1,40 @@ +// run + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +// Zero returns the zero value of T +func Zero[T any]() (_ T) { + return +} + +type AnyInt[X any] int + +func (AnyInt[X]) M() { + var have interface{} = Zero[X]() + var want interface{} = Zero[MyInt]() + + if have != want { + println("FAIL") + } +} + +type I interface{ M() } + +type MyInt int +type U = AnyInt[MyInt] + +var x = U(0) +var i I = x + +func main() { + x.M() + U.M(x) + (*U).M(&x) + + i.M() + I.M(x) +} diff --git a/go/test/typeparam/mdempsky/15.go b/go/test/typeparam/mdempsky/15.go new file mode 100644 index 0000000000000000000000000000000000000000..b03ad6f21048404f917fa8960b004757360314ee --- /dev/null +++ b/go/test/typeparam/mdempsky/15.go @@ -0,0 +1,69 @@ +// run -goexperiment fieldtrack + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that generics, promoted methods, and //go:nointerface +// interoperate as expected. + +package main + +import ( + "reflect" +) + +func TypeString[T any]() string { + return reflect.TypeOf(new(T)).Elem().String() +} + +func Test[T, Bad, Good any]() { + switch interface{}(new(T)).(type) { + case Bad: + println("FAIL:", TypeString[T](), "matched", TypeString[Bad]()) + case Good: + // ok + default: + println("FAIL:", TypeString[T](), "did not match", TypeString[Good]()) + } +} + +func TestE[T any]() { Test[T, interface{ EBad() }, interface{ EGood() }]() } +func TestX[T any]() { Test[T, interface{ XBad() }, interface{ XGood() }]() } + +type E struct{} + +//go:nointerface +func (E) EBad() {} +func (E) EGood() {} + +type X[T any] struct{ E } + +//go:nointerface +func (X[T]) XBad() {} +func (X[T]) XGood() {} + +type W struct{ X[int] } + +func main() { + _ = E.EGood + _ = E.EBad + + TestE[E]() + + _ = X[int].EGood + _ = X[int].EBad + _ = X[int].XGood + _ = X[int].XBad + + TestE[X[int]]() + TestX[X[int]]() + + _ = W.EGood + _ = W.EBad + _ = W.XGood + _ = W.XBad + + TestE[W]() + TestX[W]() +} diff --git a/go/test/typeparam/mdempsky/16.go b/go/test/typeparam/mdempsky/16.go new file mode 100644 index 0000000000000000000000000000000000000000..f4f79b9aac5d1583f35dc9e0971d0e3368beef6f --- /dev/null +++ b/go/test/typeparam/mdempsky/16.go @@ -0,0 +1,34 @@ +// run + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that type assertion panics mention the real interface type, +// not their shape type. + +package main + +import ( + "fmt" + "runtime" + "strings" +) + +func main() { + // The exact error message isn't important, but it should mention + // `main.T`, not `go.shape.int_0`. + if have := F[T](); !strings.Contains(have, "interface { T() main.T }") { + fmt.Printf("FAIL: unexpected panic message: %q\n", have) + } +} + +type T int + +func F[T any]() (res string) { + defer func() { + res = recover().(runtime.Error).Error() + }() + _ = interface{ T() T }(nil).(T) + return +} diff --git a/go/test/typeparam/mdempsky/17.go b/go/test/typeparam/mdempsky/17.go new file mode 100644 index 0000000000000000000000000000000000000000..12385c3f9eea78c05ee73d576123a3a40aeaa250 --- /dev/null +++ b/go/test/typeparam/mdempsky/17.go @@ -0,0 +1,110 @@ +// run + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that implicit conversions of derived types to interface type +// in range loops work correctly. + +package main + +import ( + "fmt" + "reflect" +) + +func main() { + test{"int", "V"}.match(RangeArrayAny[V]()) + test{"int", "V"}.match(RangeArrayIface[V]()) + test{"V"}.match(RangeChanAny[V]()) + test{"V"}.match(RangeChanIface[V]()) + test{"K", "V"}.match(RangeMapAny[K, V]()) + test{"K", "V"}.match(RangeMapIface[K, V]()) + test{"int", "V"}.match(RangeSliceAny[V]()) + test{"int", "V"}.match(RangeSliceIface[V]()) +} + +type test []string + +func (t test) match(args ...any) { + if len(t) != len(args) { + fmt.Printf("FAIL: want %v values, have %v\n", len(t), len(args)) + return + } + for i, want := range t { + if have := reflect.TypeOf(args[i]).Name(); want != have { + fmt.Printf("FAIL: %v: want type %v, have %v\n", i, want, have) + } + } +} + +type iface interface{ M() int } + +type K int +type V int + +func (K) M() int { return 0 } +func (V) M() int { return 0 } + +func RangeArrayAny[V any]() (k, v any) { + for k, v = range [...]V{zero[V]()} { + } + return +} + +func RangeArrayIface[V iface]() (k any, v iface) { + for k, v = range [...]V{zero[V]()} { + } + return +} + +func RangeChanAny[V any]() (v any) { + for v = range chanOf(zero[V]()) { + } + return +} + +func RangeChanIface[V iface]() (v iface) { + for v = range chanOf(zero[V]()) { + } + return +} + +func RangeMapAny[K comparable, V any]() (k, v any) { + for k, v = range map[K]V{zero[K](): zero[V]()} { + } + return +} + +func RangeMapIface[K interface { + iface + comparable +}, V iface]() (k, v iface) { + for k, v = range map[K]V{zero[K](): zero[V]()} { + } + return +} + +func RangeSliceAny[V any]() (k, v any) { + for k, v = range []V{zero[V]()} { + } + return +} + +func RangeSliceIface[V iface]() (k any, v iface) { + for k, v = range []V{zero[V]()} { + } + return +} + +func chanOf[T any](elems ...T) chan T { + c := make(chan T, len(elems)) + for _, elem := range elems { + c <- elem + } + close(c) + return c +} + +func zero[T any]() (_ T) { return } diff --git a/go/test/typeparam/mdempsky/18.go b/go/test/typeparam/mdempsky/18.go new file mode 100644 index 0000000000000000000000000000000000000000..f4a4ec73c5eb6e35e84510ec165c58bd9e80e466 --- /dev/null +++ b/go/test/typeparam/mdempsky/18.go @@ -0,0 +1,26 @@ +// run + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that implicit conversions to interface type in a select/case +// clause are compiled correctly. + +package main + +import "fmt" + +func main() { f[int]() } + +func f[T any]() { + ch := make(chan T) + close(ch) + + var i, ok any + select { + case i, ok = <-ch: + } + + fmt.Printf("%T %T\n", i, ok) +} diff --git a/go/test/typeparam/mdempsky/18.out b/go/test/typeparam/mdempsky/18.out new file mode 100644 index 0000000000000000000000000000000000000000..19f1c39a22d9959068430358d5f49a01581cd7a5 --- /dev/null +++ b/go/test/typeparam/mdempsky/18.out @@ -0,0 +1 @@ +int bool diff --git a/go/test/typeparam/mdempsky/19.go b/go/test/typeparam/mdempsky/19.go new file mode 100644 index 0000000000000000000000000000000000000000..53d979a1f249565955b322ce3a01bc80dc61fe20 --- /dev/null +++ b/go/test/typeparam/mdempsky/19.go @@ -0,0 +1,32 @@ +// run + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that type parameter methods are handled correctly, even when +// the instantiating type argument has additional methods. + +package main + +func main() { + F(X(0)) +} + +type I interface{ B() } + +func F[T I](t T) { + CallMethod(t) + MethodExpr[T]()(t) + MethodVal(t)() +} + +func CallMethod[T I](t T) { t.B() } +func MethodExpr[T I]() func(T) { return T.B } +func MethodVal[T I](t T) func() { return t.B } + +type X int + +func (X) A() { panic("FAIL") } +func (X) B() {} +func (X) C() { panic("FAIL") } diff --git a/go/test/typeparam/mdempsky/2.go b/go/test/typeparam/mdempsky/2.go new file mode 100644 index 0000000000000000000000000000000000000000..ad548e6a549f92693f5bf91cf991cae0f851f6b8 --- /dev/null +++ b/go/test/typeparam/mdempsky/2.go @@ -0,0 +1,20 @@ +// compile + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +type T[A, B, C any] int + +func (T[A, B, C]) m(x int) { + if x <= 0 { + return + } + T[B, C, A](0).m(x - 1) +} + +func main() { + T[int8, int16, int32](0).m(3) +} diff --git a/go/test/typeparam/mdempsky/20.go b/go/test/typeparam/mdempsky/20.go new file mode 100644 index 0000000000000000000000000000000000000000..6b97ca102c344052cb5630ef619ca62e122057a9 --- /dev/null +++ b/go/test/typeparam/mdempsky/20.go @@ -0,0 +1,38 @@ +// run + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that method expressions with a derived receiver type and +// promoted methods work correctly. + +package main + +func main() { + F[int]() + F[string]() +} + +func F[X any]() { + call(T[X].M, T[X].N) +} + +func call[X any](fns ...func(T[X]) int) { + for want, fn := range fns { + if have := fn(T[X]{}); have != want { + println("FAIL:", have, "!=", want) + } + } +} + +type T[X any] struct { + E1 + *E2[*X] +} + +type E1 struct{} +type E2[_ any] struct{} + +func (E1) M() int { return 0 } +func (*E2[_]) N() int { return 1 } diff --git a/go/test/typeparam/mdempsky/21.go b/go/test/typeparam/mdempsky/21.go new file mode 100644 index 0000000000000000000000000000000000000000..da10ae3ea329889c75552360673ca15ef1ceea8e --- /dev/null +++ b/go/test/typeparam/mdempsky/21.go @@ -0,0 +1,26 @@ +// run + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that devirtualization doesn't introduce spurious type +// assertion failures due to shaped and non-shaped interfaces having +// distinct itabs. + +package main + +func main() { + F[int]() +} + +func F[T any]() { + var i I[T] = X(0) + i.M() +} + +type I[T any] interface{ M() } + +type X int + +func (X) M() {} diff --git a/go/test/typeparam/mdempsky/3.dir/a.go b/go/test/typeparam/mdempsky/3.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..cf456e8d48f17422ebb16183066d6556f371f04e --- /dev/null +++ b/go/test/typeparam/mdempsky/3.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F[T interface{ chan int }](c T) {} diff --git a/go/test/typeparam/mdempsky/3.dir/b.go b/go/test/typeparam/mdempsky/3.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..0cfd142f4c454e8222253d97e5a48cab273580d5 --- /dev/null +++ b/go/test/typeparam/mdempsky/3.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func g() { a.F(make(chan int)) } diff --git a/go/test/typeparam/mdempsky/3.go b/go/test/typeparam/mdempsky/3.go new file mode 100644 index 0000000000000000000000000000000000000000..b83fbd7af16a576c16e0fc73b84f1ca0f618b756 --- /dev/null +++ b/go/test/typeparam/mdempsky/3.go @@ -0,0 +1,7 @@ +// compiledir + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ignored diff --git a/go/test/typeparam/mdempsky/4.dir/a.go b/go/test/typeparam/mdempsky/4.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..cb672949eaedcd8faaeb72beb135078c6de41a7e --- /dev/null +++ b/go/test/typeparam/mdempsky/4.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F[T any](T) { +Loop: + for { + break Loop + } +} diff --git a/go/test/typeparam/mdempsky/4.dir/b.go b/go/test/typeparam/mdempsky/4.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..e1fb0e7c5eaabc3af41c320fe9adfda6a22e7eab --- /dev/null +++ b/go/test/typeparam/mdempsky/4.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func f() { a.F(0) } diff --git a/go/test/typeparam/mdempsky/4.go b/go/test/typeparam/mdempsky/4.go new file mode 100644 index 0000000000000000000000000000000000000000..b83fbd7af16a576c16e0fc73b84f1ca0f618b756 --- /dev/null +++ b/go/test/typeparam/mdempsky/4.go @@ -0,0 +1,7 @@ +// compiledir + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ignored diff --git a/go/test/typeparam/mdempsky/5.go b/go/test/typeparam/mdempsky/5.go new file mode 100644 index 0000000000000000000000000000000000000000..00d3b71be0ee53f71e4482b4dd7fb46fb0681e87 --- /dev/null +++ b/go/test/typeparam/mdempsky/5.go @@ -0,0 +1,15 @@ +// compile + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type X[T any] int + +func (X[T]) F(T) {} + +func x() { + X[interface{}](0).F(0) +} diff --git a/go/test/typeparam/mdempsky/6.go b/go/test/typeparam/mdempsky/6.go new file mode 100644 index 0000000000000000000000000000000000000000..ed57009436850f1c59335f8c442cb45b2c10549c --- /dev/null +++ b/go/test/typeparam/mdempsky/6.go @@ -0,0 +1,11 @@ +// compile + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I[T any] interface{ M() T } + +var _ = I[int].M diff --git a/go/test/typeparam/mdempsky/7.dir/a.go b/go/test/typeparam/mdempsky/7.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..59c5995611834a9cbec9ca3b2aa9f9588011ea36 --- /dev/null +++ b/go/test/typeparam/mdempsky/7.dir/a.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type I[T any] interface{ M() T } + +var X I[int] diff --git a/go/test/typeparam/mdempsky/7.dir/b.go b/go/test/typeparam/mdempsky/7.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..9f70530811482ea8213ec47efd5f76593a432814 --- /dev/null +++ b/go/test/typeparam/mdempsky/7.dir/b.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +var _ = a.X diff --git a/go/test/typeparam/mdempsky/7.go b/go/test/typeparam/mdempsky/7.go new file mode 100644 index 0000000000000000000000000000000000000000..b83fbd7af16a576c16e0fc73b84f1ca0f618b756 --- /dev/null +++ b/go/test/typeparam/mdempsky/7.go @@ -0,0 +1,7 @@ +// compiledir + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ignored diff --git a/go/test/typeparam/mdempsky/8.dir/a.go b/go/test/typeparam/mdempsky/8.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..607fe5e0af2e098b1083bbe81c12c3f7dfa58506 --- /dev/null +++ b/go/test/typeparam/mdempsky/8.dir/a.go @@ -0,0 +1,7 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F[T interface{ comparable }]() {} diff --git a/go/test/typeparam/mdempsky/8.dir/b.go b/go/test/typeparam/mdempsky/8.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..ef2637b894fb69c563689081f44dc3f431a9ee5d --- /dev/null +++ b/go/test/typeparam/mdempsky/8.dir/b.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func init() { + a.F[func()]() // ERROR "does not satisfy comparable" +} diff --git a/go/test/typeparam/mdempsky/8.go b/go/test/typeparam/mdempsky/8.go new file mode 100644 index 0000000000000000000000000000000000000000..e3a470b4195ab9ee0b49030efa76975b00b284f7 --- /dev/null +++ b/go/test/typeparam/mdempsky/8.go @@ -0,0 +1,7 @@ +// errorcheckdir + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ignored diff --git a/go/test/typeparam/mdempsky/9.go b/go/test/typeparam/mdempsky/9.go new file mode 100644 index 0000000000000000000000000000000000000000..948a9e532e0c7661cdacdd36a5a65dfc7a544798 --- /dev/null +++ b/go/test/typeparam/mdempsky/9.go @@ -0,0 +1,11 @@ +// compile + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func f[V any]() []V { return []V{0: *new(V)} } + +func g() { f[int]() } diff --git a/go/test/typeparam/mincheck.dir/a.go b/go/test/typeparam/mincheck.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..fa0f249e61510c3a136fc0c66b3cff4d3f876df0 --- /dev/null +++ b/go/test/typeparam/mincheck.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Ordered interface { + int | int64 | float64 +} + +func Min[T Ordered](x, y T) T { + if x < y { + return x + } + return y +} diff --git a/go/test/typeparam/mincheck.dir/main.go b/go/test/typeparam/mincheck.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6f85f9e5e12bf0514a10633ed34c07b06d193e42 --- /dev/null +++ b/go/test/typeparam/mincheck.dir/main.go @@ -0,0 +1,38 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" +) + +func main() { + const want = 2 + if got := a.Min[int](2, 3); got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + if got := a.Min(2, 3); got != want { + panic(fmt.Sprintf("want %d, got %d", want, got)) + } + + if got := a.Min[float64](3.5, 2.0); got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + if got := a.Min(3.5, 2.0); got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + const want2 = "ay" + if got := a.Min[string]("bb", "ay"); got != want2 { // ERROR "string does not satisfy" + panic(fmt.Sprintf("got %d, want %d", got, want2)) + } + + if got := a.Min("bb", "ay"); got != want2 { // ERROR "string does not satisfy" + panic(fmt.Sprintf("got %d, want %d", got, want2)) + } +} diff --git a/go/test/typeparam/minimp.dir/a.go b/go/test/typeparam/minimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..fabde62c5d7218c987cbd64793586c941456451c --- /dev/null +++ b/go/test/typeparam/minimp.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Ordered interface { + ~int | ~int64 | ~float64 | ~string +} + +func Min[T Ordered](x, y T) T { + if x < y { + return x + } + return y +} diff --git a/go/test/typeparam/minimp.dir/main.go b/go/test/typeparam/minimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..36bec0f600de2dea6b1ab763b56a9e758c9b7405 --- /dev/null +++ b/go/test/typeparam/minimp.dir/main.go @@ -0,0 +1,38 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" +) + +func main() { + const want = 2 + if got := a.Min[int](2, 3); got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + if got := a.Min(2, 3); got != want { + panic(fmt.Sprintf("want %d, got %d", want, got)) + } + + if got := a.Min[float64](3.5, 2.0); got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + if got := a.Min(3.5, 2.0); got != want { + panic(fmt.Sprintf("got %d, want %d", got, want)) + } + + const want2 = "ay" + if got := a.Min[string]("bb", "ay"); got != want2 { + panic(fmt.Sprintf("got %d, want %d", got, want2)) + } + + if got := a.Min("bb", "ay"); got != want2 { + panic(fmt.Sprintf("got %d, want %d", got, want2)) + } +} diff --git a/go/test/typeparam/mutualimp.dir/a.go b/go/test/typeparam/mutualimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..5b924d3ce5dfec687d84c11e0bcf7b145493abcb --- /dev/null +++ b/go/test/typeparam/mutualimp.dir/a.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type X int + +func (x X) M() X { return x } + +func F[T interface{ M() U }, U interface{ M() T }]() {} +func G() { F[X, X]() } diff --git a/go/test/typeparam/mutualimp.dir/b.go b/go/test/typeparam/mutualimp.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..83cc3af2835c55b7c1b5db2ba604d9a5b2da05e8 --- /dev/null +++ b/go/test/typeparam/mutualimp.dir/b.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func H() { + a.F[a.X, a.X]() + a.G() +} diff --git a/go/test/typeparam/orderedmapsimp.dir/a.go b/go/test/typeparam/orderedmapsimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..d6a2de5d7b3e4a7eead46e360ac9a9c04b1293a1 --- /dev/null +++ b/go/test/typeparam/orderedmapsimp.dir/a.go @@ -0,0 +1,226 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import ( + "context" + "runtime" +) + +type Ordered interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 | + ~string +} + +// Map is an ordered map. +type Map[K, V any] struct { + root *node[K, V] + compare func(K, K) int +} + +// node is the type of a node in the binary tree. +type node[K, V any] struct { + key K + val V + left, right *node[K, V] +} + +// New returns a new map. It takes a comparison function that compares two +// keys and returns < 0 if the first is less, == 0 if they are equal, +// > 0 if the first is greater. +func New[K, V any](compare func(K, K) int) *Map[K, V] { + return &Map[K, V]{compare: compare} +} + +// NewOrdered returns a new map whose key is an ordered type. +// This is like New, but does not require providing a compare function. +// The map compare function uses the obvious key ordering. +func NewOrdered[K Ordered, V any]() *Map[K, V] { + return New[K, V](func(k1, k2 K) int { + switch { + case k1 < k2: + return -1 + case k1 > k2: + return 1 + default: + return 0 + } + }) +} + +// find looks up key in the map, returning either a pointer to the slot of the +// node holding key, or a pointer to the slot where a node would go. +func (m *Map[K, V]) find(key K) **node[K, V] { + pn := &m.root + for *pn != nil { + switch cmp := m.compare(key, (*pn).key); { + case cmp < 0: + pn = &(*pn).left + case cmp > 0: + pn = &(*pn).right + default: + return pn + } + } + return pn +} + +// Insert inserts a new key/value into the map. +// If the key is already present, the value is replaced. +// Reports whether this is a new key. +func (m *Map[K, V]) Insert(key K, val V) bool { + pn := m.find(key) + if *pn != nil { + (*pn).val = val + return false + } + *pn = &node[K, V]{key: key, val: val} + return true +} + +// Find returns the value associated with a key, or the zero value +// if not present. The second result reports whether the key was found. +func (m *Map[K, V]) Find(key K) (V, bool) { + pn := m.find(key) + if *pn == nil { + var zero V + return zero, false + } + return (*pn).val, true +} + +// keyValue is a pair of key and value used while iterating. +type keyValue[K, V any] struct { + key K + val V +} + +// iterate returns an iterator that traverses the map. +func (m *Map[K, V]) Iterate() *Iterator[K, V] { + sender, receiver := Ranger[keyValue[K, V]]() + var f func(*node[K, V]) bool + f = func(n *node[K, V]) bool { + if n == nil { + return true + } + // Stop the traversal if Send fails, which means that + // nothing is listening to the receiver. + return f(n.left) && + sender.Send(context.Background(), keyValue[K, V]{n.key, n.val}) && + f(n.right) + } + go func() { + f(m.root) + sender.Close() + }() + return &Iterator[K, V]{receiver} +} + +// Iterator is used to iterate over the map. +type Iterator[K, V any] struct { + r *Receiver[keyValue[K, V]] +} + +// Next returns the next key and value pair, and a boolean that reports +// whether they are valid. If not valid, we have reached the end of the map. +func (it *Iterator[K, V]) Next() (K, V, bool) { + keyval, ok := it.r.Next(context.Background()) + if !ok { + var zerok K + var zerov V + return zerok, zerov, false + } + return keyval.key, keyval.val, true +} + +// Equal reports whether two slices are equal: the same length and all +// elements equal. All floating point NaNs are considered equal. +func SliceEqual[Elem comparable](s1, s2 []Elem) bool { + if len(s1) != len(s2) { + return false + } + for i, v1 := range s1 { + v2 := s2[i] + if v1 != v2 { + isNaN := func(f Elem) bool { return f != f } + if !isNaN(v1) || !isNaN(v2) { + return false + } + } + } + return true +} + +// Ranger returns a Sender and a Receiver. The Receiver provides a +// Next method to retrieve values. The Sender provides a Send method +// to send values and a Close method to stop sending values. The Next +// method indicates when the Sender has been closed, and the Send +// method indicates when the Receiver has been freed. +// +// This is a convenient way to exit a goroutine sending values when +// the receiver stops reading them. +func Ranger[Elem any]() (*Sender[Elem], *Receiver[Elem]) { + c := make(chan Elem) + d := make(chan struct{}) + s := &Sender[Elem]{ + values: c, + done: d, + } + r := &Receiver[Elem]{ + values: c, + done: d, + } + runtime.SetFinalizer(r, (*Receiver[Elem]).finalize) + return s, r +} + +// A Sender is used to send values to a Receiver. +type Sender[Elem any] struct { + values chan<- Elem + done <-chan struct{} +} + +// Send sends a value to the receiver. It reports whether the value was sent. +// The value will not be sent if the context is closed or the receiver +// is freed. +func (s *Sender[Elem]) Send(ctx context.Context, v Elem) bool { + select { + case <-ctx.Done(): + return false + case s.values <- v: + return true + case <-s.done: + return false + } +} + +// Close tells the receiver that no more values will arrive. +// After Close is called, the Sender may no longer be used. +func (s *Sender[Elem]) Close() { + close(s.values) +} + +// A Receiver receives values from a Sender. +type Receiver[Elem any] struct { + values <-chan Elem + done chan<- struct{} +} + +// Next returns the next value from the channel. The bool result indicates +// whether the value is valid. +func (r *Receiver[Elem]) Next(ctx context.Context) (v Elem, ok bool) { + select { + case <-ctx.Done(): + case v, ok = <-r.values: + } + return v, ok +} + +// finalize is a finalizer for the receiver. +func (r *Receiver[Elem]) finalize() { + close(r.done) +} diff --git a/go/test/typeparam/orderedmapsimp.dir/main.go b/go/test/typeparam/orderedmapsimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..7758a75c233776aad8ea0e118b55a7536ea50d76 --- /dev/null +++ b/go/test/typeparam/orderedmapsimp.dir/main.go @@ -0,0 +1,64 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "bytes" + "fmt" +) + +func TestMap() { + m := a.New[[]byte, int](bytes.Compare) + + if _, found := m.Find([]byte("a")); found { + panic(fmt.Sprintf("unexpectedly found %q in empty map", []byte("a"))) + } + + for _, c := range []int{'a', 'c', 'b'} { + if !m.Insert([]byte(string(c)), c) { + panic(fmt.Sprintf("key %q unexpectedly already present", []byte(string(c)))) + } + } + if m.Insert([]byte("c"), 'x') { + panic(fmt.Sprintf("key %q unexpectedly not present", []byte("c"))) + } + + if v, found := m.Find([]byte("a")); !found { + panic(fmt.Sprintf("did not find %q", []byte("a"))) + } else if v != 'a' { + panic(fmt.Sprintf("key %q returned wrong value %c, expected %c", []byte("a"), v, 'a')) + } + if v, found := m.Find([]byte("c")); !found { + panic(fmt.Sprintf("did not find %q", []byte("c"))) + } else if v != 'x' { + panic(fmt.Sprintf("key %q returned wrong value %c, expected %c", []byte("c"), v, 'x')) + } + + if _, found := m.Find([]byte("d")); found { + panic(fmt.Sprintf("unexpectedly found %q", []byte("d"))) + } + + gather := func(it *a.Iterator[[]byte, int]) []int { + var r []int + for { + _, v, ok := it.Next() + if !ok { + return r + } + r = append(r, v) + } + } + got := gather(m.Iterate()) + want := []int{'a', 'b', 'x'} + if !a.SliceEqual(got, want) { + panic(fmt.Sprintf("Iterate returned %v, want %v", got, want)) + } + +} + +func main() { + TestMap() +} diff --git a/go/test/typeparam/pairimp.dir/a.go b/go/test/typeparam/pairimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..a984fba37b6e6655d8ba2031166d7b575737927c --- /dev/null +++ b/go/test/typeparam/pairimp.dir/a.go @@ -0,0 +1,10 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Pair[F1, F2 any] struct { + Field1 F1 + Field2 F2 +} diff --git a/go/test/typeparam/pairimp.dir/main.go b/go/test/typeparam/pairimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f76da434d4cfe34deaf4534df90f5d1bd101e9cd --- /dev/null +++ b/go/test/typeparam/pairimp.dir/main.go @@ -0,0 +1,30 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" + "unsafe" +) + +func main() { + p := a.Pair[int32, int64]{1, 2} + if got, want := unsafe.Sizeof(p.Field1), uintptr(4); got != want { + panic(fmt.Sprintf("unexpected f1 size == %d, want %d", got, want)) + } + if got, want := unsafe.Sizeof(p.Field2), uintptr(8); got != want { + panic(fmt.Sprintf("unexpected f2 size == %d, want %d", got, want)) + } + + type mypair struct { + Field1 int32 + Field2 int64 + } + mp := mypair(p) + if mp.Field1 != 1 || mp.Field2 != 2 { + panic(fmt.Sprintf("mp == %#v, want %#v", mp, mypair{1, 2})) + } +} diff --git a/go/test/typeparam/recoverimp.dir/a.go b/go/test/typeparam/recoverimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..a465fd1545fe9deda77d80575f100b4af9d60d30 --- /dev/null +++ b/go/test/typeparam/recoverimp.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +import "fmt" + +func F[T any](a T) { + defer func() { + if x := recover(); x != nil { + fmt.Printf("panic: %v\n", x) + } + }() + panic(a) +} diff --git a/go/test/typeparam/recoverimp.dir/main.go b/go/test/typeparam/recoverimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..d8cfa3875c0b5e69208e9253edb4b0b8388b5950 --- /dev/null +++ b/go/test/typeparam/recoverimp.dir/main.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./a" + +func main() { + a.F(5.3) + a.F("hello") +} diff --git a/go/test/typeparam/select.dir/a.go b/go/test/typeparam/select.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..983e4b1d5f7cd8c4deb00ce7a43893fb4b09a3e2 --- /dev/null +++ b/go/test/typeparam/select.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +func F[T any](c, d chan T) T { + select { + case x := <- c: + return x + case x := <- d: + return x + } +} + diff --git a/go/test/typeparam/select.dir/main.go b/go/test/typeparam/select.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6ea3fe2eeac3a4b54e0175211a996aca02e34cec --- /dev/null +++ b/go/test/typeparam/select.dir/main.go @@ -0,0 +1,28 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "sort" + + "./a" +) + +func main() { + c := make(chan int, 1) + d := make(chan int, 1) + + c <- 5 + d <- 6 + + var r [2]int + r[0] = a.F(c, d) + r[1] = a.F(c, d) + sort.Ints(r[:]) + + if r != [2]int{5, 6} { + panic("incorrect results") + } +} diff --git a/go/test/typeparam/setsimp.dir/a.go b/go/test/typeparam/setsimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..92449ce95620caf19ee17019ddecf36c8130ea89 --- /dev/null +++ b/go/test/typeparam/setsimp.dir/a.go @@ -0,0 +1,128 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +// SliceEqual reports whether two slices are equal: the same length and all +// elements equal. All floating point NaNs are considered equal. +func SliceEqual[Elem comparable](s1, s2 []Elem) bool { + if len(s1) != len(s2) { + return false + } + for i, v1 := range s1 { + v2 := s2[i] + if v1 != v2 { + isNaN := func(f Elem) bool { return f != f } + if !isNaN(v1) || !isNaN(v2) { + return false + } + } + } + return true +} + +// A Set is a set of elements of some type. +type Set[Elem comparable] struct { + m map[Elem]struct{} +} + +// Make makes a new set. +func Make[Elem comparable]() Set[Elem] { + return Set[Elem]{m: make(map[Elem]struct{})} +} + +// Add adds an element to a set. +func (s Set[Elem]) Add(v Elem) { + s.m[v] = struct{}{} +} + +// Delete removes an element from a set. If the element is not present +// in the set, this does nothing. +func (s Set[Elem]) Delete(v Elem) { + delete(s.m, v) +} + +// Contains reports whether v is in the set. +func (s Set[Elem]) Contains(v Elem) bool { + _, ok := s.m[v] + return ok +} + +// Len returns the number of elements in the set. +func (s Set[Elem]) Len() int { + return len(s.m) +} + +// Values returns the values in the set. +// The values will be in an indeterminate order. +func (s Set[Elem]) Values() []Elem { + r := make([]Elem, 0, len(s.m)) + for v := range s.m { + r = append(r, v) + } + return r +} + +// Equal reports whether two sets contain the same elements. +func Equal[Elem comparable](s1, s2 Set[Elem]) bool { + if len(s1.m) != len(s2.m) { + return false + } + for v1 := range s1.m { + if !s2.Contains(v1) { + return false + } + } + return true +} + +// Copy returns a copy of s. +func (s Set[Elem]) Copy() Set[Elem] { + r := Set[Elem]{m: make(map[Elem]struct{}, len(s.m))} + for v := range s.m { + r.m[v] = struct{}{} + } + return r +} + +// AddSet adds all the elements of s2 to s. +func (s Set[Elem]) AddSet(s2 Set[Elem]) { + for v := range s2.m { + s.m[v] = struct{}{} + } +} + +// SubSet removes all elements in s2 from s. +// Values in s2 that are not in s are ignored. +func (s Set[Elem]) SubSet(s2 Set[Elem]) { + for v := range s2.m { + delete(s.m, v) + } +} + +// Intersect removes all elements from s that are not present in s2. +// Values in s2 that are not in s are ignored. +func (s Set[Elem]) Intersect(s2 Set[Elem]) { + for v := range s.m { + if !s2.Contains(v) { + delete(s.m, v) + } + } +} + +// Iterate calls f on every element in the set. +func (s Set[Elem]) Iterate(f func(Elem)) { + for v := range s.m { + f(v) + } +} + +// Filter deletes any elements from s for which f returns false. +func (s Set[Elem]) Filter(f func(Elem) bool) { + for v := range s.m { + if !f(v) { + delete(s.m, v) + } + } +} diff --git a/go/test/typeparam/setsimp.dir/main.go b/go/test/typeparam/setsimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e1ec86a6f0d030f43955977c18e814d5265649b1 --- /dev/null +++ b/go/test/typeparam/setsimp.dir/main.go @@ -0,0 +1,156 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" + "sort" +) + +func TestSet() { + s1 := a.Make[int]() + if got := s1.Len(); got != 0 { + panic(fmt.Sprintf("Len of empty set = %d, want 0", got)) + } + s1.Add(1) + s1.Add(1) + s1.Add(1) + if got := s1.Len(); got != 1 { + panic(fmt.Sprintf("(%v).Len() == %d, want 1", s1, got)) + } + s1.Add(2) + s1.Add(3) + s1.Add(4) + if got := s1.Len(); got != 4 { + panic(fmt.Sprintf("(%v).Len() == %d, want 4", s1, got)) + } + if !s1.Contains(1) { + panic(fmt.Sprintf("(%v).Contains(1) == false, want true", s1)) + } + if s1.Contains(5) { + panic(fmt.Sprintf("(%v).Contains(5) == true, want false", s1)) + } + vals := s1.Values() + sort.Ints(vals) + w1 := []int{1, 2, 3, 4} + if !a.SliceEqual(vals, w1) { + panic(fmt.Sprintf("(%v).Values() == %v, want %v", s1, vals, w1)) + } +} + +func TestEqual() { + s1 := a.Make[string]() + s2 := a.Make[string]() + if !a.Equal(s1, s2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = false, want true", s1, s2)) + } + s1.Add("hello") + s1.Add("world") + if got := s1.Len(); got != 2 { + panic(fmt.Sprintf("(%v).Len() == %d, want 2", s1, got)) + } + if a.Equal(s1, s2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = true, want false", s1, s2)) + } +} + +func TestCopy() { + s1 := a.Make[float64]() + s1.Add(0) + s2 := s1.Copy() + if !a.Equal(s1, s2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = false, want true", s1, s2)) + } + s1.Add(1) + if a.Equal(s1, s2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = true, want false", s1, s2)) + } +} + +func TestAddSet() { + s1 := a.Make[int]() + s1.Add(1) + s1.Add(2) + s2 := a.Make[int]() + s2.Add(2) + s2.Add(3) + s1.AddSet(s2) + if got := s1.Len(); got != 3 { + panic(fmt.Sprintf("(%v).Len() == %d, want 3", s1, got)) + } + s2.Add(1) + if !a.Equal(s1, s2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = false, want true", s1, s2)) + } +} + +func TestSubSet() { + s1 := a.Make[int]() + s1.Add(1) + s1.Add(2) + s2 := a.Make[int]() + s2.Add(2) + s2.Add(3) + s1.SubSet(s2) + if got := s1.Len(); got != 1 { + panic(fmt.Sprintf("(%v).Len() == %d, want 1", s1, got)) + } + if vals, want := s1.Values(), []int{1}; !a.SliceEqual(vals, want) { + panic(fmt.Sprintf("after SubSet got %v, want %v", vals, want)) + } +} + +func TestIntersect() { + s1 := a.Make[int]() + s1.Add(1) + s1.Add(2) + s2 := a.Make[int]() + s2.Add(2) + s2.Add(3) + s1.Intersect(s2) + if got := s1.Len(); got != 1 { + panic(fmt.Sprintf("(%v).Len() == %d, want 1", s1, got)) + } + if vals, want := s1.Values(), []int{2}; !a.SliceEqual(vals, want) { + panic(fmt.Sprintf("after Intersect got %v, want %v", vals, want)) + } +} + +func TestIterate() { + s1 := a.Make[int]() + s1.Add(1) + s1.Add(2) + s1.Add(3) + s1.Add(4) + tot := 0 + s1.Iterate(func(i int) { tot += i }) + if tot != 10 { + panic(fmt.Sprintf("total of %v == %d, want 10", s1, tot)) + } +} + +func TestFilter() { + s1 := a.Make[int]() + s1.Add(1) + s1.Add(2) + s1.Add(3) + s1.Filter(func(v int) bool { return v%2 == 0 }) + if vals, want := s1.Values(), []int{2}; !a.SliceEqual(vals, want) { + panic(fmt.Sprintf("after Filter got %v, want %v", vals, want)) + } + +} + +func main() { + TestSet() + TestEqual() + TestCopy() + TestAddSet() + TestSubSet() + TestIntersect() + TestIterate() + TestFilter() +} diff --git a/go/test/typeparam/sliceimp.dir/a.go b/go/test/typeparam/sliceimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..dbcfae893185e3b9f2e07f1060c523c0c48b3155 --- /dev/null +++ b/go/test/typeparam/sliceimp.dir/a.go @@ -0,0 +1,141 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Ordered interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 | + ~string +} + +// Max returns the maximum of two values of some ordered type. +func Max[T Ordered](a, b T) T { + if a > b { + return a + } + return b +} + +// Min returns the minimum of two values of some ordered type. +func Min[T Ordered](a, b T) T { + if a < b { + return a + } + return b +} + +// Equal reports whether two slices are equal: the same length and all +// elements equal. All floating point NaNs are considered equal. +func Equal[Elem comparable](s1, s2 []Elem) bool { + if len(s1) != len(s2) { + return false + } + for i, v1 := range s1 { + v2 := s2[i] + if v1 != v2 { + isNaN := func(f Elem) bool { return f != f } + if !isNaN(v1) || !isNaN(v2) { + return false + } + } + } + return true +} + +// EqualFn reports whether two slices are equal using a comparison +// function on each element. +func EqualFn[Elem any](s1, s2 []Elem, eq func(Elem, Elem) bool) bool { + if len(s1) != len(s2) { + return false + } + for i, v1 := range s1 { + v2 := s2[i] + if !eq(v1, v2) { + return false + } + } + return true +} + +// Map turns a []Elem1 to a []Elem2 using a mapping function. +func Map[Elem1, Elem2 any](s []Elem1, f func(Elem1) Elem2) []Elem2 { + r := make([]Elem2, len(s)) + for i, v := range s { + r[i] = f(v) + } + return r +} + +// Reduce reduces a []Elem1 to a single value of type Elem2 using +// a reduction function. +func Reduce[Elem1, Elem2 any](s []Elem1, initializer Elem2, f func(Elem2, Elem1) Elem2) Elem2 { + r := initializer + for _, v := range s { + r = f(r, v) + } + return r +} + +// Filter filters values from a slice using a filter function. +func Filter[Elem any](s []Elem, f func(Elem) bool) []Elem { + var r []Elem + for _, v := range s { + if f(v) { + r = append(r, v) + } + } + return r +} + +// Max returns the maximum element in a slice of some ordered type. +// If the slice is empty it returns the zero value of the element type. +func SliceMax[Elem Ordered](s []Elem) Elem { + if len(s) == 0 { + var zero Elem + return zero + } + return Reduce(s[1:], s[0], Max[Elem]) +} + +// Min returns the minimum element in a slice of some ordered type. +// If the slice is empty it returns the zero value of the element type. +func SliceMin[Elem Ordered](s []Elem) Elem { + if len(s) == 0 { + var zero Elem + return zero + } + return Reduce(s[1:], s[0], Min[Elem]) +} + +// Append adds values to the end of a slice, returning a new slice. +// This is like the predeclared append function; it's an example +// of how to write it using generics. We used to write code like +// this before append was added to the language, but we had to write +// a separate copy for each type. +func Append[T any](s []T, t ...T) []T { + lens := len(s) + tot := lens + len(t) + if tot <= cap(s) { + s = s[:tot] + } else { + news := make([]T, tot, tot+tot/2) + Copy(news, s) + s = news + } + Copy(s[lens:tot], t) + return s +} + +// Copy copies values from t to s, stopping when either slice is full, +// returning the number of values copied. This is like the predeclared +// copy function; it's an example of how to write it using generics. +func Copy[T any](s, t []T) int { + i := 0 + for ; i < len(s) && i < len(t); i++ { + s[i] = t[i] + } + return i +} diff --git a/go/test/typeparam/sliceimp.dir/main.go b/go/test/typeparam/sliceimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..ec13188ba9654d3b1c0e0fd774c6792643542d4a --- /dev/null +++ b/go/test/typeparam/sliceimp.dir/main.go @@ -0,0 +1,179 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" + "math" + "strings" +) + +type Integer interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +func TestEqual() { + s1 := []int{1, 2, 3} + if !a.Equal(s1, s1) { + panic(fmt.Sprintf("a.Equal(%v, %v) = false, want true", s1, s1)) + } + s2 := []int{1, 2, 3} + if !a.Equal(s1, s2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = false, want true", s1, s2)) + } + s2 = append(s2, 4) + if a.Equal(s1, s2) { + panic(fmt.Sprintf("a.Equal(%v, %v) = true, want false", s1, s2)) + } + + s3 := []float64{1, 2, math.NaN()} + if !a.Equal(s3, s3) { + panic(fmt.Sprintf("a.Equal(%v, %v) = false, want true", s3, s3)) + } + + if a.Equal(s1, nil) { + panic(fmt.Sprintf("a.Equal(%v, nil) = true, want false", s1)) + } + if a.Equal(nil, s1) { + panic(fmt.Sprintf("a.Equal(nil, %v) = true, want false", s1)) + } + if !a.Equal(s1[:0], nil) { + panic(fmt.Sprintf("a.Equal(%v, nil = false, want true", s1[:0])) + } +} + +func offByOne[Elem Integer](a, b Elem) bool { + return a == b+1 || a == b-1 +} + +func TestEqualFn() { + s1 := []int{1, 2, 3} + s2 := []int{2, 3, 4} + if a.EqualFn(s1, s1, offByOne[int]) { + panic(fmt.Sprintf("a.EqualFn(%v, %v, offByOne) = true, want false", s1, s1)) + } + if !a.EqualFn(s1, s2, offByOne[int]) { + panic(fmt.Sprintf("a.EqualFn(%v, %v, offByOne) = false, want true", s1, s2)) + } + + if !a.EqualFn(s1[:0], nil, offByOne[int]) { + panic(fmt.Sprintf("a.EqualFn(%v, nil, offByOne) = false, want true", s1[:0])) + } + + s3 := []string{"a", "b", "c"} + s4 := []string{"A", "B", "C"} + if !a.EqualFn(s3, s4, strings.EqualFold) { + panic(fmt.Sprintf("a.EqualFn(%v, %v, strings.EqualFold) = false, want true", s3, s4)) + } +} + +func TestMap() { + s1 := []int{1, 2, 3} + s2 := a.Map(s1, func(i int) float64 { return float64(i) * 2.5 }) + if want := []float64{2.5, 5, 7.5}; !a.Equal(s2, want) { + panic(fmt.Sprintf("a.Map(%v, ...) = %v, want %v", s1, s2, want)) + } + + s3 := []string{"Hello", "World"} + s4 := a.Map(s3, strings.ToLower) + if want := []string{"hello", "world"}; !a.Equal(s4, want) { + panic(fmt.Sprintf("a.Map(%v, strings.ToLower) = %v, want %v", s3, s4, want)) + } + + s5 := a.Map(nil, func(i int) int { return i }) + if len(s5) != 0 { + panic(fmt.Sprintf("a.Map(nil, identity) = %v, want empty slice", s5)) + } +} + +func TestReduce() { + s1 := []int{1, 2, 3} + r := a.Reduce(s1, 0, func(f float64, i int) float64 { return float64(i)*2.5 + f }) + if want := 15.0; r != want { + panic(fmt.Sprintf("a.Reduce(%v, 0, ...) = %v, want %v", s1, r, want)) + } + + if got := a.Reduce(nil, 0, func(i, j int) int { return i + j }); got != 0 { + panic(fmt.Sprintf("a.Reduce(nil, 0, add) = %v, want 0", got)) + } +} + +func TestFilter() { + s1 := []int{1, 2, 3} + s2 := a.Filter(s1, func(i int) bool { return i%2 == 0 }) + if want := []int{2}; !a.Equal(s2, want) { + panic(fmt.Sprintf("a.Filter(%v, even) = %v, want %v", s1, s2, want)) + } + + if s3 := a.Filter(s1[:0], func(i int) bool { return true }); len(s3) > 0 { + panic(fmt.Sprintf("a.Filter(%v, identity) = %v, want empty slice", s1[:0], s3)) + } +} + +func TestMax() { + s1 := []int{1, 2, 3, -5} + if got, want := a.SliceMax(s1), 3; got != want { + panic(fmt.Sprintf("a.Max(%v) = %d, want %d", s1, got, want)) + } + + s2 := []string{"aaa", "a", "aa", "aaaa"} + if got, want := a.SliceMax(s2), "aaaa"; got != want { + panic(fmt.Sprintf("a.Max(%v) = %q, want %q", s2, got, want)) + } + + if got, want := a.SliceMax(s2[:0]), ""; got != want { + panic(fmt.Sprintf("a.Max(%v) = %q, want %q", s2[:0], got, want)) + } +} + +func TestMin() { + s1 := []int{1, 2, 3, -5} + if got, want := a.SliceMin(s1), -5; got != want { + panic(fmt.Sprintf("a.Min(%v) = %d, want %d", s1, got, want)) + } + + s2 := []string{"aaa", "a", "aa", "aaaa"} + if got, want := a.SliceMin(s2), "a"; got != want { + panic(fmt.Sprintf("a.Min(%v) = %q, want %q", s2, got, want)) + } + + if got, want := a.SliceMin(s2[:0]), ""; got != want { + panic(fmt.Sprintf("a.Min(%v) = %q, want %q", s2[:0], got, want)) + } +} + +func TestAppend() { + s := []int{1, 2, 3} + s = a.Append(s, 4, 5, 6) + want := []int{1, 2, 3, 4, 5, 6} + if !a.Equal(s, want) { + panic(fmt.Sprintf("after a.Append got %v, want %v", s, want)) + } +} + +func TestCopy() { + s1 := []int{1, 2, 3} + s2 := []int{4, 5} + if got := a.Copy(s1, s2); got != 2 { + panic(fmt.Sprintf("a.Copy returned %d, want 2", got)) + } + want := []int{4, 5, 3} + if !a.Equal(s1, want) { + panic(fmt.Sprintf("after a.Copy got %v, want %v", s1, want)) + } +} +func main() { + TestEqual() + TestEqualFn() + TestMap() + TestReduce() + TestFilter() + TestMax() + TestMin() + TestAppend() + TestCopy() +} diff --git a/go/test/typeparam/stringerimp.dir/a.go b/go/test/typeparam/stringerimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..3f70937ff55e862ed1fbf8dc206d830f56a97f59 --- /dev/null +++ b/go/test/typeparam/stringerimp.dir/a.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Stringer interface { + String() string +} + +func Stringify[T Stringer](s []T) (ret []string) { + for _, v := range s { + ret = append(ret, v.String()) + } + return ret +} diff --git a/go/test/typeparam/stringerimp.dir/main.go b/go/test/typeparam/stringerimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..9b41d3bc1db010c996e69ea005d090651b6ca463 --- /dev/null +++ b/go/test/typeparam/stringerimp.dir/main.go @@ -0,0 +1,38 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" + "reflect" + "strconv" +) + +type myint int + +func (i myint) String() string { + return strconv.Itoa(int(i)) +} + +func main() { + x := []myint{myint(1), myint(2), myint(3)} + + got := a.Stringify(x) + want := []string{"1", "2", "3"} + if !reflect.DeepEqual(got, want) { + panic(fmt.Sprintf("got %s, want %s", got, want)) + } + + m1 := myint(1) + m2 := myint(2) + m3 := myint(3) + y := []*myint{&m1, &m2, &m3} + got2 := a.Stringify(y) + want2 := []string{"1", "2", "3"} + if !reflect.DeepEqual(got2, want2) { + panic(fmt.Sprintf("got %s, want %s", got2, want2)) + } +} diff --git a/go/test/typeparam/structinit.dir/a.go b/go/test/typeparam/structinit.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..c76d1551adbeea9b19e3f500deac9405f0c64fc4 --- /dev/null +++ b/go/test/typeparam/structinit.dir/a.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type S[T any] struct { +} + +func (b *S[T]) build() *X[T] { + return &X[T]{f:0} +} +type X[T any] struct { + f int +} diff --git a/go/test/typeparam/structinit.dir/b.go b/go/test/typeparam/structinit.dir/b.go new file mode 100644 index 0000000000000000000000000000000000000000..40a929bcaede4af5d4a496b07de5c78565934b12 --- /dev/null +++ b/go/test/typeparam/structinit.dir/b.go @@ -0,0 +1,12 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "./a" + +func B() { + var x a.S[int] + _ = x +} diff --git a/go/test/typeparam/structinit.dir/main.go b/go/test/typeparam/structinit.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c564171879578c48318ee7284953e5f363fa8131 --- /dev/null +++ b/go/test/typeparam/structinit.dir/main.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "./b" + +func main() { + b.B() +} diff --git a/go/test/typeparam/valimp.dir/a.go b/go/test/typeparam/valimp.dir/a.go new file mode 100644 index 0000000000000000000000000000000000000000..2ed0063cfd6473855a71a27e3327130ae6c553a2 --- /dev/null +++ b/go/test/typeparam/valimp.dir/a.go @@ -0,0 +1,32 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type Value[T any] struct { + val T +} + +// The noinline directive should survive across import, and prevent instantiations +// of these functions from being inlined. + +//go:noinline +func Get[T any](v *Value[T]) T { + return v.val +} + +//go:noinline +func Set[T any](v *Value[T], val T) { + v.val = val +} + +//go:noinline +func (v *Value[T]) Set(val T) { + v.val = val +} + +//go:noinline +func (v *Value[T]) Get() T { + return v.val +} diff --git a/go/test/typeparam/valimp.dir/main.go b/go/test/typeparam/valimp.dir/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e357af4615f1ab74c623d640bb236fddc5723f79 --- /dev/null +++ b/go/test/typeparam/valimp.dir/main.go @@ -0,0 +1,55 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "./a" + "fmt" +) + +func main() { + var v1 a.Value[int] + + a.Set(&v1, 1) + if got, want := a.Get(&v1), 1; got != want { + panic(fmt.Sprintf("Get() == %d, want %d", got, want)) + } + v1.Set(2) + if got, want := v1.Get(), 2; got != want { + panic(fmt.Sprintf("Get() == %d, want %d", got, want)) + } + v1p := new(a.Value[int]) + a.Set(v1p, 3) + if got, want := a.Get(v1p), 3; got != want { + panic(fmt.Sprintf("Get() == %d, want %d", got, want)) + } + + v1p.Set(4) + if got, want := v1p.Get(), 4; got != want { + panic(fmt.Sprintf("Get() == %d, want %d", got, want)) + } + + var v2 a.Value[string] + a.Set(&v2, "a") + if got, want := a.Get(&v2), "a"; got != want { + panic(fmt.Sprintf("Get() == %q, want %q", got, want)) + } + + v2.Set("b") + if got, want := a.Get(&v2), "b"; got != want { + panic(fmt.Sprintf("Get() == %q, want %q", got, want)) + } + + v2p := new(a.Value[string]) + a.Set(v2p, "c") + if got, want := a.Get(v2p), "c"; got != want { + panic(fmt.Sprintf("Get() == %d, want %d", got, want)) + } + + v2p.Set("d") + if got, want := v2p.Get(), "d"; got != want { + panic(fmt.Sprintf("Get() == %d, want %d", got, want)) + } +}