split out reusable bits into separate headers
[kgio.git] / ext / kgio / sock_for_fd.h
blobdb5cba5d143a4fdd847ee02c7c94897f2cf09df5
1 #include <ruby.h>
2 #ifdef HAVE_RUBY_IO_H
3 # include <ruby/io.h>
4 #else
5 # include <stdio.h>
6 # include <rubyio.h>
7 #endif
9 #if defined(MakeOpenFile) && \
10 defined(HAVE_RB_IO_T) && (HAVE_RB_IO_T == 1) && \
11 defined(HAVE_RB_IO_ASCII8BIT_BINMODE) && \
12 defined(HAVE_ST_FD) && \
13 defined(HAVE_ST_MODE)
14 # define SOCK_FOR_FD (19)
15 # define FMODE_NOREVLOOKUP 0x100
16 #elif defined(MakeOpenFile) && \
17 (defined(OpenFile) || defined(HAVE_RB_IO_T)) && \
18 defined(HAVE_RB_FDOPEN) && \
19 defined(HAVE_ST_F) && \
20 defined(HAVE_ST_F2) && \
21 defined(HAVE_ST_MODE)
22 # define SOCK_FOR_FD (18)
23 #else
24 # define SOCK_FOR_FD (-1)
25 #endif
27 #if SOCK_FOR_FD == 19 /* modeled after ext/socket/init.c */
28 static VALUE sock_for_fd(VALUE klass, int fd)
30 VALUE sock = rb_obj_alloc(klass);
31 rb_io_t *fp;
33 MakeOpenFile(sock, fp);
34 fp->fd = fd;
35 fp->mode = FMODE_READWRITE|FMODE_DUPLEX|FMODE_NOREVLOOKUP;
36 rb_io_ascii8bit_binmode(sock);
37 rb_io_synchronized(fp);
38 return sock;
40 #elif SOCK_FOR_FD == 18 /* modeled after init_sock() in ext/socket/socket.c */
41 static VALUE sock_for_fd(VALUE klass, int fd)
43 VALUE sock = rb_obj_alloc(klass);
44 OpenFile *fp;
46 MakeOpenFile(sock, fp);
47 fp->f = rb_fdopen(fd, "r");
48 fp->f2 = rb_fdopen(fd, "w");
49 fp->mode = FMODE_READWRITE;
50 rb_io_synchronized(fp);
51 return sock;
53 #else /* Rubinius, et al. */
54 static ID id_for_fd;
55 static VALUE sock_for_fd(VALUE klass, int fd)
57 return rb_funcall(klass, id_for_fd, 1, INT2NUM(fd));
59 static void init_sock_for_fd(void)
61 id_for_fd = rb_intern("for_fd");
63 #endif /* sock_for_fd */
64 #if SOCK_FOR_FD > 0
65 # define init_sock_for_fd() if (0)
66 #endif