/*
 * fdutils.c -- useful stuff for dealing with file descriptors
 * by Filip Pizlo, 2004
 */

#include "fdutils.h"

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

jint get_flags(jint fd) {
    return fcntl(fd, F_GETFL, 0);
}

jint set_flags(jint fd, jint flags) {
    return fcntl(fd, F_SETFL, flags);
}

int set_fl(int fd,int flags) {
    int res;
    res=fcntl(fd,F_GETFL,0);
    if (res<0) return -1;
    return fcntl(fd,F_SETFL,res|flags);
}

int clr_fl(int fd,int flags) {
    int res;
    res=fcntl(fd,F_GETFL,0);
    if (res<0) return -1;
    return fcntl(fd,F_SETFL,res&(~flags));
}

jint makeNonBlocking(jint fd) {
    return set_fl(fd,O_NONBLOCK);
}

jint makeBlocking(jint fd) {
    return clr_fl(fd,O_NONBLOCK);
}

jboolean SBE(int fd,jboolean enabled) {
    int res=fcntl(fd,F_GETFL,0);
    if (res<0) {
        fprintf(stderr,"fcntl(%d,F_GETFL,0) failed in SBE(%s): %s\n",
                       fd,
                       enabled?"true":"false",
                       strerror(errno));
        abort();
    }
    
    if (enabled && (res&O_NONBLOCK)!=0) {
        /* we want to enable blocking but non-blocking flag is set.  so reset it. */
        if (fcntl(fd,F_SETFL,res&~O_NONBLOCK)<0) {
            fprintf(stderr,"fcntl(%d,F_SETFL,%x&~O_NONBLOCK) failed in SBE(%s): %s\n",
                           fd,
                           res,
                           enabled?"true":"false",
                           strerror(errno));
            abort();
        }
    }
    else
    if (!enabled && (res&O_NONBLOCK)==0) {
        /* we want to disable blocking but non-blocking flag is NOT set.  so set it. */
        if (fcntl(fd,F_SETFL,res|O_NONBLOCK)<0) {
            fprintf(stderr,"fcntl(%d,F_SETFL,%x|O_NONBLOCK) failed in SBE(%s): %s\n",
                           fd,
                           res,
                           enabled?"true":"false",
                           strerror(errno));
            abort();
        }
    }
    
    return (res&O_NONBLOCK)==0;
}

jboolean fSBE(FILE *file,jboolean enabled) {
    jboolean res;
    res=SBE(file->FILE_FD_FIELD,enabled);
    return res;
}





