-
Notifications
You must be signed in to change notification settings - Fork 25
/
buffer.go
81 lines (71 loc) · 1.62 KB
/
buffer.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package libssh
/*
#cgo pkg-config: libssh
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/types.h>
#include <libssh/libssh.h>
*/
import "C"
import (
"errors"
"unsafe"
)
type Buffer struct {
ptr *C.struct_ssh_buffer_struct
}
func NewBuffer() (Buffer, error) {
buf := Buffer{}
buf.ptr = C.ssh_buffer_new()
if buf.ptr == nil {
return buf, errors.New("ssh_buffer_new() == nil")
}
return buf, nil
}
func (b Buffer) Free() {
C.ssh_buffer_free(b.ptr)
}
func (b Buffer) AddRawData(data_ptr unsafe.Pointer, length C.uint32_t) error {
if C.ssh_buffer_add_data(b.ptr, data_ptr, length) < 0 {
return errors.New("Unable to add data to buffer")
}
return nil
}
func (b Buffer) AddData(data []byte) error {
len := len(data)
data_ptr := unsafe.Pointer(&data[0])
return b.AddRawData(data_ptr, C.uint32_t(len))
}
// Get the length of the buffer from the current position.
func (b Buffer) Len() int {
return int(C.ssh_buffer_get_len(b.ptr))
}
// Get the remaining data out of the buffer and adjust the read pointer.
func (b Buffer) Read(length int) []byte {
if length <= 0 {
return nil
}
buf := make([]C.uchar, length)
ret := int(C.ssh_buffer_get_data(b.ptr, unsafe.Pointer(&buf[0]), C.uint32_t(length)))
if ret == 0 {
return nil
}
result := make([]byte, ret)
for i := 0; i < ret; i++ {
result[i] = byte(buf[i])
}
return result
}
// read all unread data
func (b Buffer) ReadAll() []byte {
return b.Read(b.Len())
}
// Reinitialize a SSH buffer.
func (b Buffer) Reset() error {
if C.ssh_buffer_reinit(b.ptr) < 0 {
return errors.New("Fails to reinitialize buffer")
}
return nil
}