package wayland

import (
	"encoding/binary"
	"errors"
)

func pad4(n int) int { return (n + 3) &^ 3 }

func encodeString(s string) []byte {
	strLen := len(s) + 1
	padded := pad4(strLen)
	buf := make([]byte, 4+padded)
	binary.LittleEndian.PutUint32(buf[:4], uint32(strLen))
	copy(buf[4:], s)
	return buf
}

// decodeString safely decodes a length-prefixed, NUL-terminated, 4-byte padded Wayland string.
// It guards against slice bounds out of range, truncated lengths, and empty strings.
func decodeString(data []byte, offset int) (string, int, error) {
	if offset+4 > len(data) {
		return "", offset, errors.New("truncated string length prefix")
	}
	strLen := int(binary.LittleEndian.Uint32(data[offset : offset+4]))
	offset += 4
	if strLen <= 0 {
		return "", offset, nil
	}
	padded := pad4(strLen)
	if offset+padded > len(data) {
		return "", offset, errors.New("truncated string payload")
	}
	var s string
	if strLen > 1 {
		// strLen includes terminating NUL
		s = string(data[offset : offset+strLen-1])
	}
	return s, offset + padded, nil
}
