// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build unix

// Socket control messages

package syscall

import (
	
)

// CmsgLen returns the value to store in the Len field of the Cmsghdr
// structure, taking into account any necessary alignment.
func ( int) int {
	return cmsgAlignOf(SizeofCmsghdr) + 
}

// CmsgSpace returns the number of bytes an ancillary element with
// payload of the passed data length occupies.
func ( int) int {
	return cmsgAlignOf(SizeofCmsghdr) + cmsgAlignOf()
}

func ( *Cmsghdr) ( uintptr) unsafe.Pointer {
	return unsafe.Pointer(uintptr(unsafe.Pointer()) + uintptr(cmsgAlignOf(SizeofCmsghdr)) + )
}

// SocketControlMessage represents a socket control message.
type SocketControlMessage struct {
	Header Cmsghdr
	Data   []byte
}

// ParseSocketControlMessage parses b as an array of socket control
// messages.
func ( []byte) ([]SocketControlMessage, error) {
	var  []SocketControlMessage
	 := 0
	for +CmsgLen(0) <= len() {
		, ,  := socketControlMessageHeaderAndData([:])
		if  != nil {
			return nil, 
		}
		 := SocketControlMessage{Header: *, Data: }
		 = append(, )
		 += cmsgAlignOf(int(.Len))
	}
	return , nil
}

func ( []byte) (*Cmsghdr, []byte, error) {
	 := (*Cmsghdr)(unsafe.Pointer(&[0]))
	if .Len < SizeofCmsghdr || uint64(.Len) > uint64(len()) {
		return nil, nil, EINVAL
	}
	return , [cmsgAlignOf(SizeofCmsghdr):.Len], nil
}

// UnixRights encodes a set of open file descriptors into a socket
// control message for sending to another process.
func ( ...int) []byte {
	 := len() * 4
	 := make([]byte, CmsgSpace())
	 := (*Cmsghdr)(unsafe.Pointer(&[0]))
	.Level = SOL_SOCKET
	.Type = SCM_RIGHTS
	.SetLen(CmsgLen())
	for ,  := range  {
		*(*int32)(.data(4 * uintptr())) = int32()
	}
	return 
}

// ParseUnixRights decodes a socket control message that contains an
// integer array of open file descriptors from another process.
func ( *SocketControlMessage) ([]int, error) {
	if .Header.Level != SOL_SOCKET {
		return nil, EINVAL
	}
	if .Header.Type != SCM_RIGHTS {
		return nil, EINVAL
	}
	 := make([]int, len(.Data)>>2)
	for ,  := 0, 0;  < len(.Data);  += 4 {
		[] = int(*(*int32)(unsafe.Pointer(&.Data[])))
		++
	}
	return , nil
}