aboutsummaryrefslogtreecommitdiff
path: root/spdu/spdu.go
blob: bf4c2dafdffb4dc70a65c4c251c932aa418b10ee (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
51
52
53
54
55
// Package 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

// Conn spdu
type Conn struct{ net.Conn }

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

// Read spdu
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])
}

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

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