aboutsummaryrefslogtreecommitdiff
path: root/spdu/spdu.go
blob: 688d5b4017d8e6648fd4b172feafe55f37f5d14e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// SPDU (Session Protocol Data Unit)
package spdu

import (
	"encoding/binary"
	"errors"
	"io"
	"net"
)

// |<-- 2 octets -->|<-- maximum 240 octets -->|
// | header         | acse/rose pdu            |
// | big endian     |                          |

const maxLen = 240 // max PDU size

type Conn struct{ net.Conn }

func (c Conn) Write(p []byte) (n int, err error) {
	size := uint16(len(p))
	if size > maxLen {
		return 0, errors.New("PDU too big")
	}
	if err := binary.Write(c.Conn, binary.BigEndian, size); err != nil {
		return 0, err
	}
	return c.Conn.Write(p)
}

func (c Conn) Read(p []byte) (n int, err error) {
	var size uint16
	if err := binary.Read(c.Conn, binary.BigEndian, &size); err != nil {
		return 0, err
	}
	return c.Conn.Read(p[:size])
}

func ReadAll(r io.Reader) ([]byte, error) {
	p := make([]byte, maxLen)
	n, err := r.Read(p)
	return p[:n], err
}

func Dial(service string) (Conn, error) {
	conn, err := net.Dial("tcp", service)
	if err != nil {
		return Conn{}, err
	}
	return Conn{conn}, nil
}