2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2016 Jakub Klama <jceel@FreeBSD.org>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer
12 * in this position and unchanged.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
34 #include <sys/types.h>
42 seek_iov(struct iovec *iov1, size_t niov1, struct iovec *iov2, size_t *niov2,
49 for (i = 0; i < niov1; i++) {
50 size_t toseek = MIN(left, iov1[i].iov_len);
53 if (toseek == iov1[i].iov_len)
62 for (j = i; j < niov1; j++) {
63 iov2[j - i].iov_base = (char *)iov1[j].iov_base + remainder;
64 iov2[j - i].iov_len = iov1[j].iov_len - remainder;
72 count_iov(struct iovec *iov, size_t niov)
76 for (i = 0; i < niov; i++)
77 total += iov[i].iov_len;
83 truncate_iov(struct iovec *iov, size_t niov, size_t length)
87 for (i = 0; i < niov; i++) {
88 size_t toseek = MIN(length - done, iov[i].iov_len);
91 if (toseek < iov[i].iov_len) {
92 iov[i].iov_len = toseek;
101 iov_to_buf(struct iovec *iov, size_t niov, void **buf)
103 size_t i, ptr = 0, total = 0;
105 for (i = 0; i < niov; i++) {
106 total += iov[i].iov_len;
107 *buf = realloc(*buf, total);
111 memcpy(*buf + ptr, iov[i].iov_base, iov[i].iov_len);
112 ptr += iov[i].iov_len;
119 buf_to_iov(void *buf, size_t buflen, struct iovec *iov, size_t niov,
127 diov = malloc(sizeof(struct iovec) * niov);
128 seek_iov(iov, niov, diov, &ndiov, seek);
134 for (i = 0; i < ndiov; i++) {
135 memcpy(diov[i].iov_base, buf + off, diov[i].iov_len);
136 off += diov[i].iov_len;
139 return ((ssize_t)off);