package main

// Cheap reads for the hot path. A sample reads a few small files per process every minute; with
// os.ReadFile each one costs an os.File, an fstat and a fresh buffer. These helpers read into a
// buffer the caller keeps (open, read, close: three system calls, no allocation besides the path)
// and parse numbers straight from the bytes.

import (
	"os"
	"syscall"
)

// readInto reads the start of a small file (a /proc or /sys entry) into buf and returns the
// number of bytes read. A file longer than buf is cut: callers size buf for what they parse.
func readInto(path string, buf []byte) (int, error) {
	fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_CLOEXEC, 0)
	if err != nil {
		return 0, &os.PathError{Op: "open", Path: path, Err: err}
	}
	n := 0
	for n < len(buf) {
		m, err := syscall.Read(fd, buf[n:])
		if err == syscall.EINTR {
			continue
		}
		if err != nil {
			syscall.Close(fd)
			return n, &os.PathError{Op: "read", Path: path, Err: err}
		}
		if m <= 0 {
			break
		}
		n += m
	}
	syscall.Close(fd)
	return n, nil
}

// readlinkInto returns the target of a symbolic link read into buf (no allocation for the result
// beyond the string conversion the caller decides on).
func readlinkInto(path string, buf []byte) (int, error) {
	for {
		n, err := syscall.Readlink(path, buf)
		if err == syscall.EINTR {
			continue
		}
		if err != nil {
			return 0, &os.PathError{Op: "readlink", Path: path, Err: err}
		}
		return n, nil
	}
}

// parseUintBytes reads a decimal number; ok is false for an empty field or a non-digit.
func parseUintBytes(b []byte) (uint64, bool) {
	if len(b) == 0 {
		return 0, false
	}
	var n uint64
	for _, c := range b {
		if c < '0' || c > '9' {
			return 0, false
		}
		n = n*10 + uint64(c-'0')
	}
	return n, true
}

func parseIntBytes(b []byte) (int64, bool) {
	neg := len(b) > 0 && b[0] == '-'
	if neg {
		b = b[1:]
	}
	u, ok := parseUintBytes(b)
	if !ok {
		return 0, false
	}
	if neg {
		return -int64(u), true
	}
	return int64(u), true
}

// fieldsBytes splits b on spaces and tabs into at most len(dst) fields, without allocating: the
// fields are subslices of b. It returns how many fields it found.
func fieldsBytes(b []byte, dst [][]byte) int {
	n := 0
	i := 0
	for i < len(b) && n < len(dst) {
		for i < len(b) && (b[i] == ' ' || b[i] == '\t') {
			i++
		}
		if i >= len(b) {
			break
		}
		j := i
		for j < len(b) && b[j] != ' ' && b[j] != '\t' {
			j++
		}
		dst[n] = b[i:j]
		n++
		i = j
	}
	return n
}

// uitoa writes a non-negative number into a small buffer (for /proc/<pid>/... paths).
func appendPid(b []byte, pid int) []byte {
	var tmp [20]byte
	i := len(tmp)
	if pid == 0 {
		return append(b, '0')
	}
	for pid > 0 {
		i--
		tmp[i] = byte('0' + pid%10)
		pid /= 10
	}
	return append(b, tmp[i:]...)
}

// readIntoZ is readInto for a NUL-terminated path held in a byte slice (no allocation at all on
// Linux, where the kernel gets the bytes directly).
func readIntoZ(pathZ []byte, buf []byte) (int, error) {
	fd, err := openZ(pathZ)
	if err != nil {
		return 0, err
	}
	n := 0
	for n < len(buf) {
		m, err := syscall.Read(fd, buf[n:])
		if err == syscall.EINTR {
			continue
		}
		if err != nil {
			syscall.Close(fd)
			return n, err
		}
		if m <= 0 {
			break
		}
		n += m
	}
	syscall.Close(fd)
	return n, nil
}
