/*
 *  Copyright (C) 2006-2019, Thomas Maier-Komor
 *
 *  This is the source code of xjobs.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef SUPPORT_H
#define SUPPORT_H

#include <assert.h>
#include <fcntl.h>
#include <stddef.h>
#include <string.h>
#include <sys/time.h>


void *Malloc(size_t s);
int read_to_0(void);
int read_to_nl(void);
int resolve_symlink(char *cmd);
char *complete_exe(char *exe);
const char *timestr(long long usec, char *ustr, size_t n);
char *concatstr(const char *s0, const char *s1);
char *makestr(const char *f, ...);
char *replace_string(char *in, const char *param, const char *v);
char *replace_string_l(char *in, const char *param, long v);
char *resolve_env(const char *in);

#ifdef __sun
#define gettime() (gethrtime()/1000)
#else
static inline unsigned long long gettime(void)
{
	struct timeval now;
	
	(void) gettimeofday(&now,0);
	return now.tv_sec * 1000000ULL + now.tv_usec;
}
#endif


static inline void close_onexec(int f)
{
	if (f != -1) {
		int err = fcntl(f,F_SETFD,FD_CLOEXEC);
		assert(err != -1);
	}
}


static inline char *Strdup(const char *s)
{
	size_t n;
	if (s == 0) {
		char *r = Malloc(1);
		*r = 0;
		return r;
	}
	n = strlen(s) + 1;
	return memcpy(Malloc(n),s,n);
}


static inline char *Strdupn(const char *s, size_t n)
{
	assert(s != 0);
	return memcpy(Malloc(n),s,n);
}


static inline const char *timevstr(struct timeval t, char *ustr, size_t n)
{
	long long dt = t.tv_sec * 1000000 + t.tv_usec;
	return timestr(dt,ustr,n);
}


static inline int Write(int fd, const void *buf, size_t n)
{
	int r;
	do {
		r = write(fd,buf,n);
	} while ((r == -1) && (errno == EINTR));
	return r;
}

#endif
