code
stringlengths 11
335k
| docstring
stringlengths 20
11.8k
| func_name
stringlengths 1
100
| language
stringclasses 1
value | repo
stringclasses 245
values | path
stringlengths 4
144
| url
stringlengths 43
214
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func Major(dev uint64) uint32 {
major := uint32((dev & 0x00000000000fff00) >> 8)
major |= uint32((dev & 0xfffff00000000000) >> 32)
return major
} | Major returns the major component of a Linux device number. | Major | go | flynn/flynn | vendor/golang.org/x/sys/unix/dev_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/dev_linux.go | BSD-3-Clause |
func Minor(dev uint64) uint32 {
minor := uint32((dev & 0x00000000000000ff) >> 0)
minor |= uint32((dev & 0x00000ffffff00000) >> 12)
return minor
} | Minor returns the minor component of a Linux device number. | Minor | go | flynn/flynn | vendor/golang.org/x/sys/unix/dev_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/dev_linux.go | BSD-3-Clause |
func Mkdev(major, minor uint32) uint64 {
dev := (uint64(major) & 0x00000fff) << 8
dev |= (uint64(major) & 0xfffff000) << 32
dev |= (uint64(minor) & 0x000000ff) << 0
dev |= (uint64(minor) & 0xffffff00) << 12
return dev
} | Mkdev returns a Linux device number generated from the given major and minor
components. | Mkdev | go | flynn/flynn | vendor/golang.org/x/sys/unix/dev_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/dev_linux.go | BSD-3-Clause |
func ReadDirent(fd int, buf []byte) (n int, err error) {
// Final argument is (basep *uintptr) and the syscall doesn't take nil.
// 64 bits should be enough. (32 bits isn't even on 386). Since the
// actual system call is getdirentries64, 64 is a good guess.
// TODO(rsc): Can we use a single global basep for all calls?
var base = (*uintptr)(unsafe.Pointer(new(uint64)))
return Getdirentries(fd, buf, base)
} | ReadDirent reads directory entries from fd and writes them into buf. | ReadDirent | go | flynn/flynn | vendor/golang.org/x/sys/unix/readdirent_getdirentries.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go | BSD-3-Clause |
func GetsockoptString(fd, level, opt int) (string, error) {
buf := make([]byte, 256)
vallen := _Socklen(len(buf))
err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
if err != nil {
return "", err
}
return string(buf[:vallen-1]), nil
} | GetsockoptString returns the string value of the socket option opt for the
socket associated with fd at the given socket level. | GetsockoptString | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_solaris.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_solaris.go | BSD-3-Clause |
func ReadDirent(fd int, buf []byte) (n int, err error) {
// Final argument is (basep *uintptr) and the syscall doesn't take nil.
// TODO(rsc): Can we use a single global basep for all calls?
return Getdents(fd, buf, new(uintptr))
} | ReadDirent reads directory entries from fd and writes them into buf. | ReadDirent | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_solaris.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_solaris.go | BSD-3-Clause |
func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
valptr, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0)
var err error
if errno != 0 {
err = errno
}
return int(valptr), err
} | FcntlInt performs a fcntl syscall on fd with the provided command and argument. | FcntlInt | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_solaris.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_solaris.go | BSD-3-Clause |
func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
_, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0)
if e1 != 0 {
return e1
}
return nil
} | FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. | FcntlFlock | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_solaris.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_solaris.go | BSD-3-Clause |
func Futimes(fd int, tv []Timeval) error {
if tv == nil {
return futimesat(fd, nil, nil)
}
if len(tv) != 2 {
return EINVAL
}
return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
} | Solaris doesn't have an futimes function because it allows NULL to be
specified as the path for futimesat. However, Go doesn't like
NULL-style string interfaces, so this simple wrapper is provided. | Futimes | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_solaris.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_solaris.go | BSD-3-Clause |
func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func callutimes(_p0 uintptr, times uintptr) (r1 uintptr, e1 Errno) {
r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_utimes)), 2, _p0, times, 0, 0, 0, 0)
return
} | Implemented in runtime/syscall_aix.go. | rawSyscall6 | go | flynn/flynn | vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go | BSD-3-Clause |
func Gettimeofday(tv *Timeval) (err error) {
// The tv passed to gettimeofday must be non-nil
// but is otherwise unused. The answers come back
// in the two registers.
sec, usec, err := gettimeofday(tv)
tv.Sec = sec
tv.Usec = usec
return err
} | sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) | Gettimeofday | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go | BSD-3-Clause |
func Pledge(promises, execpromises string) error {
maj, min, err := majmin()
if err != nil {
return err
}
err = pledgeAvailable(maj, min, execpromises)
if err != nil {
return err
}
pptr, err := syscall.BytePtrFromString(promises)
if err != nil {
return err
}
// This variable will hold either a nil unsafe.Pointer or
// an unsafe.Pointer to a string (execpromises).
var expr unsafe.Pointer
// If we're running on OpenBSD > 6.2, pass execpromises to the syscall.
if maj > 6 || (maj == 6 && min > 2) {
exptr, err := syscall.BytePtrFromString(execpromises)
if err != nil {
return err
}
expr = unsafe.Pointer(exptr)
}
_, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(unsafe.Pointer(pptr)), uintptr(expr), 0)
if e != 0 {
return e
}
return nil
} | Pledge implements the pledge syscall.
The pledge syscall does not accept execpromises on OpenBSD releases
before 6.3.
execpromises must be empty when Pledge is called on OpenBSD
releases predating 6.3, otherwise an error will be returned.
For more information see pledge(2). | Pledge | go | flynn/flynn | vendor/golang.org/x/sys/unix/pledge_openbsd.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/pledge_openbsd.go | BSD-3-Clause |
func PledgePromises(promises string) error {
maj, min, err := majmin()
if err != nil {
return err
}
err = pledgeAvailable(maj, min, "")
if err != nil {
return err
}
// This variable holds the execpromises and is always nil.
var expr unsafe.Pointer
pptr, err := syscall.BytePtrFromString(promises)
if err != nil {
return err
}
_, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(unsafe.Pointer(pptr)), uintptr(expr), 0)
if e != 0 {
return e
}
return nil
} | PledgePromises implements the pledge syscall.
This changes the promises and leaves the execpromises untouched.
For more information see pledge(2). | PledgePromises | go | flynn/flynn | vendor/golang.org/x/sys/unix/pledge_openbsd.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/pledge_openbsd.go | BSD-3-Clause |
func PledgeExecpromises(execpromises string) error {
maj, min, err := majmin()
if err != nil {
return err
}
err = pledgeAvailable(maj, min, execpromises)
if err != nil {
return err
}
// This variable holds the promises and is always nil.
var pptr unsafe.Pointer
exptr, err := syscall.BytePtrFromString(execpromises)
if err != nil {
return err
}
_, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(pptr), uintptr(unsafe.Pointer(exptr)), 0)
if e != 0 {
return e
}
return nil
} | PledgeExecpromises implements the pledge syscall.
This changes the execpromises and leaves the promises untouched.
For more information see pledge(2). | PledgeExecpromises | go | flynn/flynn | vendor/golang.org/x/sys/unix/pledge_openbsd.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/pledge_openbsd.go | BSD-3-Clause |
func majmin() (major int, minor int, err error) {
var v Utsname
err = Uname(&v)
if err != nil {
return
}
major, err = strconv.Atoi(string(v.Release[0]))
if err != nil {
err = errors.New("cannot parse major version number returned by uname")
return
}
minor, err = strconv.Atoi(string(v.Release[2]))
if err != nil {
err = errors.New("cannot parse minor version number returned by uname")
return
}
return
} | majmin returns major and minor version number for an OpenBSD system. | majmin | go | flynn/flynn | vendor/golang.org/x/sys/unix/pledge_openbsd.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/pledge_openbsd.go | BSD-3-Clause |
func pledgeAvailable(maj, min int, execpromises string) error {
// If OpenBSD <= 5.9, pledge is not available.
if (maj == 5 && min != 9) || maj < 5 {
return fmt.Errorf("pledge syscall is not available on OpenBSD %d.%d", maj, min)
}
// If OpenBSD <= 6.2 and execpromises is not empty,
// return an error - execpromises is not available before 6.3
if (maj < 6 || (maj == 6 && min <= 2)) && execpromises != "" {
return fmt.Errorf("cannot use execpromises on OpenBSD %d.%d", maj, min)
}
return nil
} | pledgeAvailable checks for availability of the pledge(2) syscall
based on the running OpenBSD version. | pledgeAvailable | go | flynn/flynn | vendor/golang.org/x/sys/unix/pledge_openbsd.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/pledge_openbsd.go | BSD-3-Clause |
func IoctlSetPointerInt(fd int, req uint, value int) error {
v := int32(value)
return ioctl(fd, req, uintptr(unsafe.Pointer(&v)))
} | IoctlSetPointerInt performs an ioctl operation which sets an
integer value on fd, using the specified request number. The ioctl
argument is called with a pointer to the integer value, rather than
passing the integer value directly. | IoctlSetPointerInt | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func IoctlSetInt(fd int, req uint, value int) error {
return ioctl(fd, req, uintptr(value))
} | IoctlSetInt performs an ioctl operation which sets an integer value
on fd, using the specified request number. | IoctlSetInt | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func IoctlGetInt(fd int, req uint) (int, error) {
var value int
err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
return value, err
} | IoctlGetInt performs an ioctl operation which gets an integer value
from fd, using the specified request number. | IoctlGetInt | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func GetsockoptString(fd, level, opt int) (string, error) {
buf := make([]byte, 256)
vallen := _Socklen(len(buf))
err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
if err != nil {
if err == ERANGE {
buf = make([]byte, vallen)
err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
}
if err != nil {
return "", err
}
}
return string(buf[:vallen-1]), nil
} | GetsockoptString returns the string value of the socket option opt for the
socket associated with fd at the given socket level. | GetsockoptString | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func SetsockoptSockFprog(fd, level, opt int, fprog *SockFprog) error {
return setsockopt(fd, level, opt, unsafe.Pointer(fprog), unsafe.Sizeof(*fprog))
} | SetsockoptSockFprog attaches a classic BPF or an extended BPF program to a
socket to filter incoming packets. See 'man 7 socket' for usage information. | SetsockoptSockFprog | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func KeyctlString(cmd int, id int) (string, error) {
// We must loop as the string data may change in between the syscalls.
// We could allocate a large buffer here to reduce the chance that the
// syscall needs to be called twice; however, this is unnecessary as
// the performance loss is negligible.
var buffer []byte
for {
// Try to fill the buffer with data
length, err := KeyctlBuffer(cmd, id, buffer, 0)
if err != nil {
return "", err
}
// Check if the data was written
if length <= len(buffer) {
// Exclude the null terminator
return string(buffer[:length-1]), nil
}
// Make a bigger buffer if needed
buffer = make([]byte, length)
}
} | KeyctlString calls keyctl commands which return a string.
These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY. | KeyctlString | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
createInt := 0
if create {
createInt = 1
}
return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
} | KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
See the full documentation at:
http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html | KeyctlGetKeyringID | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func KeyctlSetperm(id int, perm uint32) error {
_, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
return err
} | KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
key handle permission mask as described in the "keyctl setperm" section of
http://man7.org/linux/man-pages/man1/keyctl.1.html.
See the full documentation at:
http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html | KeyctlSetperm | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
} | KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
See the full documentation at:
http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html | KeyctlJoinSessionKeyring | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
} | KeyctlSearch implements the KEYCTL_SEARCH command.
See the full documentation at:
http://man7.org/linux/man-pages/man3/keyctl_search.3.html | KeyctlSearch | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
} | KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
of Iovec (each of which represents a buffer) instead of a single buffer.
See the full documentation at:
http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html | KeyctlInstantiateIOV | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
} | KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
computes a Diffie-Hellman shared secret based on the provide params. The
secret is written to the provided buffer and the returned size is the number
of bytes written (returning an error if there is insufficient space in the
buffer). If a nil buffer is passed in, this function returns the minimum
buffer length needed to store the appropriate data. Note that this differs
from KEYCTL_READ's behavior which always returns the requested payload size.
See the full documentation at:
http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html | KeyctlDHCompute | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func BindToDevice(fd int, device string) (err error) {
return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
} | BindToDevice binds the socket associated with fd to device. | BindToDevice | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
var p unsafe.Pointer
if len(iovs) > 0 {
p = unsafe.Pointer(&iovs[0])
}
n, _, errno := Syscall6(SYS_VMSPLICE, uintptr(fd), uintptr(p), uintptr(len(iovs)), uintptr(flags), 0, 0)
if errno != 0 {
return 0, syscall.Errno(errno)
}
return int(n), nil
} | Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
using the specified flags. | Vmsplice | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func NewFileHandle(handleType int32, handle []byte) FileHandle {
const hdrSize = unsafe.Sizeof(fileHandle{})
buf := make([]byte, hdrSize+uintptr(len(handle)))
copy(buf[hdrSize:], handle)
fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
fh.Type = handleType
fh.Bytes = uint32(len(handle))
return FileHandle{fh}
} | NewFileHandle constructs a FileHandle. | NewFileHandle | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func NameToHandleAt(dirfd int, path string, flags int) (handle FileHandle, mountID int, err error) {
var mid _C_int
// Try first with a small buffer, assuming the handle will
// only be 32 bytes.
size := uint32(32 + unsafe.Sizeof(fileHandle{}))
didResize := false
for {
buf := make([]byte, size)
fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
fh.Bytes = size - uint32(unsafe.Sizeof(fileHandle{}))
err = nameToHandleAt(dirfd, path, fh, &mid, flags)
if err == EOVERFLOW {
if didResize {
// We shouldn't need to resize more than once
return
}
didResize = true
size = fh.Bytes + uint32(unsafe.Sizeof(fileHandle{}))
continue
}
if err != nil {
return
}
return FileHandle{fh}, int(mid), nil
}
} | NameToHandleAt wraps the name_to_handle_at system call; it obtains
a handle for a path name. | NameToHandleAt | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func OpenByHandleAt(mountFD int, handle FileHandle, flags int) (fd int, err error) {
return openByHandleAt(mountFD, handle.fileHandle, flags)
} | OpenByHandleAt wraps the open_by_handle_at system call; it opens a
file via a handle as previously returned by NameToHandleAt. | OpenByHandleAt | go | flynn/flynn | vendor/golang.org/x/sys/unix/syscall_linux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/sys/unix/syscall_linux.go | BSD-3-Clause |
func (NopResetter) Reset() {} | Reset implements the Reset method of the Transformer interface. | Reset | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func NewReader(r io.Reader, t Transformer) *Reader {
t.Reset()
return &Reader{
r: r,
t: t,
dst: make([]byte, defaultBufSize),
src: make([]byte, defaultBufSize),
}
} | NewReader returns a new Reader that wraps r by transforming the bytes read
via t. It calls Reset on t. | NewReader | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func (r *Reader) Read(p []byte) (int, error) {
n, err := 0, error(nil)
for {
// Copy out any transformed bytes and return the final error if we are done.
if r.dst0 != r.dst1 {
n = copy(p, r.dst[r.dst0:r.dst1])
r.dst0 += n
if r.dst0 == r.dst1 && r.transformComplete {
return n, r.err
}
return n, nil
} else if r.transformComplete {
return 0, r.err
}
// Try to transform some source bytes, or to flush the transformer if we
// are out of source bytes. We do this even if r.r.Read returned an error.
// As the io.Reader documentation says, "process the n > 0 bytes returned
// before considering the error".
if r.src0 != r.src1 || r.err != nil {
r.dst0 = 0
r.dst1, n, err = r.t.Transform(r.dst, r.src[r.src0:r.src1], r.err == io.EOF)
r.src0 += n
switch {
case err == nil:
if r.src0 != r.src1 {
r.err = errInconsistentByteCount
}
// The Transform call was successful; we are complete if we
// cannot read more bytes into src.
r.transformComplete = r.err != nil
continue
case err == ErrShortDst && (r.dst1 != 0 || n != 0):
// Make room in dst by copying out, and try again.
continue
case err == ErrShortSrc && r.src1-r.src0 != len(r.src) && r.err == nil:
// Read more bytes into src via the code below, and try again.
default:
r.transformComplete = true
// The reader error (r.err) takes precedence over the
// transformer error (err) unless r.err is nil or io.EOF.
if r.err == nil || r.err == io.EOF {
r.err = err
}
continue
}
}
// Move any untransformed source bytes to the start of the buffer
// and read more bytes.
if r.src0 != 0 {
r.src0, r.src1 = 0, copy(r.src, r.src[r.src0:r.src1])
}
n, r.err = r.r.Read(r.src[r.src1:])
r.src1 += n
}
} | Read implements the io.Reader interface. | Read | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func NewWriter(w io.Writer, t Transformer) *Writer {
t.Reset()
return &Writer{
w: w,
t: t,
dst: make([]byte, defaultBufSize),
src: make([]byte, defaultBufSize),
}
} | NewWriter returns a new Writer that wraps w by transforming the bytes written
via t. It calls Reset on t. | NewWriter | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func (w *Writer) Write(data []byte) (n int, err error) {
src := data
if w.n > 0 {
// Append bytes from data to the last remainder.
// TODO: limit the amount copied on first try.
n = copy(w.src[w.n:], data)
w.n += n
src = w.src[:w.n]
}
for {
nDst, nSrc, err := w.t.Transform(w.dst, src, false)
if _, werr := w.w.Write(w.dst[:nDst]); werr != nil {
return n, werr
}
src = src[nSrc:]
if w.n == 0 {
n += nSrc
} else if len(src) <= n {
// Enough bytes from w.src have been consumed. We make src point
// to data instead to reduce the copying.
w.n = 0
n -= len(src)
src = data[n:]
if n < len(data) && (err == nil || err == ErrShortSrc) {
continue
}
}
switch err {
case ErrShortDst:
// This error is okay as long as we are making progress.
if nDst > 0 || nSrc > 0 {
continue
}
case ErrShortSrc:
if len(src) < len(w.src) {
m := copy(w.src, src)
// If w.n > 0, bytes from data were already copied to w.src and n
// was already set to the number of bytes consumed.
if w.n == 0 {
n += m
}
w.n = m
err = nil
} else if nDst > 0 || nSrc > 0 {
// Not enough buffer to store the remainder. Keep processing as
// long as there is progress. Without this case, transforms that
// require a lookahead larger than the buffer may result in an
// error. This is not something one may expect to be common in
// practice, but it may occur when buffers are set to small
// sizes during testing.
continue
}
case nil:
if w.n > 0 {
err = errInconsistentByteCount
}
}
return n, err
}
} | Write implements the io.Writer interface. If there are not enough
bytes available to complete a Transform, the bytes will be buffered
for the next write. Call Close to convert the remaining bytes. | Write | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func (w *Writer) Close() error {
src := w.src[:w.n]
for {
nDst, nSrc, err := w.t.Transform(w.dst, src, true)
if _, werr := w.w.Write(w.dst[:nDst]); werr != nil {
return werr
}
if err != ErrShortDst {
return err
}
src = src[nSrc:]
}
} | Close implements the io.Closer interface. | Close | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func Chain(t ...Transformer) Transformer {
if len(t) == 0 {
return nop{}
}
c := &chain{link: make([]link, len(t)+1)}
for i, tt := range t {
c.link[i].t = tt
}
// Allocate intermediate buffers.
b := make([][defaultBufSize]byte, len(t)-1)
for i := range b {
c.link[i+1].b = b[i][:]
}
return c
} | Chain returns a Transformer that applies t in sequence. | Chain | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func (c *chain) Reset() {
for i, l := range c.link {
if l.t != nil {
l.t.Reset()
}
c.link[i].p, c.link[i].n = 0, 0
}
} | Reset resets the state of Chain. It calls Reset on all the Transformers. | Reset | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func (c *chain) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
// Set up src and dst in the chain.
srcL := &c.link[0]
dstL := &c.link[len(c.link)-1]
srcL.b, srcL.p, srcL.n = src, 0, len(src)
dstL.b, dstL.n = dst, 0
var lastFull, needProgress bool // for detecting progress
// i is the index of the next Transformer to apply, for i in [low, high].
// low is the lowest index for which c.link[low] may still produce bytes.
// high is the highest index for which c.link[high] has a Transformer.
// The error returned by Transform determines whether to increase or
// decrease i. We try to completely fill a buffer before converting it.
for low, i, high := c.errStart, c.errStart, len(c.link)-2; low <= i && i <= high; {
in, out := &c.link[i], &c.link[i+1]
nDst, nSrc, err0 := in.t.Transform(out.dst(), in.src(), atEOF && low == i)
out.n += nDst
in.p += nSrc
if i > 0 && in.p == in.n {
in.p, in.n = 0, 0
}
needProgress, lastFull = lastFull, false
switch err0 {
case ErrShortDst:
// Process the destination buffer next. Return if we are already
// at the high index.
if i == high {
return dstL.n, srcL.p, ErrShortDst
}
if out.n != 0 {
i++
// If the Transformer at the next index is not able to process any
// source bytes there is nothing that can be done to make progress
// and the bytes will remain unprocessed. lastFull is used to
// detect this and break out of the loop with a fatal error.
lastFull = true
continue
}
// The destination buffer was too small, but is completely empty.
// Return a fatal error as this transformation can never complete.
c.fatalError(i, errShortInternal)
case ErrShortSrc:
if i == 0 {
// Save ErrShortSrc in err. All other errors take precedence.
err = ErrShortSrc
break
}
// Source bytes were depleted before filling up the destination buffer.
// Verify we made some progress, move the remaining bytes to the errStart
// and try to get more source bytes.
if needProgress && nSrc == 0 || in.n-in.p == len(in.b) {
// There were not enough source bytes to proceed while the source
// buffer cannot hold any more bytes. Return a fatal error as this
// transformation can never complete.
c.fatalError(i, errShortInternal)
break
}
// in.b is an internal buffer and we can make progress.
in.p, in.n = 0, copy(in.b, in.src())
fallthrough
case nil:
// if i == low, we have depleted the bytes at index i or any lower levels.
// In that case we increase low and i. In all other cases we decrease i to
// fetch more bytes before proceeding to the next index.
if i > low {
i--
continue
}
default:
c.fatalError(i, err0)
}
// Exhausted level low or fatal error: increase low and continue
// to process the bytes accepted so far.
i++
low = i
}
// If c.errStart > 0, this means we found a fatal error. We will clear
// all upstream buffers. At this point, no more progress can be made
// downstream, as Transform would have bailed while handling ErrShortDst.
if c.errStart > 0 {
for i := 1; i < c.errStart; i++ {
c.link[i].p, c.link[i].n = 0, 0
}
err, c.errStart, c.err = c.err, 0, nil
}
return dstL.n, srcL.p, err
} | Transform applies the transformers of c in sequence. | Transform | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func RemoveFunc(f func(r rune) bool) Transformer {
return removeF(f)
} | Deprecated: Use runes.Remove instead. | RemoveFunc | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func (t removeF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
for r, sz := rune(0), 0; len(src) > 0; src = src[sz:] {
if r = rune(src[0]); r < utf8.RuneSelf {
sz = 1
} else {
r, sz = utf8.DecodeRune(src)
if sz == 1 {
// Invalid rune.
if !atEOF && !utf8.FullRune(src) {
err = ErrShortSrc
break
}
// We replace illegal bytes with RuneError. Not doing so might
// otherwise turn a sequence of invalid UTF-8 into valid UTF-8.
// The resulting byte sequence may subsequently contain runes
// for which t(r) is true that were passed unnoticed.
if !t(r) {
if nDst+3 > len(dst) {
err = ErrShortDst
break
}
nDst += copy(dst[nDst:], "\uFFFD")
}
nSrc++
continue
}
}
if !t(r) {
if nDst+sz > len(dst) {
err = ErrShortDst
break
}
nDst += copy(dst[nDst:], src[:sz])
}
nSrc += sz
}
return
} | Transform implements the Transformer interface. | Transform | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func grow(b []byte, n int) []byte {
m := len(b)
if m <= 32 {
m = 64
} else if m <= 256 {
m *= 2
} else {
m += m >> 1
}
buf := make([]byte, m)
copy(buf, b[:n])
return buf
} | grow returns a new []byte that is longer than b, and copies the first n bytes
of b to the start of the new slice. | grow | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func String(t Transformer, s string) (result string, n int, err error) {
t.Reset()
if s == "" {
// Fast path for the common case for empty input. Results in about a
// 86% reduction of running time for BenchmarkStringLowerEmpty.
if _, _, err := t.Transform(nil, nil, true); err == nil {
return "", 0, nil
}
}
// Allocate only once. Note that both dst and src escape when passed to
// Transform.
buf := [2 * initialBufSize]byte{}
dst := buf[:initialBufSize:initialBufSize]
src := buf[initialBufSize : 2*initialBufSize]
// The input string s is transformed in multiple chunks (starting with a
// chunk size of initialBufSize). nDst and nSrc are per-chunk (or
// per-Transform-call) indexes, pDst and pSrc are overall indexes.
nDst, nSrc := 0, 0
pDst, pSrc := 0, 0
// pPrefix is the length of a common prefix: the first pPrefix bytes of the
// result will equal the first pPrefix bytes of s. It is not guaranteed to
// be the largest such value, but if pPrefix, len(result) and len(s) are
// all equal after the final transform (i.e. calling Transform with atEOF
// being true returned nil error) then we don't need to allocate a new
// result string.
pPrefix := 0
for {
// Invariant: pDst == pPrefix && pSrc == pPrefix.
n := copy(src, s[pSrc:])
nDst, nSrc, err = t.Transform(dst, src[:n], pSrc+n == len(s))
pDst += nDst
pSrc += nSrc
// TODO: let transformers implement an optional Spanner interface, akin
// to norm's QuickSpan. This would even allow us to avoid any allocation.
if !bytes.Equal(dst[:nDst], src[:nSrc]) {
break
}
pPrefix = pSrc
if err == ErrShortDst {
// A buffer can only be short if a transformer modifies its input.
break
} else if err == ErrShortSrc {
if nSrc == 0 {
// No progress was made.
break
}
// Equal so far and !atEOF, so continue checking.
} else if err != nil || pPrefix == len(s) {
return string(s[:pPrefix]), pPrefix, err
}
}
// Post-condition: pDst == pPrefix + nDst && pSrc == pPrefix + nSrc.
// We have transformed the first pSrc bytes of the input s to become pDst
// transformed bytes. Those transformed bytes are discontiguous: the first
// pPrefix of them equal s[:pPrefix] and the last nDst of them equal
// dst[:nDst]. We copy them around, into a new dst buffer if necessary, so
// that they become one contiguous slice: dst[:pDst].
if pPrefix != 0 {
newDst := dst
if pDst > len(newDst) {
newDst = make([]byte, len(s)+nDst-nSrc)
}
copy(newDst[pPrefix:pDst], dst[:nDst])
copy(newDst[:pPrefix], s[:pPrefix])
dst = newDst
}
// Prevent duplicate Transform calls with atEOF being true at the end of
// the input. Also return if we have an unrecoverable error.
if (err == nil && pSrc == len(s)) ||
(err != nil && err != ErrShortDst && err != ErrShortSrc) {
return string(dst[:pDst]), pSrc, err
}
// Transform the remaining input, growing dst and src buffers as necessary.
for {
n := copy(src, s[pSrc:])
nDst, nSrc, err := t.Transform(dst[pDst:], src[:n], pSrc+n == len(s))
pDst += nDst
pSrc += nSrc
// If we got ErrShortDst or ErrShortSrc, do not grow as long as we can
// make progress. This may avoid excessive allocations.
if err == ErrShortDst {
if nDst == 0 {
dst = grow(dst, pDst)
}
} else if err == ErrShortSrc {
if nSrc == 0 {
src = grow(src, 0)
}
} else if err != nil || pSrc == len(s) {
return string(dst[:pDst]), pSrc, err
}
}
} | String returns a string with the result of converting s[:n] using t, where
n <= len(s). If err == nil, n will be len(s). It calls Reset on t. | String | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func Bytes(t Transformer, b []byte) (result []byte, n int, err error) {
return doAppend(t, 0, make([]byte, len(b)), b)
} | Bytes returns a new byte slice with the result of converting b[:n] using t,
where n <= len(b). If err == nil, n will be len(b). It calls Reset on t. | Bytes | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func Append(t Transformer, dst, src []byte) (result []byte, n int, err error) {
if len(dst) == cap(dst) {
n := len(src) + len(dst) // It is okay for this to be 0.
b := make([]byte, n)
dst = b[:copy(b, dst)]
}
return doAppend(t, len(dst), dst[:cap(dst)], src)
} | Append appends the result of converting src[:n] using t to dst, where
n <= len(src), If err == nil, n will be len(src). It calls Reset on t. | Append | go | flynn/flynn | vendor/golang.org/x/text/transform/transform.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/transform/transform.go | BSD-3-Clause |
func Direction(b []byte) bidi.Direction {
for i := 0; i < len(b); {
e, sz := bidi.Lookup(b[i:])
if sz == 0 {
i++
}
c := e.Class()
if c == bidi.R || c == bidi.AL || c == bidi.AN {
return bidi.RightToLeft
}
i += sz
}
return bidi.LeftToRight
} | Direction reports the direction of the given label as defined by RFC 5893.
The Bidi Rule does not have to be applied to labels of the category
LeftToRight. | Direction | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func DirectionString(s string) bidi.Direction {
for i := 0; i < len(s); {
e, sz := bidi.LookupString(s[i:])
if sz == 0 {
i++
continue
}
c := e.Class()
if c == bidi.R || c == bidi.AL || c == bidi.AN {
return bidi.RightToLeft
}
i += sz
}
return bidi.LeftToRight
} | DirectionString reports the direction of the given label as defined by RFC
5893. The Bidi Rule does not have to be applied to labels of the category
LeftToRight. | DirectionString | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func Valid(b []byte) bool {
var t Transformer
if n, ok := t.advance(b); !ok || n < len(b) {
return false
}
return t.isFinal()
} | Valid reports whether b conforms to the BiDi rule. | Valid | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func ValidString(s string) bool {
var t Transformer
if n, ok := t.advanceString(s); !ok || n < len(s) {
return false
}
return t.isFinal()
} | ValidString reports whether s conforms to the BiDi rule. | ValidString | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func New() *Transformer {
return &Transformer{}
} | New returns a Transformer that verifies that input adheres to the Bidi Rule. | New | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func (t *Transformer) isRTL() bool {
const isRTL = 1<<bidi.R | 1<<bidi.AL | 1<<bidi.AN
return t.seen&isRTL != 0
} | A rule can only be violated for "Bidi Domain names", meaning if one of the
following categories has been observed. | isRTL | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func (t *Transformer) Reset() { *t = Transformer{} } | Reset implements transform.Transformer. | Reset | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func (t *Transformer) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
if len(dst) < len(src) {
src = src[:len(dst)]
atEOF = false
err = transform.ErrShortDst
}
n, err1 := t.Span(src, atEOF)
copy(dst, src[:n])
if err == nil || err1 != nil && err1 != transform.ErrShortSrc {
err = err1
}
return n, n, err
} | Transform implements transform.Transformer. This Transformer has state and
needs to be reset between uses. | Transform | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func (t *Transformer) Span(src []byte, atEOF bool) (n int, err error) {
if t.state == ruleInvalid && t.isRTL() {
return 0, ErrInvalid
}
n, ok := t.advance(src)
switch {
case !ok:
err = ErrInvalid
case n < len(src):
if !atEOF {
err = transform.ErrShortSrc
break
}
err = ErrInvalid
case !t.isFinal():
err = ErrInvalid
}
return n, err
} | Span returns the first n bytes of src that conform to the Bidi rule. | Span | go | flynn/flynn | vendor/golang.org/x/text/secure/bidirule/bidirule.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/secure/bidirule/bidirule.go | BSD-3-Clause |
func (c Class) in(set ...Class) bool {
for _, s := range set {
if c == s {
return true
}
}
return false
} | in returns if x is equal to any of the values in set. | in | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func newParagraph(types []Class, pairTypes []bracketType, pairValues []rune, levels level) *paragraph {
validateTypes(types)
validatePbTypes(pairTypes)
validatePbValues(pairValues, pairTypes)
validateParagraphEmbeddingLevel(levels)
p := ¶graph{
initialTypes: append([]Class(nil), types...),
embeddingLevel: levels,
pairTypes: pairTypes,
pairValues: pairValues,
resultTypes: append([]Class(nil), types...),
}
p.run()
return p
} | newParagraph initializes a paragraph. The user needs to supply a few arrays
corresponding to the preprocessed text input. The types correspond to the
Unicode BiDi classes for each rune. pairTypes indicates the bracket type for
each rune. pairValues provides a unique bracket class identifier for each
rune (suggested is the rune of the open bracket for opening and matching
close brackets, after normalization). The embedding levels are optional, but
may be supplied to encode embedding levels of styled text.
TODO: return an error. | newParagraph | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) run() {
p.determineMatchingIsolates()
// 1) determining the paragraph level
// Rule P1 is the requirement for entering this algorithm.
// Rules P2, P3.
// If no externally supplied paragraph embedding level, use default.
if p.embeddingLevel == implicitLevel {
p.embeddingLevel = p.determineParagraphEmbeddingLevel(0, p.Len())
}
// Initialize result levels to paragraph embedding level.
p.resultLevels = make([]level, p.Len())
setLevels(p.resultLevels, p.embeddingLevel)
// 2) Explicit levels and directions
// Rules X1-X8.
p.determineExplicitEmbeddingLevels()
// Rule X9.
// We do not remove the embeddings, the overrides, the PDFs, and the BNs
// from the string explicitly. But they are not copied into isolating run
// sequences when they are created, so they are removed for all
// practical purposes.
// Rule X10.
// Run remainder of algorithm one isolating run sequence at a time
for _, seq := range p.determineIsolatingRunSequences() {
// 3) resolving weak types
// Rules W1-W7.
seq.resolveWeakTypes()
// 4a) resolving paired brackets
// Rule N0
resolvePairedBrackets(seq)
// 4b) resolving neutral types
// Rules N1-N3.
seq.resolveNeutralTypes()
// 5) resolving implicit embedding levels
// Rules I1, I2.
seq.resolveImplicitLevels()
// Apply the computed levels and types
seq.applyLevelsAndTypes()
}
// Assign appropriate levels to 'hide' LREs, RLEs, LROs, RLOs, PDFs, and
// BNs. This is for convenience, so the resulting level array will have
// a value for every character.
p.assignLevelsToCharactersRemovedByX9()
} | The algorithm. Does not include line-based processing (Rules L1, L2).
These are applied later in the line-based phase of the algorithm. | run | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) determineMatchingIsolates() {
p.matchingPDI = make([]int, p.Len())
p.matchingIsolateInitiator = make([]int, p.Len())
for i := range p.matchingIsolateInitiator {
p.matchingIsolateInitiator[i] = -1
}
for i := range p.matchingPDI {
p.matchingPDI[i] = -1
if t := p.resultTypes[i]; t.in(LRI, RLI, FSI) {
depthCounter := 1
for j := i + 1; j < p.Len(); j++ {
if u := p.resultTypes[j]; u.in(LRI, RLI, FSI) {
depthCounter++
} else if u == PDI {
if depthCounter--; depthCounter == 0 {
p.matchingPDI[i] = j
p.matchingIsolateInitiator[j] = i
break
}
}
}
if p.matchingPDI[i] == -1 {
p.matchingPDI[i] = p.Len()
}
}
}
} | determineMatchingIsolates determines the matching PDI for each isolate
initiator and vice versa.
Definition BD9.
At the end of this function:
- The member variable matchingPDI is set to point to the index of the
matching PDI character for each isolate initiator character. If there is
no matching PDI, it is set to the length of the input text. For other
characters, it is set to -1.
- The member variable matchingIsolateInitiator is set to point to the
index of the matching isolate initiator character for each PDI character.
If there is no matching isolate initiator, or the character is not a PDI,
it is set to -1. | determineMatchingIsolates | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) determineParagraphEmbeddingLevel(start, end int) level {
var strongType Class = unknownClass
// Rule P2.
for i := start; i < end; i++ {
if t := p.resultTypes[i]; t.in(L, AL, R) {
strongType = t
break
} else if t.in(FSI, LRI, RLI) {
i = p.matchingPDI[i] // skip over to the matching PDI
if i > end {
log.Panic("assert (i <= end)")
}
}
}
// Rule P3.
switch strongType {
case unknownClass: // none found
// default embedding level when no strong types found is 0.
return 0
case L:
return 0
default: // AL, R
return 1
}
} | determineParagraphEmbeddingLevel reports the resolved paragraph direction of
the substring limited by the given range [start, end).
Determines the paragraph level based on rules P2, P3. This is also used
in rule X5c to find if an FSI should resolve to LRI or RLI. | determineParagraphEmbeddingLevel | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) determineExplicitEmbeddingLevels() {
var stack directionalStatusStack
var overflowIsolateCount, overflowEmbeddingCount, validIsolateCount int
// Rule X1.
stack.push(p.embeddingLevel, ON, false)
for i, t := range p.resultTypes {
// Rules X2, X3, X4, X5, X5a, X5b, X5c
switch t {
case RLE, LRE, RLO, LRO, RLI, LRI, FSI:
isIsolate := t.in(RLI, LRI, FSI)
isRTL := t.in(RLE, RLO, RLI)
// override if this is an FSI that resolves to RLI
if t == FSI {
isRTL = (p.determineParagraphEmbeddingLevel(i+1, p.matchingPDI[i]) == 1)
}
if isIsolate {
p.resultLevels[i] = stack.lastEmbeddingLevel()
if stack.lastDirectionalOverrideStatus() != ON {
p.resultTypes[i] = stack.lastDirectionalOverrideStatus()
}
}
var newLevel level
if isRTL {
// least greater odd
newLevel = (stack.lastEmbeddingLevel() + 1) | 1
} else {
// least greater even
newLevel = (stack.lastEmbeddingLevel() + 2) &^ 1
}
if newLevel <= maxDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0 {
if isIsolate {
validIsolateCount++
}
// Push new embedding level, override status, and isolated
// status.
// No check for valid stack counter, since the level check
// suffices.
switch t {
case LRO:
stack.push(newLevel, L, isIsolate)
case RLO:
stack.push(newLevel, R, isIsolate)
default:
stack.push(newLevel, ON, isIsolate)
}
// Not really part of the spec
if !isIsolate {
p.resultLevels[i] = newLevel
}
} else {
// This is an invalid explicit formatting character,
// so apply the "Otherwise" part of rules X2-X5b.
if isIsolate {
overflowIsolateCount++
} else { // !isIsolate
if overflowIsolateCount == 0 {
overflowEmbeddingCount++
}
}
}
// Rule X6a
case PDI:
if overflowIsolateCount > 0 {
overflowIsolateCount--
} else if validIsolateCount == 0 {
// do nothing
} else {
overflowEmbeddingCount = 0
for !stack.lastDirectionalIsolateStatus() {
stack.pop()
}
stack.pop()
validIsolateCount--
}
p.resultLevels[i] = stack.lastEmbeddingLevel()
// Rule X7
case PDF:
// Not really part of the spec
p.resultLevels[i] = stack.lastEmbeddingLevel()
if overflowIsolateCount > 0 {
// do nothing
} else if overflowEmbeddingCount > 0 {
overflowEmbeddingCount--
} else if !stack.lastDirectionalIsolateStatus() && stack.depth() >= 2 {
stack.pop()
}
case B: // paragraph separator.
// Rule X8.
// These values are reset for clarity, in this implementation B
// can only occur as the last code in the array.
stack.empty()
overflowIsolateCount = 0
overflowEmbeddingCount = 0
validIsolateCount = 0
p.resultLevels[i] = p.embeddingLevel
default:
p.resultLevels[i] = stack.lastEmbeddingLevel()
if stack.lastDirectionalOverrideStatus() != ON {
p.resultTypes[i] = stack.lastDirectionalOverrideStatus()
}
}
}
} | Determine explicit levels using rules X1 - X8 | determineExplicitEmbeddingLevels | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) isolatingRunSequence(indexes []int) *isolatingRunSequence {
length := len(indexes)
types := make([]Class, length)
for i, x := range indexes {
types[i] = p.resultTypes[x]
}
// assign level, sos and eos
prevChar := indexes[0] - 1
for prevChar >= 0 && isRemovedByX9(p.initialTypes[prevChar]) {
prevChar--
}
prevLevel := p.embeddingLevel
if prevChar >= 0 {
prevLevel = p.resultLevels[prevChar]
}
var succLevel level
lastType := types[length-1]
if lastType.in(LRI, RLI, FSI) {
succLevel = p.embeddingLevel
} else {
// the first character after the end of run sequence
limit := indexes[length-1] + 1
for ; limit < p.Len() && isRemovedByX9(p.initialTypes[limit]); limit++ {
}
succLevel = p.embeddingLevel
if limit < p.Len() {
succLevel = p.resultLevels[limit]
}
}
level := p.resultLevels[indexes[0]]
return &isolatingRunSequence{
p: p,
indexes: indexes,
types: types,
level: level,
sos: typeForLevel(maxLevel(prevLevel, level)),
eos: typeForLevel(maxLevel(succLevel, level)),
}
} | Rule X10, second bullet: Determine the start-of-sequence (sos) and end-of-sequence (eos) types,
either L or R, for each isolating run sequence. | isolatingRunSequence | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (s *isolatingRunSequence) resolveWeakTypes() {
// on entry, only these types remain
s.assertOnly(L, R, AL, EN, ES, ET, AN, CS, B, S, WS, ON, NSM, LRI, RLI, FSI, PDI)
// Rule W1.
// Changes all NSMs.
preceedingCharacterType := s.sos
for i, t := range s.types {
if t == NSM {
s.types[i] = preceedingCharacterType
} else {
if t.in(LRI, RLI, FSI, PDI) {
preceedingCharacterType = ON
}
preceedingCharacterType = t
}
}
// Rule W2.
// EN does not change at the start of the run, because sos != AL.
for i, t := range s.types {
if t == EN {
for j := i - 1; j >= 0; j-- {
if t := s.types[j]; t.in(L, R, AL) {
if t == AL {
s.types[i] = AN
}
break
}
}
}
}
// Rule W3.
for i, t := range s.types {
if t == AL {
s.types[i] = R
}
}
// Rule W4.
// Since there must be values on both sides for this rule to have an
// effect, the scan skips the first and last value.
//
// Although the scan proceeds left to right, and changes the type
// values in a way that would appear to affect the computations
// later in the scan, there is actually no problem. A change in the
// current value can only affect the value to its immediate right,
// and only affect it if it is ES or CS. But the current value can
// only change if the value to its right is not ES or CS. Thus
// either the current value will not change, or its change will have
// no effect on the remainder of the analysis.
for i := 1; i < s.Len()-1; i++ {
t := s.types[i]
if t == ES || t == CS {
prevSepType := s.types[i-1]
succSepType := s.types[i+1]
if prevSepType == EN && succSepType == EN {
s.types[i] = EN
} else if s.types[i] == CS && prevSepType == AN && succSepType == AN {
s.types[i] = AN
}
}
}
// Rule W5.
for i, t := range s.types {
if t == ET {
// locate end of sequence
runStart := i
runEnd := s.findRunLimit(runStart, ET)
// check values at ends of sequence
t := s.sos
if runStart > 0 {
t = s.types[runStart-1]
}
if t != EN {
t = s.eos
if runEnd < len(s.types) {
t = s.types[runEnd]
}
}
if t == EN {
setTypes(s.types[runStart:runEnd], EN)
}
// continue at end of sequence
i = runEnd
}
}
// Rule W6.
for i, t := range s.types {
if t.in(ES, ET, CS) {
s.types[i] = ON
}
}
// Rule W7.
for i, t := range s.types {
if t == EN {
// set default if we reach start of run
prevStrongType := s.sos
for j := i - 1; j >= 0; j-- {
t = s.types[j]
if t == L || t == R { // AL's have been changed to R
prevStrongType = t
break
}
}
if prevStrongType == L {
s.types[i] = L
}
}
}
} | Resolving weak types Rules W1-W7.
Note that some weak types (EN, AN) remain after this processing is
complete. | resolveWeakTypes | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (s *isolatingRunSequence) resolveNeutralTypes() {
// on entry, only these types can be in resultTypes
s.assertOnly(L, R, EN, AN, B, S, WS, ON, RLI, LRI, FSI, PDI)
for i, t := range s.types {
switch t {
case WS, ON, B, S, RLI, LRI, FSI, PDI:
// find bounds of run of neutrals
runStart := i
runEnd := s.findRunLimit(runStart, B, S, WS, ON, RLI, LRI, FSI, PDI)
// determine effective types at ends of run
var leadType, trailType Class
// Note that the character found can only be L, R, AN, or
// EN.
if runStart == 0 {
leadType = s.sos
} else {
leadType = s.types[runStart-1]
if leadType.in(AN, EN) {
leadType = R
}
}
if runEnd == len(s.types) {
trailType = s.eos
} else {
trailType = s.types[runEnd]
if trailType.in(AN, EN) {
trailType = R
}
}
var resolvedType Class
if leadType == trailType {
// Rule N1.
resolvedType = leadType
} else {
// Rule N2.
// Notice the embedding level of the run is used, not
// the paragraph embedding level.
resolvedType = typeForLevel(s.level)
}
setTypes(s.types[runStart:runEnd], resolvedType)
// skip over run of (former) neutrals
i = runEnd
}
}
} | 6) resolving neutral types Rules N1-N2. | resolveNeutralTypes | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (s *isolatingRunSequence) resolveImplicitLevels() {
// on entry, only these types can be in resultTypes
s.assertOnly(L, R, EN, AN)
s.resolvedLevels = make([]level, len(s.types))
setLevels(s.resolvedLevels, s.level)
if (s.level & 1) == 0 { // even level
for i, t := range s.types {
// Rule I1.
if t == L {
// no change
} else if t == R {
s.resolvedLevels[i] += 1
} else { // t == AN || t == EN
s.resolvedLevels[i] += 2
}
}
} else { // odd level
for i, t := range s.types {
// Rule I2.
if t == R {
// no change
} else { // t == L || t == AN || t == EN
s.resolvedLevels[i] += 1
}
}
}
} | 7) resolving implicit embedding levels Rules I1, I2. | resolveImplicitLevels | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (s *isolatingRunSequence) applyLevelsAndTypes() {
for i, x := range s.indexes {
s.p.resultTypes[x] = s.types[i]
s.p.resultLevels[x] = s.resolvedLevels[i]
}
} | Applies the levels and types resolved in rules W1-I2 to the
resultLevels array. | applyLevelsAndTypes | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (s *isolatingRunSequence) findRunLimit(index int, validSet ...Class) int {
loop:
for ; index < len(s.types); index++ {
t := s.types[index]
for _, valid := range validSet {
if t == valid {
continue loop
}
}
return index // didn't find a match in validSet
}
return len(s.types)
} | Return the limit of the run consisting only of the types in validSet
starting at index. This checks the value at index, and will return
index if that value is not in validSet. | findRunLimit | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (s *isolatingRunSequence) assertOnly(codes ...Class) {
loop:
for i, t := range s.types {
for _, c := range codes {
if t == c {
continue loop
}
}
log.Panicf("invalid bidi code %v present in assertOnly at position %d", t, s.indexes[i])
}
} | Algorithm validation. Assert that all values in types are in the
provided set. | assertOnly | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) determineLevelRuns() [][]int {
run := []int{}
allRuns := [][]int{}
currentLevel := implicitLevel
for i := range p.initialTypes {
if !isRemovedByX9(p.initialTypes[i]) {
if p.resultLevels[i] != currentLevel {
// we just encountered a new run; wrap up last run
if currentLevel >= 0 { // only wrap it up if there was a run
allRuns = append(allRuns, run)
run = nil
}
// Start new run
currentLevel = p.resultLevels[i]
}
run = append(run, i)
}
}
// Wrap up the final run, if any
if len(run) > 0 {
allRuns = append(allRuns, run)
}
return allRuns
} | determineLevelRuns returns an array of level runs. Each level run is
described as an array of indexes into the input string.
Determines the level runs. Rule X9 will be applied in determining the
runs, in the way that makes sure the characters that are supposed to be
removed are not included in the runs. | determineLevelRuns | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) determineIsolatingRunSequences() []*isolatingRunSequence {
levelRuns := p.determineLevelRuns()
// Compute the run that each character belongs to
runForCharacter := make([]int, p.Len())
for i, run := range levelRuns {
for _, index := range run {
runForCharacter[index] = i
}
}
sequences := []*isolatingRunSequence{}
var currentRunSequence []int
for _, run := range levelRuns {
first := run[0]
if p.initialTypes[first] != PDI || p.matchingIsolateInitiator[first] == -1 {
currentRunSequence = nil
// int run = i;
for {
// Copy this level run into currentRunSequence
currentRunSequence = append(currentRunSequence, run...)
last := currentRunSequence[len(currentRunSequence)-1]
lastT := p.initialTypes[last]
if lastT.in(LRI, RLI, FSI) && p.matchingPDI[last] != p.Len() {
run = levelRuns[runForCharacter[p.matchingPDI[last]]]
} else {
break
}
}
sequences = append(sequences, p.isolatingRunSequence(currentRunSequence))
}
}
return sequences
} | Definition BD13. Determine isolating run sequences. | determineIsolatingRunSequences | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) assignLevelsToCharactersRemovedByX9() {
for i, t := range p.initialTypes {
if t.in(LRE, RLE, LRO, RLO, PDF, BN) {
p.resultTypes[i] = t
p.resultLevels[i] = -1
}
}
// now propagate forward the levels information (could have
// propagated backward, the main thing is not to introduce a level
// break where one doesn't already exist).
if p.resultLevels[0] == -1 {
p.resultLevels[0] = p.embeddingLevel
}
for i := 1; i < len(p.initialTypes); i++ {
if p.resultLevels[i] == -1 {
p.resultLevels[i] = p.resultLevels[i-1]
}
}
// Embedding information is for informational purposes only so need not be
// adjusted.
} | Assign level information to characters removed by rule X9. This is for
ease of relating the level information to the original input data. Note
that the levels assigned to these codes are arbitrary, they're chosen so
as to avoid breaking level runs. | assignLevelsToCharactersRemovedByX9 | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) getLevels(linebreaks []int) []level {
// Note that since the previous processing has removed all
// P, S, and WS values from resultTypes, the values referred to
// in these rules are the initial types, before any processing
// has been applied (including processing of overrides).
//
// This example implementation has reinserted explicit format codes
// and BN, in order that the levels array correspond to the
// initial text. Their final placement is not normative.
// These codes are treated like WS in this implementation,
// so they don't interrupt sequences of WS.
validateLineBreaks(linebreaks, p.Len())
result := append([]level(nil), p.resultLevels...)
// don't worry about linebreaks since if there is a break within
// a series of WS values preceding S, the linebreak itself
// causes the reset.
for i, t := range p.initialTypes {
if t.in(B, S) {
// Rule L1, clauses one and two.
result[i] = p.embeddingLevel
// Rule L1, clause three.
for j := i - 1; j >= 0; j-- {
if isWhitespace(p.initialTypes[j]) { // including format codes
result[j] = p.embeddingLevel
} else {
break
}
}
}
}
// Rule L1, clause four.
start := 0
for _, limit := range linebreaks {
for j := limit - 1; j >= start; j-- {
if isWhitespace(p.initialTypes[j]) { // including format codes
result[j] = p.embeddingLevel
} else {
break
}
}
start = limit
}
return result
} | getLevels computes levels array breaking lines at offsets in linebreaks.
Rule L1.
The linebreaks array must include at least one value. The values must be
in strictly increasing order (no duplicates) between 1 and the length of
the text, inclusive. The last value must be the length of the text. | getLevels | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func (p *paragraph) getReordering(linebreaks []int) []int {
validateLineBreaks(linebreaks, p.Len())
return computeMultilineReordering(p.getLevels(linebreaks), linebreaks)
} | getReordering returns the reordering of lines from a visual index to a
logical index for line breaks at the given offsets.
Lines are concatenated from left to right. So for example, the fifth
character from the left on the third line is
getReordering(linebreaks)[linebreaks[1] + 4]
(linebreaks[1] is the position after the last character of the second
line, which is also the index of the first character on the third line,
and adding four gets the fifth character from the left).
The linebreaks array must include at least one value. The values must be
in strictly increasing order (no duplicates) between 1 and the length of
the text, inclusive. The last value must be the length of the text. | getReordering | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func computeMultilineReordering(levels []level, linebreaks []int) []int {
result := make([]int, len(levels))
start := 0
for _, limit := range linebreaks {
tempLevels := make([]level, limit-start)
copy(tempLevels, levels[start:])
for j, order := range computeReordering(tempLevels) {
result[start+j] = order + start
}
start = limit
}
return result
} | Return multiline reordering array for a given level array. Reordering
does not occur across a line break. | computeMultilineReordering | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func computeReordering(levels []level) []int {
result := make([]int, len(levels))
// initialize order
for i := range result {
result[i] = i
}
// locate highest level found on line.
// Note the rules say text, but no reordering across line bounds is
// performed, so this is sufficient.
highestLevel := level(0)
lowestOddLevel := level(maxDepth + 2)
for _, level := range levels {
if level > highestLevel {
highestLevel = level
}
if level&1 != 0 && level < lowestOddLevel {
lowestOddLevel = level
}
}
for level := highestLevel; level >= lowestOddLevel; level-- {
for i := 0; i < len(levels); i++ {
if levels[i] >= level {
// find range of text at or above this level
start := i
limit := i + 1
for limit < len(levels) && levels[limit] >= level {
limit++
}
for j, k := start, limit-1; j < k; j, k = j+1, k-1 {
result[j], result[k] = result[k], result[j]
}
// skip to end of level run
i = limit
}
}
}
return result
} | Return reordering array for a given level array. This reorders a single
line. The reordering is a visual to logical map. For example, the
leftmost char is string.charAt(order[0]). Rule L2. | computeReordering | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func isWhitespace(c Class) bool {
switch c {
case LRE, RLE, LRO, RLO, PDF, LRI, RLI, FSI, PDI, BN, WS:
return true
}
return false
} | isWhitespace reports whether the type is considered a whitespace type for the
line break rules. | isWhitespace | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func isRemovedByX9(c Class) bool {
switch c {
case LRE, RLE, LRO, RLO, PDF, BN:
return true
}
return false
} | isRemovedByX9 reports whether the type is one of the types removed in X9. | isRemovedByX9 | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func typeForLevel(level level) Class {
if (level & 0x1) == 0 {
return L
}
return R
} | typeForLevel reports the strong type (L or R) corresponding to the level. | typeForLevel | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/core.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/core.go | BSD-3-Clause |
func resolvePairedBrackets(s *isolatingRunSequence) {
p := bracketPairer{
sos: s.sos,
openers: list.New(),
codesIsolatedRun: s.types,
indexes: s.indexes,
}
dirEmbed := L
if s.level&1 != 0 {
dirEmbed = R
}
p.locateBrackets(s.p.pairTypes, s.p.pairValues)
p.resolveBrackets(dirEmbed, s.p.initialTypes)
} | resolvePairedBrackets runs the paired bracket part of the UBA algorithm.
For each rune, it takes the indexes into the original string, the class the
bracket type (in pairTypes) and the bracket identifier (pairValues). It also
takes the direction type for the start-of-sentence and the embedding level.
The identifiers for bracket types are the rune of the canonicalized opening
bracket for brackets (open or close) or 0 for runes that are not brackets. | resolvePairedBrackets | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func (p *bracketPairer) matchOpener(pairValues []rune, opener, closer int) bool {
return pairValues[p.indexes[opener]] == pairValues[p.indexes[closer]]
} | matchOpener reports whether characters at given positions form a matching
bracket pair. | matchOpener | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func (p *bracketPairer) locateBrackets(pairTypes []bracketType, pairValues []rune) {
// traverse the run
// do that explicitly (not in a for-each) so we can record position
for i, index := range p.indexes {
// look at the bracket type for each character
if pairTypes[index] == bpNone || p.codesIsolatedRun[i] != ON {
// continue scanning
continue
}
switch pairTypes[index] {
case bpOpen:
// check if maximum pairing depth reached
if p.openers.Len() == maxPairingDepth {
p.openers.Init()
return
}
// remember opener location, most recent first
p.openers.PushFront(i)
case bpClose:
// see if there is a match
count := 0
for elem := p.openers.Front(); elem != nil; elem = elem.Next() {
count++
opener := elem.Value.(int)
if p.matchOpener(pairValues, opener, i) {
// if the opener matches, add nested pair to the ordered list
p.pairPositions = append(p.pairPositions, bracketPair{opener, i})
// remove up to and including matched opener
for ; count > 0; count-- {
p.openers.Remove(p.openers.Front())
}
break
}
}
sort.Sort(p.pairPositions)
// if we get here, the closing bracket matched no openers
// and gets ignored
}
}
} | locateBrackets locates matching bracket pairs according to BD16.
This implementation uses a linked list instead of a stack, because, while
elements are added at the front (like a push) they are not generally removed
in atomic 'pop' operations, reducing the benefit of the stack archetype. | locateBrackets | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func (p *bracketPairer) getStrongTypeN0(index int) Class {
switch p.codesIsolatedRun[index] {
// in the scope of N0, number types are treated as R
case EN, AN, AL, R:
return R
case L:
return L
default:
return ON
}
} | getStrongTypeN0 maps character's directional code to strong type as required
by rule N0.
TODO: have separate type for "strong" directionality. | getStrongTypeN0 | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func (p *bracketPairer) classifyPairContent(loc bracketPair, dirEmbed Class) Class {
dirOpposite := ON
for i := loc.opener + 1; i < loc.closer; i++ {
dir := p.getStrongTypeN0(i)
if dir == ON {
continue
}
if dir == dirEmbed {
return dir // type matching embedding direction found
}
dirOpposite = dir
}
// return ON if no strong type found, or class opposite to dirEmbed
return dirOpposite
} | classifyPairContent reports the strong types contained inside a Bracket Pair,
assuming the given embedding direction.
It returns ON if no strong type is found. If a single strong type is found,
it returns this type. Otherwise it returns the embedding direction.
TODO: use separate type for "strong" directionality. | classifyPairContent | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func (p *bracketPairer) classBeforePair(loc bracketPair) Class {
for i := loc.opener - 1; i >= 0; i-- {
if dir := p.getStrongTypeN0(i); dir != ON {
return dir
}
}
// no strong types found, return sos
return p.sos
} | classBeforePair determines which strong types are present before a Bracket
Pair. Return R or L if strong type found, otherwise ON. | classBeforePair | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func (p *bracketPairer) assignBracketType(loc bracketPair, dirEmbed Class, initialTypes []Class) {
// rule "N0, a", inspect contents of pair
dirPair := p.classifyPairContent(loc, dirEmbed)
// dirPair is now L, R, or N (no strong type found)
// the following logical tests are performed out of order compared to
// the statement of the rules but yield the same results
if dirPair == ON {
return // case "d" - nothing to do
}
if dirPair != dirEmbed {
// case "c": strong type found, opposite - check before (c.1)
dirPair = p.classBeforePair(loc)
if dirPair == dirEmbed || dirPair == ON {
// no strong opposite type found before - use embedding (c.2)
dirPair = dirEmbed
}
}
// else: case "b", strong type found matching embedding,
// no explicit action needed, as dirPair is already set to embedding
// direction
// set the bracket types to the type found
p.setBracketsToType(loc, dirPair, initialTypes)
} | assignBracketType implements rule N0 for a single bracket pair. | assignBracketType | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func (p *bracketPairer) resolveBrackets(dirEmbed Class, initialTypes []Class) {
for _, loc := range p.pairPositions {
p.assignBracketType(loc, dirEmbed, initialTypes)
}
} | resolveBrackets implements rule N0 for a list of pairs. | resolveBrackets | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bracket.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bracket.go | BSD-3-Clause |
func DefaultDirection(d Direction) Option {
panic("unimplemented")
} | DefaultDirection sets the default direction for a Paragraph. The direction is
overridden if the text contains directional characters. | DefaultDirection | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (p *Paragraph) SetBytes(b []byte, opts ...Option) (n int, err error) {
panic("unimplemented")
} | SetBytes configures p for the given paragraph text. It replaces text
previously set by SetBytes or SetString. If b contains a paragraph separator
it will only process the first paragraph and report the number of bytes
consumed from b including this separator. Error may be non-nil if options are
given. | SetBytes | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (p *Paragraph) SetString(s string, opts ...Option) (n int, err error) {
panic("unimplemented")
} | SetString configures p for the given paragraph text. It replaces text
previously set by SetBytes or SetString. If b contains a paragraph separator
it will only process the first paragraph and report the number of bytes
consumed from b including this separator. Error may be non-nil if options are
given. | SetString | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (p *Paragraph) IsLeftToRight() bool {
panic("unimplemented")
} | IsLeftToRight reports whether the principle direction of rendering for this
paragraphs is left-to-right. If this returns false, the principle direction
of rendering is right-to-left. | IsLeftToRight | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (p *Paragraph) Direction() Direction {
panic("unimplemented")
} | Direction returns the direction of the text of this paragraph.
The direction may be LeftToRight, RightToLeft, Mixed, or Neutral. | Direction | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (p *Paragraph) RunAt(pos int) Run {
panic("unimplemented")
} | RunAt reports the Run at the given position of the input text.
This method can be used for computing line breaks on paragraphs. | RunAt | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (p *Paragraph) Order() (Ordering, error) {
panic("unimplemented")
} | Order computes the visual ordering of all the runs in a Paragraph. | Order | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (p *Paragraph) Line(start, end int) (Ordering, error) {
panic("unimplemented")
} | Line computes the visual ordering of runs for a single line starting and
ending at the given positions in the original text. | Line | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (o *Ordering) Direction() Direction {
panic("unimplemented")
} | Direction reports the directionality of the runs.
The direction may be LeftToRight, RightToLeft, Mixed, or Neutral. | Direction | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (o *Ordering) NumRuns() int {
panic("unimplemented")
} | NumRuns returns the number of runs. | NumRuns | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (o *Ordering) Run(i int) Run {
panic("unimplemented")
} | Run returns the ith run within the ordering. | Run | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
func (r *Run) String() string {
panic("unimplemented")
} | String returns the text of the run in its original order. | String | go | flynn/flynn | vendor/golang.org/x/text/unicode/bidi/bidi.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/text/unicode/bidi/bidi.go | BSD-3-Clause |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.