missinggo

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 26, 2019 License: MIT Imports: 33 Imported by: 3,566

README

missinggo

GoDoc

Stuff that supplements Go's stdlib, or isn't significant enough to be in its own repo.

Documentation

Overview

Package missinggo contains miscellaneous helpers used in many of anacrolix' projects.

Index

Examples

Constants

View Source
const MiB = 1 << 20
View Source
const O_ACCMODE = os.O_RDONLY | os.O_WRONLY | os.O_RDWR

Variables

View Source
var ZeroReader zeroReader

Functions

func AddCondToFlags

func AddCondToFlags(cond *sync.Cond, flags ...*Flag)

Adds the sync.Cond to all the given Flag's.

func AddrIP

func AddrIP(addr net.Addr) net.IP

func AddrPort

func AddrPort(addr net.Addr) int

Extracts the port as an integer from an address string.

func BestNamedCertificate

func BestNamedCertificate(c *tls.Config, clientHello *tls.ClientHelloInfo) (*tls.Certificate, bool)

Select the best named certificate per the usual behaviour if c.GetCertificate is nil, and c.NameToCertificate is not.

func CleanURLPath

func CleanURLPath(p string) string

Cleans the (absolute) URL path, removing unnecessary . and .. elements. See "net/http".cleanPath.

func CopyExact

func CopyExact(dest interface{}, src interface{})

Copy elements from src to dst. Panics if the length of src and dst are different.

func Fatal

func Fatal(msg interface{})

func FileInfoAccessTime

func FileInfoAccessTime(fi os.FileInfo) time.Time

Extracts the access time from the FileInfo internals.

func FilePathExists

func FilePathExists(p string) bool

func GetTestName

func GetTestName() string

Returns the name of the test function from the call stack. See http://stackoverflow.com/q/35535635/149482 for another method.

func IsAddrInUse

func IsAddrInUse(err error) bool

func IsEmptyValue

func IsEmptyValue(v reflect.Value) bool

Returns whether the value represents the empty value for its type. Used for example to determine if complex types satisfy the common "omitempty" tag option for marshalling. Taken from http://stackoverflow.com/a/23555352/149482.

func IsZeroValue

func IsZeroValue(i interface{}) bool

func JitterDuration

func JitterDuration(average, plusMinus time.Duration) (ret time.Duration)

Returns random duration in the range [average-plusMinus, average+plusMinus]. Negative plusMinus will likely panic. Be aware that if plusMinus >= average, you may get a zero or negative Duration. The distribution function is unspecified, in case I find a more appropriate one in the future.

func KebabCase

func KebabCase(s string) string

func LimitLen

func LimitLen(b []byte, max ...interface{}) []byte

Sets an upper bound on the len of b. max can be any type that will cast to int64.

func LoadCertificateDir

func LoadCertificateDir(dir string) (certs []tls.Certificate, err error)

func Max

func Max(_less interface{}, vals ...interface{}) interface{}

func MaxInt

func MaxInt(first int64, rest ...interface{}) int64

func MinInt

func MinInt(first interface{}, rest ...interface{}) int64

func MonotonicSince

func MonotonicSince(since MonotonicTime) (ret time.Duration)

func NewSelfSignedCertificate

func NewSelfSignedCertificate() (cert tls.Certificate, err error)

Creates a self-signed certificate in memory for use with tls.Config.

func ParseHostPort

func ParseHostPort(hostport string) (host string, port int, err error)

func PathSplitExt

func PathSplitExt(p string) (ret struct {
	Root, Ext string
})

Splits the pathname p into Root and Ext, such that Root+Ext==p.

Example
fmt.Printf("%q\n", PathSplitExt(".cshrc"))
fmt.Printf("%q\n", PathSplitExt("dir/a.ext"))
fmt.Printf("%q\n", PathSplitExt("dir/.rc"))
fmt.Printf("%q\n", PathSplitExt("home/.secret/file"))
Output:

{"" ".cshrc"}
{"dir/a" ".ext"}
{"dir/" ".rc"}
{"home/.secret/file" ""}

func StoppedFuncTimer

func StoppedFuncTimer(f func()) (t *time.Timer)

Returns a time.Timer that calls f. The timer is initially stopped.

func StringTruth

func StringTruth(s string) (ret bool)

func URLJoinSubPath

func URLJoinSubPath(base, rel string) string

func URLOpaquePath

func URLOpaquePath(u *url.URL) string

Returns URL opaque as an unrooted path.

func Unchomp

func Unchomp(s string) string

func WaitEvents

