1 /*
2  * Copyright (c) 2008, 2012 by Farsight Security, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /* Import. */
18 
19 #include "private.h"
20 
21 /* Internal functions. */
22 
23 struct nmsg_buf *
_nmsg_buf_new(size_t sz)24 _nmsg_buf_new(size_t sz) {
25 	struct nmsg_buf *buf;
26 
27 	buf = calloc(1, sizeof(*buf));
28 	if (buf == NULL)
29 		return (NULL);
30 	buf->data = calloc(1, sz);
31 	if (buf->data == NULL) {
32 		free(buf);
33 		return (NULL);
34 	}
35 	return (buf);
36 }
37 
38 ssize_t
_nmsg_buf_used(struct nmsg_buf * buf)39 _nmsg_buf_used(struct nmsg_buf *buf) {
40 	assert(buf->pos >= buf->data);
41 	return (buf->pos - buf->data);
42 }
43 
44 ssize_t
_nmsg_buf_avail(struct nmsg_buf * buf)45 _nmsg_buf_avail(struct nmsg_buf *buf) {
46 	assert(buf->pos <= buf->end);
47 	return (buf->end - buf->pos);
48 }
49 
50 void
_nmsg_buf_destroy(struct nmsg_buf ** buf)51 _nmsg_buf_destroy(struct nmsg_buf **buf) {
52 	if (*buf != NULL) {
53 		if (_nmsg_global_autoclose == true)
54 			close((*buf)->fd);
55 		if ((*buf)->data != NULL)
56 			free((*buf)->data);
57 		free(*buf);
58 		*buf = NULL;
59 	}
60 }
61 
62 void
_nmsg_buf_reset(struct nmsg_buf * buf)63 _nmsg_buf_reset(struct nmsg_buf *buf) {
64 	buf->end = buf->pos = buf->data;
65 }
66