#include "orconfig.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include "lib/fdio/fdio.h"
#include "lib/cc/torint.h"
#include "lib/err/torerr.h"
#include <stdlib.h>
#include <stdio.h>
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
#ifndef SEEK_CUR
#define SEEK_CUR 1
#endif
#ifndef SEEK_END
#define SEEK_END 2
#endif
off_t
tor_fd_getpos(int fd)
{
#ifdef _WIN32
return (off_t) _lseeki64(fd, 0, SEEK_CUR);
#else
return (off_t) lseek(fd, 0, SEEK_CUR);
#endif
}
int
tor_fd_seekend(int fd)
{
#ifdef _WIN32
return _lseeki64(fd, 0, SEEK_END) < 0 ? -1 : 0;
#else
off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
#ifdef ESPIPE
if (rc < 0 && errno == ESPIPE)
rc = 0;
#endif
return (rc < 0) ? -1 : 0;
#endif
}
int
tor_fd_setpos(int fd, off_t pos)
{
#ifdef _WIN32
return _lseeki64(fd, pos, SEEK_SET) < 0 ? -1 : 0;
#else
return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
#endif
}
int
tor_ftruncate(int fd)
{
if (tor_fd_setpos(fd, 0) < 0)
return -1;
#ifdef _WIN32
return _chsize(fd, 0);
#else
return ftruncate(fd, 0);
#endif
}
int
write_all_to_fd_minimal(int fd, const char *buf, size_t count)
{
size_t written = 0;
raw_assert(count < SSIZE_MAX);
while (written < count) {
ssize_t result = write(fd, buf+written, count-written);
if (result<0)
return -1;
written += result;
}
return 0;
}