func WaitEvents(l sync.Locker, evs ...*Event)

func WriteStack

func WriteStack(w io.Writer, stack []uintptr)

Types

type ChanCond

type ChanCond struct {
	// contains filtered or unexported fields
}

func (*ChanCond) Broadcast

func (me *ChanCond) Broadcast()

func (*ChanCond) Signal

func (me *ChanCond) Signal()

func (*ChanCond) Wait

func (me *ChanCond) Wait() <-chan struct{}

type ContextedReader

type ContextedReader struct {
	R   ReadContexter
	Ctx context.Context
}

func (ContextedReader) Read

func (me ContextedReader) Read(b []byte) (int, error)

type Encoding

type Encoding interface {
	EncodeToString([]byte) string
	DecodeString(string) ([]byte, error)
}

An interface for "encoding/base64".Encoder

type Event

type Event struct {
	// contains filtered or unexported fields
}

Events are boolean flags that provide a channel that's closed when true. This could go in the sync package, but that's more of a debug wrapper on the standard library sync.

func (*Event) C

func (me *Event) C() <-chan struct{}

Returns a chan that is closed when the event is true.

func (*Event) Clear

func (me *Event) Clear()

TODO: Merge into Set.

func (*Event) IsSet

func (me *Event) IsSet() bool

TODO: Change to Get.

func (*Event) LockedChan

func (me *Event) LockedChan(lock sync.Locker) <-chan struct{}

func (*Event) Set

func (me *Event) Set() (first bool)

Set the event to true/on.

func (*Event) SetBool

func (me *Event) SetBool(b bool)

TODO: Merge into Set.

func (*Event) Wait

func (me *Event) Wait()

type Flag

type Flag struct {
	Conds map[*sync.Cond]struct{}
	// contains filtered or unexported fields
}

Flag represents a boolean value, that signals sync.Cond's when it changes. It's not concurrent safe by intention.

func (*Flag) Get

func (me *Flag) Get() bool

func (*Flag) Set

func (me *Flag) Set(value bool)

type HostMaybePort

type HostMaybePort struct {
	Host   string // Just the host, with no port.
	Port   int    // The port if NoPort is false.
	NoPort bool   // Whether a port is specified.
	Err    error  // The error returned from net.SplitHostPort.
}

Represents a split host port.

func SplitHostMaybePort

func SplitHostMaybePort(hostport string) HostMaybePort

Parse a "hostport" string, a concept that floats around the stdlib a lot and is painful to work with. If no port is present, what's usually present is just the host.

func (*HostMaybePort) String

func (me *HostMaybePort) String() string

type IdentityEncoding

type IdentityEncoding struct{}

An encoding that does nothing.

func (IdentityEncoding) DecodeString

func (IdentityEncoding) DecodeString(s string) ([]byte, error)

func (IdentityEncoding) EncodeToString

func (IdentityEncoding) EncodeToString(b []byte) string

type IndentMap

type IndentMap struct {
	expvar.Map
}

func NewExpvarIndentMap

func NewExpvarIndentMap(name string) *IndentMap

func (*IndentMap) String

func (v *IndentMap) String() string

type IpPort

type IpPort struct {
	IP   net.IP
	Port uint16
}

func IpPortFromNetAddr

func IpPortFromNetAddr(na net.Addr) IpPort

func (IpPort) String

func (me IpPort) String() string

type MonotonicTime

type MonotonicTime struct {
	// contains filtered or unexported fields
}

Monotonic time represents time since an arbitrary point in the past, where the concept of now is only ever moving in a positive direction.

func MonotonicNow

func MonotonicNow() MonotonicTime

Consecutive calls always produce the same or greater time than previous calls.

func (MonotonicTime) Sub

func (me MonotonicTime) Sub(other MonotonicTime) time.Duration

type MultiLess added in v0.2.0

type MultiLess struct {
	// contains filtered or unexported fields
}

func (*MultiLess) Final added in v0.2.0

func (me *MultiLess) Final() bool

func (*MultiLess) FinalOk added in v0.2.0

func (me *MultiLess) FinalOk() (left, ok bool)

func (*MultiLess) Less added in v0.2.0

func (me *MultiLess) Less() bool

func (*MultiLess) Next added in v0.2.0

func (me *MultiLess) Next(f SameLessFunc)

func (*MultiLess) NextBool added in v0.2.0

func (me *MultiLess) NextBool(l, r bool)

func (*MultiLess) StrictNext added in v0.2.0

func (me *MultiLess) StrictNext(same, less bool)

type Operation

type Operation struct {
	// contains filtered or unexported fields
}

func (Operation) Unlock

func (op Operation) Unlock()

type RWLocker

type RWLocker interface {
	sync.Locker
	RLock()
	RUnlock()
}

type ReadContexter

type ReadContexter interface {
	ReadContext(context.Context, []byte) (int, error)
}

type ReadSeekContexter

type ReadSeekContexter interface {
	io.ReadSeeker
	ReadContexter
}

func NewSectionReadSeeker

func NewSectionReadSeeker(base io.ReadSeeker, off, size int64) (ret ReadSeekContexter)

Returns a ReadSeeker on a section of another ReadSeeker.

type RunLengthEncoder

type RunLengthEncoder interface {
	// Add a series of identical elements to the stream.
	Append(element interface{}, count uint64)
	// Emit the current element and its count if non-zero without waiting for
	// the element to change.
	Flush()
}

A RunLengthEncoder counts successive duplicate elements and emits the element and the run length when the element changes or the encoder is flushed.

func NewRunLengthEncoder

func NewRunLengthEncoder(eachRun func(element interface{}, count uint64)) RunLengthEncoder

Creates a new RunLengthEncoder. eachRun is called when an element and its count is emitted, per the RunLengthEncoder interface.

Example
package main

import (
	"fmt"

	"github.com/anacrolix/missinggo"
)

func main() {
	var s string
	rle := missinggo.NewRunLengthEncoder(func(e interface{}, count uint64) {
		s += fmt.Sprintf("%d%c", count, e)
	})
	for _, e := range "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" {
		rle.Append(e, 1)
	}
	rle.Flush()
	fmt.Println(s)
}
Output:

12W1B12W3B24W1B14W

type SameLessFunc added in v0.2.0

type SameLessFunc func() (same, less bool)

type SectionWriter

type SectionWriter struct {
	// contains filtered or unexported fields
}

func NewSectionWriter

func NewSectionWriter(w io.WriterAt, off, len int64) *SectionWriter

func (*SectionWriter) WriteAt

func (me *SectionWriter) WriteAt(b []byte, off int64) (n int, err error)

type SingleFlight

type SingleFlight struct {
	// contains filtered or unexported fields
}

func (*SingleFlight) Lock

func (me *SingleFlight) Lock(id string) Operation

func (*SingleFlight) Unlock

func (me *SingleFlight) Unlock(id string)

type SqliteTime

type SqliteTime time.Time

func (*SqliteTime) Scan

func (me *SqliteTime) Scan(src interface{}) error

type StatWriter

type StatWriter struct {
	Written int64
	// contains filtered or unexported fields
}

func NewStatWriter

func NewStatWriter(w io.Writer) *StatWriter

func (*StatWriter) Write

func (me *StatWriter) Write(b []byte) (n int, err error)

type StatusResponseWriter

type StatusResponseWriter struct {
	http.ResponseWriter
	Code         int
	BytesWritten int64
	Started      time.Time
	Ttfb         time.Duration // Time to first byte
	GotFirstByte bool
	WroteHeader  Event
	Hijacked     bool
}

A http.ResponseWriter that tracks the status of the response. The status code, and number of bytes written for example.

func (*StatusResponseWriter) Hijack

func (me *StatusResponseWriter) Hijack() (c net.Conn, b *bufio.ReadWriter, err error)

func (*StatusResponseWriter) Write

func (me *StatusResponseWriter) Write(b []byte) (n int, err error)

func (*StatusResponseWriter) WriteHeader

func (me *StatusResponseWriter) WriteHeader(code int)

type SynchronizedEvent

type SynchronizedEvent struct {
	// contains filtered or unexported fields
}

func (*SynchronizedEvent) C

func (me *SynchronizedEvent) C() <-chan struct{}

func (*SynchronizedEvent) Clear

func (me *SynchronizedEvent) Clear()

func (*SynchronizedEvent) Set

func (me *SynchronizedEvent) Set()

Directories

Path Synopsis
Package bitmap provides a []bool/bitmap implementation with standardized iteration.
Package bitmap provides a []bool/bitmap implementation with standardized iteration.
cmd
gd
nop
container
Package pproffd is for detecting resource leaks due to unclosed handles.
Package pproffd is for detecting resource leaks due to unclosed handles.
Package prioritybitmap implements a set of integers ordered by attached priorities.
Package prioritybitmap implements a set of integers ordered by attached priorities.
Package slices has several utilities for operating on slices given Go's lack of generic types.
Package slices has several utilities for operating on slices given Go's lack of generic types.
x

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL