From 7dc80f4f9c42752a6c870cff8a908f283b37cffa Mon Sep 17 00:00:00 2001 From: "(no author)" <(no author)@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> Date: Fri, 22 Mar 2002 04:48:57 +0000 Subject: This commit was manufactured by cvs2svn to create branch 'SHIGEO'. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/SHIGEO@2245 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ext/.cvsignore | 3 - ext/Setup | 20 - ext/Setup.dj | 20 - ext/Setup.emx | 21 - ext/Setup.nt | 24 - ext/Setup.x68 | 17 - ext/Win32API/.cvsignore | 1 - ext/Win32API/MANIFEST | 7 - ext/Win32API/Win32API.c | 307 ---- ext/Win32API/depend | 1 - ext/Win32API/extconf.rb | 7 - ext/Win32API/getch.rb | 5 - ext/Win32API/point.rb | 18 - ext/aix_mksym.rb | 33 - ext/configsub.rb | 32 - ext/curses/.cvsignore | 2 - ext/curses/MANIFEST | 9 - ext/curses/curses.c | 1874 --------------------- ext/curses/depend | 1 - ext/curses/extconf.rb | 27 - ext/curses/hello.rb | 30 - ext/curses/mouse.rb | 53 - ext/curses/rain.rb | 76 - ext/curses/view.rb | 91 - ext/curses/view2.rb | 115 -- ext/dbm/.cvsignore | 2 - ext/dbm/MANIFEST | 4 - ext/dbm/dbm.c | 764 --------- ext/dbm/depend | 1 - ext/dbm/extconf.rb | 56 - ext/dbm/testdbm.rb | 590 ------- ext/digest/.cvsignore | 2 - ext/digest/MANIFEST | 39 - ext/digest/defs.h | 35 - ext/digest/depend | 2 - ext/digest/digest.c | 343 ---- ext/digest/digest.h | 32 - ext/digest/digest.txt | 113 -- ext/digest/digest.txt.ja | 111 -- ext/digest/extconf.rb | 6 - ext/digest/lib/md5.rb | 14 - ext/digest/lib/sha1.rb | 14 - ext/digest/md5/.cvsignore | 2 - ext/digest/md5/MANIFEST | 5 - ext/digest/md5/depend | 5 - ext/digest/md5/extconf.rb | 19 - ext/digest/md5/md5.c | 432 ----- ext/digest/md5/md5.h | 83 - ext/digest/md5/md5init.c | 34 - ext/digest/rmd160/.cvsignore | 2 - ext/digest/rmd160/MANIFEST | 6 - ext/digest/rmd160/depend | 7 - ext/digest/rmd160/extconf.rb | 20 - ext/digest/rmd160/rmd160.c | 464 ------ ext/digest/rmd160/rmd160.h | 68 - ext/digest/rmd160/rmd160hl.c | 96 -- ext/digest/rmd160/rmd160init.c | 34 - ext/digest/sha1/.cvsignore | 2 - ext/digest/sha1/MANIFEST | 6 - ext/digest/sha1/depend | 7 - ext/digest/sha1/extconf.rb | 20 - ext/digest/sha1/sha1.c | 283 ---- ext/digest/sha1/sha1.h | 50 - ext/digest/sha1/sha1hl.c | 102 -- ext/digest/sha1/sha1init.c | 34 - ext/digest/sha2/.cvsignore | 2 - ext/digest/sha2/MANIFEST | 6 - ext/digest/sha2/depend | 7 - ext/digest/sha2/extconf.rb | 28 - ext/digest/sha2/sha2.c | 937 ----------- ext/digest/sha2/sha2.h | 133 -- ext/digest/sha2/sha2hl.c | 252 --- ext/digest/sha2/sha2init.c | 47 - ext/digest/test.rb | 100 -- ext/digest/test.sh | 27 - ext/etc/.cvsignore | 2 - ext/etc/MANIFEST | 6 - ext/etc/depend | 1 - ext/etc/etc.c | 276 --- ext/etc/etc.txt | 72 - ext/etc/etc.txt.ja | 72 - ext/etc/extconf.rb | 22 - ext/extmk.rb.in | 780 --------- ext/fcntl/.cvsignore | 2 - ext/fcntl/MANIFEST | 3 - ext/fcntl/depend | 1 - ext/fcntl/fcntl.c | 107 -- ext/gdbm/.cvsignore | 2 - ext/gdbm/MANIFEST | 6 - ext/gdbm/README | 1 - ext/gdbm/depend | 1 - ext/gdbm/extconf.rb | 7 - ext/gdbm/gdbm.c | 994 ----------- ext/gdbm/testgdbm.rb | 663 -------- ext/iconv/MANIFEST | 4 - ext/iconv/depend | 2 - ext/iconv/extconf.rb | 8 - ext/iconv/iconv.c | 735 -------- ext/nkf/.cvsignore | 2 - ext/nkf/MANIFEST | 7 - ext/nkf/depend | 1 - ext/nkf/extconf.rb | 2 - ext/nkf/lib/kconv.rb | 73 - ext/nkf/nkf.c | 197 --- ext/nkf/nkf1.7/nkf.c | 1900 --------------------- ext/nkf/test.rb | 318 ---- ext/pty/.cvsignore | 2 - ext/pty/MANIFEST | 12 - ext/pty/README | 93 -- ext/pty/README.expect | 22 - ext/pty/README.expect.ja | 21 - ext/pty/README.ja | 89 - ext/pty/depend | 1 - ext/pty/expect_sample.rb | 56 - ext/pty/extconf.rb | 15 - ext/pty/lib/expect.rb | 36 - ext/pty/pty.c | 488 ------ ext/pty/script.rb | 38 - ext/pty/shl.rb | 92 - ext/readline/.cvsignore | 2 - ext/readline/MANIFEST | 6 - ext/readline/README | 62 - ext/readline/README.ja | 63 - ext/readline/depend | 1 - ext/readline/extconf.rb | 27 - ext/readline/readline.c | 737 --------- ext/sdbm/.cvsignore | 2 - ext/sdbm/MANIFEST | 6 - ext/sdbm/_sdbm.c | 973 ----------- ext/sdbm/depend | 2 - ext/sdbm/extconf.rb | 3 - ext/sdbm/init.c | 761 --------- ext/sdbm/sdbm.h | 84 - ext/sdbm/testsdbm.rb | 556 ------- ext/socket/.cvsignore | 2 - ext/socket/MANIFEST | 8 - ext/socket/addrinfo.h | 170 -- ext/socket/depend | 3 - ext/socket/extconf.rb | 386 ----- ext/socket/getaddrinfo.c | 686 -------- ext/socket/getnameinfo.c | 261 --- ext/socket/socket.c | 2837 ------------------------------- ext/socket/sockport.h | 76 - ext/stringio/MANIFEST | 4 - ext/stringio/README | 19 - ext/stringio/depend | 2 - ext/stringio/stringio.c | 920 ---------- ext/syslog/.cvsignore | 2 - ext/syslog/MANIFEST | 6 - ext/syslog/depend | 2 - ext/syslog/extconf.rb | 10 - ext/syslog/syslog.c | 381 ----- ext/syslog/syslog.txt | 121 -- ext/syslog/test.rb | 161 -- ext/tcltklib/.cvsignore | 1 - ext/tcltklib/MANIFEST | 16 - ext/tcltklib/MANUAL.euc | 124 -- ext/tcltklib/README.euc | 133 -- ext/tcltklib/demo/lines0.tcl | 42 - ext/tcltklib/demo/lines1.rb | 54 - ext/tcltklib/demo/lines2.rb | 50 - ext/tcltklib/depend | 2 - ext/tcltklib/extconf.rb | 72 - ext/tcltklib/lib/tcltk.rb | 367 ---- ext/tcltklib/sample/batsu.gif | Bin 538 -> 0 bytes ext/tcltklib/sample/maru.gif | Bin 481 -> 0 bytes ext/tcltklib/sample/sample0.rb | 39 - ext/tcltklib/sample/sample1.rb | 634 ------- ext/tcltklib/sample/sample2.rb | 449 ----- ext/tcltklib/stubs.c | 86 - ext/tcltklib/tcltklib.c | 561 ------- ext/tk/.cvsignore | 2 - ext/tk/MANIFEST | 25 - ext/tk/depend | 1 - ext/tk/extconf.rb | 2 - ext/tk/lib/README | 15 - ext/tk/lib/tk.rb | 3592 ---------------------------------------- ext/tk/lib/tkafter.rb | 316 ---- ext/tk/lib/tkbgerror.rb | 17 - ext/tk/lib/tkcanvas.rb | 863 ---------- ext/tk/lib/tkclass.rb | 38 - ext/tk/lib/tkdialog.rb | 141 -- ext/tk/lib/tkentry.rb | 221 --- ext/tk/lib/tkfont.rb | 1042 ------------ ext/tk/lib/tkmenubar.rb | 137 -- ext/tk/lib/tkmngfocus.rb | 27 - ext/tk/lib/tkpalette.rb | 48 - ext/tk/lib/tkscrollbox.rb | 29 - ext/tk/lib/tktext.rb | 1000 ----------- ext/tk/lib/tkvirtevent.rb | 81 - ext/tk/sample/tkbiff.rb | 149 -- ext/tk/sample/tkbrowse.rb | 79 - ext/tk/sample/tkdialog.rb | 62 - ext/tk/sample/tkfrom.rb | 132 -- ext/tk/sample/tkhello.rb | 10 - ext/tk/sample/tkline.rb | 45 - ext/tk/sample/tktimer.rb | 50 - ext/tk/tkutil.c | 45 - 198 files changed, 35615 deletions(-) delete mode 100644 ext/.cvsignore delete mode 100644 ext/Setup delete mode 100644 ext/Setup.dj delete mode 100644 ext/Setup.emx delete mode 100644 ext/Setup.nt delete mode 100644 ext/Setup.x68 delete mode 100644 ext/Win32API/.cvsignore delete mode 100644 ext/Win32API/MANIFEST delete mode 100644 ext/Win32API/Win32API.c delete mode 100644 ext/Win32API/depend delete mode 100644 ext/Win32API/extconf.rb delete mode 100644 ext/Win32API/getch.rb delete mode 100644 ext/Win32API/point.rb delete mode 100644 ext/aix_mksym.rb delete mode 100644 ext/configsub.rb delete mode 100644 ext/curses/.cvsignore delete mode 100644 ext/curses/MANIFEST delete mode 100644 ext/curses/curses.c delete mode 100644 ext/curses/depend delete mode 100644 ext/curses/extconf.rb delete mode 100644 ext/curses/hello.rb delete mode 100644 ext/curses/mouse.rb delete mode 100644 ext/curses/rain.rb delete mode 100644 ext/curses/view.rb delete mode 100644 ext/curses/view2.rb delete mode 100644 ext/dbm/.cvsignore delete mode 100644 ext/dbm/MANIFEST delete mode 100644 ext/dbm/dbm.c delete mode 100644 ext/dbm/depend delete mode 100644 ext/dbm/extconf.rb delete mode 100644 ext/dbm/testdbm.rb delete mode 100644 ext/digest/.cvsignore delete mode 100644 ext/digest/MANIFEST delete mode 100644 ext/digest/defs.h delete mode 100644 ext/digest/depend delete mode 100644 ext/digest/digest.c delete mode 100644 ext/digest/digest.h delete mode 100644 ext/digest/digest.txt delete mode 100644 ext/digest/digest.txt.ja delete mode 100644 ext/digest/extconf.rb delete mode 100644 ext/digest/lib/md5.rb delete mode 100644 ext/digest/lib/sha1.rb delete mode 100644 ext/digest/md5/.cvsignore delete mode 100644 ext/digest/md5/MANIFEST delete mode 100644 ext/digest/md5/depend delete mode 100644 ext/digest/md5/extconf.rb delete mode 100644 ext/digest/md5/md5.c delete mode 100644 ext/digest/md5/md5.h delete mode 100644 ext/digest/md5/md5init.c delete mode 100644 ext/digest/rmd160/.cvsignore delete mode 100644 ext/digest/rmd160/MANIFEST delete mode 100644 ext/digest/rmd160/depend delete mode 100644 ext/digest/rmd160/extconf.rb delete mode 100644 ext/digest/rmd160/rmd160.c delete mode 100644 ext/digest/rmd160/rmd160.h delete mode 100644 ext/digest/rmd160/rmd160hl.c delete mode 100644 ext/digest/rmd160/rmd160init.c delete mode 100644 ext/digest/sha1/.cvsignore delete mode 100644 ext/digest/sha1/MANIFEST delete mode 100644 ext/digest/sha1/depend delete mode 100644 ext/digest/sha1/extconf.rb delete mode 100644 ext/digest/sha1/sha1.c delete mode 100644 ext/digest/sha1/sha1.h delete mode 100644 ext/digest/sha1/sha1hl.c delete mode 100644 ext/digest/sha1/sha1init.c delete mode 100644 ext/digest/sha2/.cvsignore delete mode 100644 ext/digest/sha2/MANIFEST delete mode 100644 ext/digest/sha2/depend delete mode 100644 ext/digest/sha2/extconf.rb delete mode 100644 ext/digest/sha2/sha2.c delete mode 100644 ext/digest/sha2/sha2.h delete mode 100644 ext/digest/sha2/sha2hl.c delete mode 100644 ext/digest/sha2/sha2init.c delete mode 100644 ext/digest/test.rb delete mode 100644 ext/digest/test.sh delete mode 100644 ext/etc/.cvsignore delete mode 100644 ext/etc/MANIFEST delete mode 100644 ext/etc/depend delete mode 100644 ext/etc/etc.c delete mode 100644 ext/etc/etc.txt delete mode 100644 ext/etc/etc.txt.ja delete mode 100644 ext/etc/extconf.rb delete mode 100644 ext/extmk.rb.in delete mode 100644 ext/fcntl/.cvsignore delete mode 100644 ext/fcntl/MANIFEST delete mode 100644 ext/fcntl/depend delete mode 100644 ext/fcntl/fcntl.c delete mode 100644 ext/gdbm/.cvsignore delete mode 100644 ext/gdbm/MANIFEST delete mode 100644 ext/gdbm/README delete mode 100644 ext/gdbm/depend delete mode 100644 ext/gdbm/extconf.rb delete mode 100644 ext/gdbm/gdbm.c delete mode 100644 ext/gdbm/testgdbm.rb delete mode 100644 ext/iconv/MANIFEST delete mode 100644 ext/iconv/depend delete mode 100644 ext/iconv/extconf.rb delete mode 100644 ext/iconv/iconv.c delete mode 100644 ext/nkf/.cvsignore delete mode 100644 ext/nkf/MANIFEST delete mode 100644 ext/nkf/depend delete mode 100644 ext/nkf/extconf.rb delete mode 100644 ext/nkf/lib/kconv.rb delete mode 100644 ext/nkf/nkf.c delete mode 100644 ext/nkf/nkf1.7/nkf.c delete mode 100644 ext/nkf/test.rb delete mode 100644 ext/pty/.cvsignore delete mode 100644 ext/pty/MANIFEST delete mode 100644 ext/pty/README delete mode 100644 ext/pty/README.expect delete mode 100644 ext/pty/README.expect.ja delete mode 100644 ext/pty/README.ja delete mode 100644 ext/pty/depend delete mode 100644 ext/pty/expect_sample.rb delete mode 100644 ext/pty/extconf.rb delete mode 100644 ext/pty/lib/expect.rb delete mode 100644 ext/pty/pty.c delete mode 100644 ext/pty/script.rb delete mode 100644 ext/pty/shl.rb delete mode 100644 ext/readline/.cvsignore delete mode 100644 ext/readline/MANIFEST delete mode 100644 ext/readline/README delete mode 100644 ext/readline/README.ja delete mode 100644 ext/readline/depend delete mode 100644 ext/readline/extconf.rb delete mode 100644 ext/readline/readline.c delete mode 100644 ext/sdbm/.cvsignore delete mode 100644 ext/sdbm/MANIFEST delete mode 100644 ext/sdbm/_sdbm.c delete mode 100644 ext/sdbm/depend delete mode 100644 ext/sdbm/extconf.rb delete mode 100644 ext/sdbm/init.c delete mode 100644 ext/sdbm/sdbm.h delete mode 100644 ext/sdbm/testsdbm.rb delete mode 100644 ext/socket/.cvsignore delete mode 100644 ext/socket/MANIFEST delete mode 100644 ext/socket/addrinfo.h delete mode 100644 ext/socket/depend delete mode 100644 ext/socket/extconf.rb delete mode 100644 ext/socket/getaddrinfo.c delete mode 100644 ext/socket/getnameinfo.c delete mode 100644 ext/socket/socket.c delete mode 100644 ext/socket/sockport.h delete mode 100644 ext/stringio/MANIFEST delete mode 100644 ext/stringio/README delete mode 100644 ext/stringio/depend delete mode 100644 ext/stringio/stringio.c delete mode 100644 ext/syslog/.cvsignore delete mode 100644 ext/syslog/MANIFEST delete mode 100644 ext/syslog/depend delete mode 100644 ext/syslog/extconf.rb delete mode 100644 ext/syslog/syslog.c delete mode 100644 ext/syslog/syslog.txt delete mode 100644 ext/syslog/test.rb delete mode 100644 ext/tcltklib/.cvsignore delete mode 100644 ext/tcltklib/MANIFEST delete mode 100644 ext/tcltklib/MANUAL.euc delete mode 100644 ext/tcltklib/README.euc delete mode 100644 ext/tcltklib/demo/lines0.tcl delete mode 100644 ext/tcltklib/demo/lines1.rb delete mode 100644 ext/tcltklib/demo/lines2.rb delete mode 100644 ext/tcltklib/depend delete mode 100644 ext/tcltklib/extconf.rb delete mode 100644 ext/tcltklib/lib/tcltk.rb delete mode 100644 ext/tcltklib/sample/batsu.gif delete mode 100644 ext/tcltklib/sample/maru.gif delete mode 100644 ext/tcltklib/sample/sample0.rb delete mode 100644 ext/tcltklib/sample/sample1.rb delete mode 100644 ext/tcltklib/sample/sample2.rb delete mode 100644 ext/tcltklib/stubs.c delete mode 100644 ext/tcltklib/tcltklib.c delete mode 100644 ext/tk/.cvsignore delete mode 100644 ext/tk/MANIFEST delete mode 100644 ext/tk/depend delete mode 100644 ext/tk/extconf.rb delete mode 100644 ext/tk/lib/README delete mode 100644 ext/tk/lib/tk.rb delete mode 100644 ext/tk/lib/tkafter.rb delete mode 100644 ext/tk/lib/tkbgerror.rb delete mode 100644 ext/tk/lib/tkcanvas.rb delete mode 100644 ext/tk/lib/tkclass.rb delete mode 100644 ext/tk/lib/tkdialog.rb delete mode 100644 ext/tk/lib/tkentry.rb delete mode 100644 ext/tk/lib/tkfont.rb delete mode 100644 ext/tk/lib/tkmenubar.rb delete mode 100644 ext/tk/lib/tkmngfocus.rb delete mode 100644 ext/tk/lib/tkpalette.rb delete mode 100644 ext/tk/lib/tkscrollbox.rb delete mode 100644 ext/tk/lib/tktext.rb delete mode 100644 ext/tk/lib/tkvirtevent.rb delete mode 100644 ext/tk/sample/tkbiff.rb delete mode 100644 ext/tk/sample/tkbrowse.rb delete mode 100644 ext/tk/sample/tkdialog.rb delete mode 100644 ext/tk/sample/tkfrom.rb delete mode 100644 ext/tk/sample/tkhello.rb delete mode 100644 ext/tk/sample/tkline.rb delete mode 100644 ext/tk/sample/tktimer.rb delete mode 100644 ext/tk/tkutil.c (limited to 'ext') diff --git a/ext/.cvsignore b/ext/.cvsignore deleted file mode 100644 index a3fac48ae6..0000000000 --- a/ext/.cvsignore +++ /dev/null @@ -1,3 +0,0 @@ -extinit.c -extmk.log -extmk.rb diff --git a/ext/Setup b/ext/Setup deleted file mode 100644 index df88155294..0000000000 --- a/ext/Setup +++ /dev/null @@ -1,20 +0,0 @@ -#option nodynamic - -#GD -#curses -#dbm -#digest -#digest/md5 -#digest/rmd160 -#digest/sha1 -#digest/sha2 -#etc -#fcntl -#kconv -#pty -#sdbm -#socket -#syslog -#tk -#tcltklib -#gtk diff --git a/ext/Setup.dj b/ext/Setup.dj deleted file mode 100644 index 7d7aa7f87e..0000000000 --- a/ext/Setup.dj +++ /dev/null @@ -1,20 +0,0 @@ -option nodynamic - -#GD -#curses -dbm -digest -digest/md5 -digest/rmd160 -digest/sha1 -digest/sha2 -gdbm -#etc -fcntl -nkf -marshal -readline -sdbm -#socket -#syslog -#tkutil diff --git a/ext/Setup.emx b/ext/Setup.emx deleted file mode 100644 index bba3d76887..0000000000 --- a/ext/Setup.emx +++ /dev/null @@ -1,21 +0,0 @@ -option nodynamic - -#Win32API -curses -#dbm -digest -digest/md5 -digest/rmd160 -digest/sha1 -digest/sha2 -etc -fcntl -#gdbm -nkf -#pty -#readline -#sdbm -socket -#syslog -#tcltklib -#tk diff --git a/ext/Setup.nt b/ext/Setup.nt deleted file mode 100644 index cb0014350b..0000000000 --- a/ext/Setup.nt +++ /dev/null @@ -1,24 +0,0 @@ -#option nodynamic - -#GD -Win32API -#curses -#dbm -digest -digest/md5 -digest/rmd160 -digest/sha1 -digest/sha2 -#etc -fcntl -#gdbm -#gtk -marshal -nkf -#pty -#readline -sdbm -socket -#syslog -#tcltklib -#tk diff --git a/ext/Setup.x68 b/ext/Setup.x68 deleted file mode 100644 index 84b8902732..0000000000 --- a/ext/Setup.x68 +++ /dev/null @@ -1,17 +0,0 @@ -option nodynamic - -#GD -#curses -dbm -digest -digest/md5 -digest/rmd160 -digest/sha1 -digest/sha2 -#etc -fcntl -kconv -marshal -#socket -#syslog -#tkutil diff --git a/ext/Win32API/.cvsignore b/ext/Win32API/.cvsignore deleted file mode 100644 index f3c7a7c5da..0000000000 --- a/ext/Win32API/.cvsignore +++ /dev/null @@ -1 +0,0 @@ -Makefile diff --git a/ext/Win32API/MANIFEST b/ext/Win32API/MANIFEST deleted file mode 100644 index 7cc9ac445e..0000000000 --- a/ext/Win32API/MANIFEST +++ /dev/null @@ -1,7 +0,0 @@ -MANIFEST -depend -MANIFEST -Win32API.c -extconf.rb -getch.rb -point.rb diff --git a/ext/Win32API/Win32API.c b/ext/Win32API/Win32API.c deleted file mode 100644 index 65b6a558c1..0000000000 --- a/ext/Win32API/Win32API.c +++ /dev/null @@ -1,307 +0,0 @@ -/* - Win32API - Ruby Win32 API Import Facility -*/ - -#if !defined _MSC_VER && !defined NT -#define WIN32_LEAN_AND_MEAN -#include -#include -#endif - -#if defined(_MSC_VER) -#if defined(_M_ALPHA) -#ifdef __cplusplus -extern "C" { long __asm(char *,...); }; -#else -long __asm(char *,...); -#endif -#pragma intrinsic(__asm) -#endif -#endif - -#define _T_VOID 0 -#define _T_NUMBER 1 -#define _T_POINTER 2 -#define _T_INTEGER 3 - -typedef char *ApiPointer(void); -typedef long ApiNumber(void); -typedef void ApiVoid(void); -typedef int ApiInteger(void); - -#include "ruby.h" - -typedef struct { - HANDLE dll; - HANDLE proc; - VALUE dllname; - VALUE import; - VALUE export; -} Win32API; - -static void -Win32API_FreeLibrary(hdll) - HINSTANCE hdll; -{ - FreeLibrary(hdll); -} - -static VALUE -Win32API_initialize(self, dllname, proc, import, export) - VALUE self; - VALUE dllname; - VALUE proc; - VALUE import; - VALUE export; -{ - HANDLE hproc; - HINSTANCE hdll; - VALUE str; - VALUE a_import; - VALUE *ptr; - char *s; - int i; - int len; - int ex; - - SafeStringValue(dllname); - SafeStringValue(proc); - hdll = LoadLibrary(RSTRING(dllname)->ptr); - if (!hdll) - rb_raise(rb_eRuntimeError, "LoadLibrary: %s\n", RSTRING(dllname)->ptr); - rb_iv_set(self, "__hdll__", Data_Wrap_Struct(self, 0, Win32API_FreeLibrary, hdll)); - hproc = GetProcAddress(hdll, RSTRING(proc)->ptr); - if (!hproc) { - str = rb_str_new3(proc); - str = rb_str_cat(str, "A", 1); - hproc = GetProcAddress(hdll, RSTRING(str)->ptr); - if (!hproc) - rb_raise(rb_eRuntimeError, "GetProcAddress: %s or %s\n", - RSTRING(proc)->ptr, RSTRING(str)->ptr); - } - rb_iv_set(self, "__dll__", UINT2NUM((unsigned long)hdll)); - rb_iv_set(self, "__dllname__", dllname); - rb_iv_set(self, "__proc__", UINT2NUM((unsigned long)hproc)); - - a_import = rb_ary_new(); - switch (TYPE(import)) { - case T_NIL: - break; - case T_ARRAY: - ptr = RARRAY(import)->ptr; - for (i = 0, len = RARRAY(import)->len; i < len; i++) { - SafeStringValue(ptr[i]); - switch (*(char *)RSTRING(ptr[i])->ptr) { - case 'N': case 'n': case 'L': case 'l': - rb_ary_push(a_import, INT2FIX(_T_NUMBER)); - break; - case 'P': case 'p': - rb_ary_push(a_import, INT2FIX(_T_POINTER)); - break; - case 'I': case 'i': - rb_ary_push(a_import, INT2FIX(_T_INTEGER)); - break; - } - } - break; - default: - SafeStringValue(import); - s = RSTRING(import)->ptr; - for (i = 0, len = RSTRING(import)->len; i < len; i++) { - switch (*s++) { - case 'N': case 'n': case 'L': case 'l': - rb_ary_push(a_import, INT2FIX(_T_NUMBER)); - break; - case 'P': case 'p': - rb_ary_push(a_import, INT2FIX(_T_POINTER)); - break; - case 'I': case 'i': - rb_ary_push(a_import, INT2FIX(_T_INTEGER)); - break; - } - } - break; - } - rb_iv_set(self, "__import__", a_import); - - if (NIL_P(export)) { - ex = _T_VOID; - } else { - SafeStringValue(export); - switch (*RSTRING(export)->ptr) { - case 'V': case 'v': - ex = _T_VOID; - break; - case 'N': case 'n': case 'L': case 'l': - ex = _T_NUMBER; - break; - case 'P': case 'p': - ex = _T_POINTER; - break; - case 'I': case 'i': - ex = _T_INTEGER; - break; - } - } - rb_iv_set(self, "__export__", INT2FIX(ex)); - - return Qnil; -} - -static VALUE -Win32API_Call(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE args; - - FARPROC ApiFunction; - - ApiPointer *ApiFunctionPointer; - ApiNumber *ApiFunctionNumber; - ApiVoid *ApiFunctionVoid; - ApiInteger *ApiFunctionInteger; - - long lParam; - char *pParam; - - VALUE Return; - - VALUE obj_proc; - VALUE obj_import; - VALUE obj_export; - VALUE import_type; - int nimport, timport, texport, i; - int items; - int ret; - - items = rb_scan_args(argc, argv, "0*", &args); - - obj_proc = rb_iv_get(obj, "__proc__"); - - ApiFunction = (FARPROC)NUM2ULONG(obj_proc); - - obj_import = rb_iv_get(obj, "__import__"); - obj_export = rb_iv_get(obj, "__export__"); - nimport = RARRAY(obj_import)->len; - texport = FIX2INT(obj_export); - - if (items != nimport) - rb_raise(rb_eRuntimeError, "Wrong number of parameters: expected %d, got %d.\n", - nimport, items); - - if (0 < nimport) { - for (i = nimport - 1; 0 <= i; i--) { - VALUE str; - import_type = rb_ary_entry(obj_import, i); - timport = FIX2INT(import_type); - switch (timport) { - case _T_NUMBER: - case _T_INTEGER: - lParam = NUM2ULONG(rb_ary_entry(args, i)); -#if defined(_MSC_VER) || defined(__LCC__) -#if defined(_M_IX86) - _asm { - mov eax, lParam - push eax - } -#elif defined(_M_ALPHA) - __asm( - "ldl r0, 0(%0);" - "stq r0, -(sp);" - , lParam - ); -#else -#error -#endif -#elif defined __GNUC__ - asm volatile ("pushl %0" :: "g" (lParam)); -#else -#error -#endif - break; - case _T_POINTER: - str = rb_ary_entry(args, i); - if (NIL_P(str)) { - pParam = 0; - } else if (FIXNUM_P(str)){ - pParam = (char *)NUM2ULONG(str); - } else { - StringValue(str); - rb_str_modify(str); - pParam = RSTRING(str)->ptr; - } -#if defined(_MSC_VER) || defined(__LCC__) -#if defined(_M_IX86) - _asm { - mov eax, pParam - push eax - } -#elif defined(_M_ALPHA) - __asm( - "ldl r0, 0(%0);" - "stq r0, -(sp);" - , pParam - ); -#else -#error -#endif -#elif defined __GNUC__ - asm volatile ("pushl %0" :: "g" (pParam)); -#else -#error -#endif - break; - } - } - } - -#if defined __GNUC__ - asm volatile ("call *%1" : "=r" (ret) : "g" (ApiFunction)); - switch (texport) { - case _T_NUMBER: - case _T_INTEGER: - Return = INT2NUM(ret); - break; - case _T_POINTER: - Return = rb_str_new2((char *)ret); - break; - case _T_VOID: - default: - Return = INT2NUM(0); - break; - } -#else - switch (texport) { - case _T_NUMBER: - ApiFunctionNumber = (ApiNumber *) ApiFunction; - Return = INT2NUM(ApiFunctionNumber()); - break; - case _T_POINTER: - ApiFunctionPointer = (ApiPointer *) ApiFunction; - Return = rb_str_new2((char *)ApiFunctionPointer()); - break; - case _T_INTEGER: - ApiFunctionInteger = (ApiInteger *) ApiFunction; - Return = INT2NUM(ApiFunctionInteger()); - break; - case _T_VOID: - default: - ApiFunctionVoid = (ApiVoid *) ApiFunction; - ApiFunctionVoid(); - Return = INT2NUM(0); - break; - } -#endif - return Return; -} - -void -Init_Win32API() -{ - VALUE cWin32API = rb_define_class("Win32API", rb_cObject); - rb_define_method(cWin32API, "initialize", Win32API_initialize, 4); - rb_define_method(cWin32API, "call", Win32API_Call, -1); - rb_define_alias(cWin32API, "Call", "call"); -} diff --git a/ext/Win32API/depend b/ext/Win32API/depend deleted file mode 100644 index b224bb66c9..0000000000 --- a/ext/Win32API/depend +++ /dev/null @@ -1 +0,0 @@ -Win32API.o : Win32API.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/Win32API/extconf.rb b/ext/Win32API/extconf.rb deleted file mode 100644 index 5e42f62558..0000000000 --- a/ext/Win32API/extconf.rb +++ /dev/null @@ -1,7 +0,0 @@ -case RUBY_PLATFORM -when /cygwin/,/mingw/ - $CFLAGS = "-fno-defer-pop -fno-omit-frame-pointer" - create_makefile("Win32API") -when /win32/ - create_makefile("Win32API") -end diff --git a/ext/Win32API/getch.rb b/ext/Win32API/getch.rb deleted file mode 100644 index c015bbe9bc..0000000000 --- a/ext/Win32API/getch.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'Win32API' - -getch = Win32API.new("crtdll", "_getch", [], 'L') - -puts getch.Call.chr diff --git a/ext/Win32API/point.rb b/ext/Win32API/point.rb deleted file mode 100644 index 60e265f3ee..0000000000 --- a/ext/Win32API/point.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'Win32API' - -getCursorPos = Win32API.new("user32", "GetCursorPos", ['P'], 'V') - -lpPoint = " " * 8 # store two LONGs -getCursorPos.Call(lpPoint) -x, y = lpPoint.unpack("LL") # get the actual values - -print "x: ", x, "\n" -print "y: ", y, "\n" - -ods = Win32API.new("kernel32", "OutputDebugString", ['P'], 'V') -ods.Call("Hello, World\n"); - -GetDesktopWindow = Win32API.new("user32", "GetDesktopWindow", [], 'L') -GetActiveWindow = Win32API.new("user32", "GetActiveWindow", [], 'L') -SendMessage = Win32API.new("user32", "SendMessage", ['L'] * 4, 'L') -SendMessage.Call GetDesktopWindow.Call, 274, 0xf140, 0 diff --git a/ext/aix_mksym.rb b/ext/aix_mksym.rb deleted file mode 100644 index 7e1af283dc..0000000000 --- a/ext/aix_mksym.rb +++ /dev/null @@ -1,33 +0,0 @@ - -def uniq(data) - last=nil - data.delete_if do |name| - if last == name - TRUE - else - last = name - FALSE - end - end -end - -def extract(nm, out) - data = nm.readlines.collect{|line| - line = line.split - case line[1] - when "B", "D" - line[0] - else - next - end - }.compact!.sort! - uniq(data) - exp = open(out, "w") - exp.printf "#!\n" - for line in data - exp.printf "%s\n", line - end - exp.close - nm.close -end -extract(open("|/usr/ccs/bin/nm -p ../libruby.a"), "../ruby.imp") diff --git a/ext/configsub.rb b/ext/configsub.rb deleted file mode 100644 index 47689d7ec0..0000000000 --- a/ext/configsub.rb +++ /dev/null @@ -1,32 +0,0 @@ -#!./miniruby -ps - -BEGIN { - CONFIG = {} - - RUBY_VERSION.scan(/(\d+)\.(\d+)\.(\d+)/) do - # overridden if config.status has version - CONFIG['MAJOR'] = $1 - CONFIG['MINOR'] = $2 - CONFIG['TEENY'] = $3 - end - - File.foreach($config || "config.status") do |line| - next if /^#/ =~ line - if /^s[%,]@(\w+)@[%,](.*)[%,][g;]/ =~ line - name = $1 - val = $2 || "" - next if /^(INSTALL|DEFS|configure_input|srcdir)$/ =~ name - val.gsub!(/\$\{([^{}]+)\}/) { "$(#{$1})" } - CONFIG[name] = val - end - end - - CONFIG['top_srcdir'] = File.expand_path($srcdir || ".") - CONFIG['RUBY_INSTALL_NAME'] = $install_name if $install_name - CONFIG['RUBY_SO_NAME'] = $so_name if $so_name - $defout = open($output, 'w') if $output -} - -gsub!(/@(\w+)@/) {CONFIG[$1] || $&} - -# vi:set sw=2: diff --git a/ext/curses/.cvsignore b/ext/curses/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/curses/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/curses/MANIFEST b/ext/curses/MANIFEST deleted file mode 100644 index 5882d682f0..0000000000 --- a/ext/curses/MANIFEST +++ /dev/null @@ -1,9 +0,0 @@ -MANIFEST -curses.c -depend -extconf.rb -hello.rb -rain.rb -view.rb -view2.rb -mouse.rb diff --git a/ext/curses/curses.c b/ext/curses/curses.c deleted file mode 100644 index 2a48508b01..0000000000 --- a/ext/curses/curses.c +++ /dev/null @@ -1,1874 +0,0 @@ -/* -*- C -*- - * $Id$ - * - * ext/curses/curses.c - * - * by MAEDA Shugo (ender@pic-internet.or.jp) - * modified by Yukihiro Matsumoto (matz@netlab.co.jp), - * Toki Yoshinori, - * Hitoshi Takahashi, - * and Takaaki Tateishi (ttate@kt.jaist.ac.jp) - * - * maintainers: - * - Takaaki Tateishi (ttate@kt.jaist.ac.jp) - */ - -#ifdef HAVE_NCURSES_H -# include -#else -# ifdef HAVE_NCURSES_CURSES_H -# include -#else -# ifdef HAVE_CURSES_COLR_CURSES_H -# include -# include -# else -# include -# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_maxx) -# define _maxx maxx -# endif -# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_maxy) -# define _maxy maxy -# endif -# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_begx) -# define _begx begx -# endif -# if (defined(__bsdi__) || defined(__NetBSD__) || defined(__APPLE__)) && !defined(_begy) -# define _begy begy -# endif -# endif -#endif -#endif - -#ifdef HAVE_INIT_COLOR -# define USE_COLOR 1 -#endif - -/* supports only ncurses mouse routines */ -#ifdef NCURSES_MOUSE_VERSION -# define USE_MOUSE 1 -#endif - -#include "stdio.h" -#include "ruby.h" -#include "rubyio.h" - -static VALUE mCurses; -static VALUE mKey; -static VALUE cWindow; -#ifdef USE_MOUSE -static VALUE cMouseEvent; -#endif - -VALUE rb_stdscr; - -struct windata { - WINDOW *window; -}; - -#define CHECK(c) c - -static VALUE window_attroff(); -static VALUE window_attron(); -static VALUE window_attrset(); - -static void -no_window() -{ - rb_raise(rb_eRuntimeError, "already closed window"); -} - - -#define GetWINDOW(obj, winp) {\ - Data_Get_Struct(obj, struct windata, winp);\ - if (winp->window == 0) no_window();\ -} - - -static void -free_window(winp) - struct windata *winp; -{ - if (winp->window && winp->window != stdscr) delwin(winp->window); - winp->window = 0; - free(winp); -} - -static VALUE -prep_window(class, window) - VALUE class; - WINDOW *window; -{ - VALUE obj; - struct windata *winp; - - if (window == NULL) { - rb_raise(rb_eRuntimeError, "failed to create window"); - } - - obj = Data_Make_Struct(class, struct windata, 0, free_window, winp); - winp->window = window; - - return obj; -} - -/*-------------------------- module Curses --------------------------*/ - -/* def init_screen */ -static VALUE -curses_init_screen() -{ - initscr(); - if (stdscr == 0) { - rb_raise(rb_eRuntimeError, "cannot initialize curses"); - } - clear(); - rb_stdscr = prep_window(cWindow, stdscr); - return rb_stdscr; -} - -/* def stdscr */ -static VALUE -curses_stdscr() -{ - if (rb_stdscr == 0) curses_init_screen(); - return rb_stdscr; -} - -/* def close_screen */ -static VALUE -curses_close_screen() -{ -#ifdef HAVE_ISENDWIN - if (!isendwin()) -#endif - endwin(); - return Qnil; -} - -static void -curses_finalize() -{ - if (stdscr -#ifdef HAVE_ISENDWIN - && !isendwin() -#endif - ) - endwin(); -} - -/* def closed? */ -static VALUE -curses_closed() -{ -#ifdef HAVE_ISENDWIN - if (isendwin()) { - return Qtrue; - } - return Qfalse; -#else - rb_notimplement(); -#endif -} - -/* def clear */ -static VALUE -curses_clear(obj) - VALUE obj; -{ - wclear(stdscr); - return Qnil; -} - -/* def refresh */ -static VALUE -curses_refresh(obj) - VALUE obj; -{ - refresh(); - return Qnil; -} - -/* def doupdate */ -static VALUE -curses_doupdate(obj) - VALUE obj; -{ -#ifdef HAVE_DOUPDATE - doupdate(); -#else - refresh(); -#endif - return Qnil; -} - -/* def echo */ -static VALUE -curses_echo(obj) - VALUE obj; -{ - echo(); - return Qnil; -} - -/* def noecho */ -static VALUE -curses_noecho(obj) - VALUE obj; -{ - noecho(); - return Qnil; -} - -/* def raw */ -static VALUE -curses_raw(obj) - VALUE obj; -{ - raw(); - return Qnil; -} - -/* def noraw */ -static VALUE -curses_noraw(obj) - VALUE obj; -{ - noraw(); - return Qnil; -} - -/* def cbreak */ -static VALUE -curses_cbreak(obj) - VALUE obj; -{ - cbreak(); - return Qnil; -} - -/* def nocbreak */ -static VALUE -curses_nocbreak(obj) - VALUE obj; -{ - nocbreak(); - return Qnil; -} - -/* def nl */ -static VALUE -curses_nl(obj) - VALUE obj; -{ - nl(); - return Qnil; -} - -/* def nonl */ -static VALUE -curses_nonl(obj) - VALUE obj; -{ - nonl(); - return Qnil; -} - -/* def beep */ -static VALUE -curses_beep(obj) - VALUE obj; -{ -#ifdef HAVE_BEEP - beep(); -#endif - return Qnil; -} - -/* def flash */ -static VALUE -curses_flash(obj) - VALUE obj; -{ -#ifdef HAVE_FLASH - flash(); -#endif - return Qnil; -} - -/* def ungetch */ -static VALUE -curses_ungetch(obj, ch) - VALUE obj; - VALUE ch; -{ -#ifdef HAVE_UNGETCH - ungetch(NUM2INT(ch)); -#else - rb_notimplement(); -#endif - return Qnil; -} - -/* def setpos(y, x) */ -static VALUE -curses_setpos(obj, y, x) - VALUE obj; - VALUE y; - VALUE x; -{ - move(NUM2INT(y), NUM2INT(x)); - return Qnil; -} - -/* def standout */ -static VALUE -curses_standout(obj) - VALUE obj; -{ - standout(); - return Qnil; -} - -/* def standend */ -static VALUE -curses_standend(obj) - VALUE obj; -{ - standend(); - return Qnil; -} - -/* def inch */ -static VALUE -curses_inch(obj) - VALUE obj; -{ - return CHR2FIX(inch()); -} - -/* def addch(ch) */ -static VALUE -curses_addch(obj, ch) - VALUE obj; - VALUE ch; -{ - addch(NUM2CHR(ch)); - return Qnil; -} - -/* def insch(ch) */ -static VALUE -curses_insch(obj, ch) - VALUE obj; - VALUE ch; -{ - insch(NUM2CHR(ch)); - return Qnil; -} - -/* def addstr(str) */ -static VALUE -curses_addstr(obj, str) - VALUE obj; - VALUE str; -{ - if (!NIL_P(str)) { - addstr(STR2CSTR(str)); - } - return Qnil; -} - -/* def getch */ -static VALUE -curses_getch(obj) - VALUE obj; -{ - rb_read_check(stdin); - return UINT2NUM(getch()); -} - -/* def getstr */ -static VALUE -curses_getstr(obj) - VALUE obj; -{ - char rtn[1024]; /* This should be big enough.. I hope */ - - rb_read_check(stdin); -#if defined(HAVE_GETNSTR) - getnstr(rtn,1023); -#else - getstr(rtn); -#endif - return rb_tainted_str_new2(rtn); -} - -/* def delch */ -static VALUE -curses_delch(obj) - VALUE obj; -{ - delch(); - return Qnil; -} - -/* def delelteln */ -static VALUE -curses_deleteln(obj) - VALUE obj; -{ -#if defined(HAVE_DELETELN) || defined(deleteln) - deleteln(); -#endif - return Qnil; -} - -/* def keyname */ -static VALUE -curses_keyname(obj, c) - VALUE obj; - VALUE c; -{ -#ifdef HAVE_KEYNAME - const char *name; - - name = keyname(NUM2INT(c)); - if (name) { - return rb_str_new2(name); - } else { - return Qnil; - } -#else - return Qnil; -#endif -} - -static VALUE -curses_lines() -{ - return INT2FIX(LINES); -} - -static VALUE -curses_cols() -{ - return INT2FIX(COLS); -} - -static VALUE -curses_curs_set(VALUE obj, VALUE visibility) -{ - int n; - return (n = curs_set(NUM2INT(visibility)) != ERR) ? INT2FIX(n) : Qnil; -} - -static VALUE -curses_scrl(VALUE obj, VALUE n) -{ - /* may have to raise exception on ERR */ - return (scrl(NUM2INT(n)) == OK) ? Qtrue : Qfalse; -} - -static VALUE -curses_setscrreg(VALUE obj, VALUE top, VALUE bottom) -{ - /* may have to raise exception on ERR */ - return (setscrreg(NUM2INT(top), NUM2INT(bottom)) == OK) ? Qtrue : Qfalse; -} - -static VALUE -curses_attroff(VALUE obj, VALUE attrs) -{ - return window_attroff(rb_stdscr,attrs); - /* return INT2FIX(attroff(NUM2INT(attrs))); */ -} - -static VALUE -curses_attron(VALUE obj, VALUE attrs) -{ - return window_attron(rb_stdscr,attrs); - /* return INT2FIX(attroff(NUM2INT(attrs))); */ -} - -static VALUE -curses_attrset(VALUE obj, VALUE attrs) -{ - return window_attrset(rb_stdscr,attrs); - /* return INT2FIX(attroff(NUM2INT(attrs))); */ -} - -static VALUE -curses_bkgdset(VALUE obj, VALUE ch) -{ - bkgdset(NUM2CHR(ch)); - return Qnil; -} - -static VALUE -curses_bkgd(VALUE obj, VALUE ch) -{ - return CHR2FIX(bkgd(NUM2CHR(ch))); -} - -static VALUE -curses_resizeterm(VALUE obj, VALUE lines, VALUE columns) -{ -#if defined(HAVE_RESIZETERM) - return (resizeterm(NUM2INT(lines),NUM2INT(columns)) == OK) ? Qtrue : Qfalse; -#else - return Qnil; -#endif -} - -#ifdef USE_COLOR -static VALUE -curses_start_color(VALUE obj) -{ - /* may have to raise exception on ERR */ - return (start_color() == OK) ? Qtrue : Qfalse; -} - -static VALUE -curses_init_pair(VALUE obj, VALUE pair, VALUE f, VALUE b) -{ - /* may have to raise exception on ERR */ - return (init_pair(NUM2INT(pair),NUM2INT(f),NUM2INT(b)) == OK) ? Qtrue : Qfalse; -} - -static VALUE -curses_init_color(VALUE obj, VALUE color, VALUE r, VALUE g, VALUE b) -{ - /* may have to raise exception on ERR */ - return (init_color(NUM2INT(color),NUM2INT(r), - NUM2INT(g),NUM2INT(b)) == OK) ? Qtrue : Qfalse; -} - -static VALUE -curses_has_colors(VALUE obj) -{ - return has_colors() ? Qtrue : Qfalse; -} - -static VALUE -curses_can_change_color(VALUE obj) -{ - return can_change_color() ? Qtrue : Qfalse; -} - -static VALUE -curses_color_content(VALUE obj, VALUE color) -{ - short r,g,b; - - color_content(NUM2INT(color),&r,&g,&b); - return rb_ary_new3(3,INT2FIX(r),INT2FIX(g),INT2FIX(b)); -} - -static VALUE -curses_pair_content(VALUE obj, VALUE pair) -{ - short f,b; - - pair_content(NUM2INT(pair),&f,&b); - return rb_ary_new3(2,INT2FIX(f),INT2FIX(b)); -} - -static VALUE -curses_color_pair(VALUE obj, VALUE attrs) -{ - return INT2FIX(COLOR_PAIR(NUM2INT(attrs))); -} - -static VALUE -curses_pair_number(VALUE obj, VALUE attrs) -{ - return INT2FIX(PAIR_NUMBER(NUM2INT(attrs))); -} -#endif - -#ifdef USE_MOUSE -struct mousedata { - MEVENT *mevent; -}; - -static void -no_mevent() -{ - rb_raise(rb_eRuntimeError, "no such mouse event"); -}; - -#define GetMOUSE(obj, data) {\ - Data_Get_Struct(obj, struct mousedata, data);\ - if (data->mevent == 0) no_mevent();\ -} - -static void -curses_mousedata_free(struct mousedata *mdata) -{ - if (mdata->mevent) - free(mdata->mevent); -}; - -static VALUE -curses_getmouse(VALUE obj) -{ - struct mousedata *mdata; - VALUE val; - - val = Data_Make_Struct(cMouseEvent,struct mousedata, - 0,curses_mousedata_free,mdata); - mdata->mevent = (MEVENT*)malloc(sizeof(MEVENT)); - return (getmouse(mdata->mevent) == OK) ? val : Qnil; -}; - -static VALUE -curses_ungetmouse(VALUE obj, VALUE mevent) -{ - struct mousedata *mdata; - - GetMOUSE(mevent,mdata); - return (ungetmouse(mdata->mevent) == OK) ? Qtrue : Qfalse; -}; - -static VALUE -curses_mouseinterval(VALUE obj, VALUE interval) -{ - return mouseinterval(NUM2INT(interval)) ? Qtrue : Qfalse; -}; - -static VALUE -curses_mousemask(VALUE obj, VALUE mask) -{ - return INT2NUM(mousemask(NUM2UINT(mask),NULL)); -}; - -#define DEFINE_MOUSE_GET_MEMBER(func_name,mem) \ -static VALUE func_name (VALUE mouse) \ -{ \ - struct mousedata *mdata; \ - GetMOUSE(mouse, mdata); \ - return (UINT2NUM(mdata->mevent -> mem)); \ -} - -DEFINE_MOUSE_GET_MEMBER(curs_mouse_id, id); -DEFINE_MOUSE_GET_MEMBER(curs_mouse_x, x); -DEFINE_MOUSE_GET_MEMBER(curs_mouse_y, y); -DEFINE_MOUSE_GET_MEMBER(curs_mouse_z, z); -DEFINE_MOUSE_GET_MEMBER(curs_mouse_bstate, bstate); -#undef define_curs_mouse_member -#endif /* USE_MOUSE */ - -/*-------------------------- class Window --------------------------*/ - -/* def new(h, w, top, left) */ -static VALUE -window_s_new(class, h, w, top, left) - VALUE class; - VALUE h; - VALUE w; - VALUE top; - VALUE left; -{ - VALUE win; - WINDOW *window; - VALUE args[4]; - - window = newwin(NUM2INT(h), NUM2INT(w), NUM2INT(top), NUM2INT(left)); - wclear(window); - win = prep_window(class, window); - args[0] = h; args[1] = w; args[2] = top; args[3] = left; - - return win; -} - -/* def subwin(h, w, top, left) */ -static VALUE -window_subwin(obj, h, w, top, left) - VALUE obj; - VALUE h; - VALUE w; - VALUE top; - VALUE left; -{ - struct windata *winp; - WINDOW *window; - VALUE win; - VALUE args[4]; - - GetWINDOW(obj, winp); - window = subwin(winp->window, NUM2INT(h), NUM2INT(w), - NUM2INT(top), NUM2INT(left)); - win = prep_window(cWindow, window); - args[0] = h; args[1] = w; args[2] = top; args[3] = left; - - return win; -} - -/* def close */ -static VALUE -window_close(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - delwin(winp->window); - winp->window = 0; - - return Qnil; -} - -/* def clear */ -static VALUE -window_clear(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - wclear(winp->window); - - return Qnil; -} - -/* def refresh */ -static VALUE -window_refresh(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - wrefresh(winp->window); - - return Qnil; -} - -/* def noutrefresh */ -static VALUE -window_noutrefresh(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); -#ifdef HAVE_DOUPDATE - wnoutrefresh(winp->window); -#else - wrefresh(winp->window); -#endif - - return Qnil; -} - -/* def move(y, x) */ -static VALUE -window_move(obj, y, x) - VALUE obj; - VALUE y; - VALUE x; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - mvwin(winp->window, NUM2INT(y), NUM2INT(x)); - - return Qnil; -} - -/* def setpos(y, x) */ -static VALUE -window_setpos(obj, y, x) - VALUE obj; - VALUE y; - VALUE x; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - wmove(winp->window, NUM2INT(y), NUM2INT(x)); - return Qnil; -} - -/* def cury */ -static VALUE -window_cury(obj) - VALUE obj; -{ - struct windata *winp; - int x, y; - - GetWINDOW(obj, winp); - getyx(winp->window, y, x); - return INT2FIX(y); -} - -/* def curx */ -static VALUE -window_curx(obj) - VALUE obj; -{ - struct windata *winp; - int x, y; - - GetWINDOW(obj, winp); - getyx(winp->window, y, x); - return INT2FIX(x); -} - -/* def maxy */ -static VALUE -window_maxy(obj) - VALUE obj; -{ - struct windata *winp; - int x, y; - - GetWINDOW(obj, winp); -#ifdef getmaxy - return INT2FIX(getmaxy(winp->window)); -#else -#ifdef getmaxyx - getmaxyx(winp->window, y, x); - return INT2FIX(y); -#else - return INT2FIX(winp->window->_maxy+1); -#endif -#endif -} - -/* def maxx */ -static VALUE -window_maxx(obj) - VALUE obj; -{ - struct windata *winp; - int x, y; - - GetWINDOW(obj, winp); -#ifdef getmaxx - return INT2FIX(getmaxx(winp->window)); -#else -#ifdef getmaxyx - getmaxyx(winp->window, y, x); - return INT2FIX(x); -#else - return INT2FIX(winp->window->_maxx+1); -#endif -#endif -} - -/* def begy */ -static VALUE -window_begy(obj) - VALUE obj; -{ - struct windata *winp; - int x, y; - - GetWINDOW(obj, winp); -#ifdef getbegyx - getbegyx(winp->window, y, x); - return INT2FIX(y); -#else - return INT2FIX(winp->window->_begy); -#endif -} - -/* def begx */ -static VALUE -window_begx(obj) - VALUE obj; -{ - struct windata *winp; - int x, y; - - GetWINDOW(obj, winp); -#ifdef getbegyx - getbegyx(winp->window, y, x); - return INT2FIX(x); -#else - return INT2FIX(winp->window->_begx); -#endif -} - -/* def box(vert, hor) */ -static VALUE -window_box(argc, argv, self) - int argc; - VALUE argv[], self; -{ - struct windata *winp; - VALUE vert, hor, corn; - - rb_scan_args(argc, argv, "21", &vert, &hor, &corn); - - GetWINDOW(self, winp); - box(winp->window, NUM2CHR(vert), NUM2CHR(hor)); - - if( argc == 3 ){ - int cur_x, cur_y, x, y; - char c; - - c = NUM2CHR(corn); - getyx(winp->window, cur_y, cur_x); - x = NUM2INT(window_maxx(self)) - 1; - y = NUM2INT(window_maxy(self)) - 1; - wmove(winp->window, 0, 0); - waddch(winp->window, c); - wmove(winp->window, y, 0); - waddch(winp->window, c); - wmove(winp->window, y, x); - waddch(winp->window, c); - wmove(winp->window, 0, x); - waddch(winp->window, c); - wmove(winp->window, cur_y, cur_x); - } - - return Qnil; -} - -/* def standout */ -static VALUE -window_standout(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - wstandout(winp->window); - return Qnil; -} - -/* def standend */ -static VALUE -window_standend(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - wstandend(winp->window); - return Qnil; -} - -/* def inch */ -static VALUE -window_inch(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - return CHR2FIX(winch(winp->window)); -} - -/* def addch(ch) */ -static VALUE -window_addch(obj, ch) - VALUE obj; - VALUE ch; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - waddch(winp->window, NUM2CHR(ch)); - - return Qnil; -} - -/* def insch(ch) */ -static VALUE -window_insch(obj, ch) - VALUE obj; - VALUE ch; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - winsch(winp->window, NUM2CHR(ch)); - - return Qnil; -} - -/* def addstr(str) */ -static VALUE -window_addstr(obj, str) - VALUE obj; - VALUE str; -{ - if (!NIL_P(str)) { - struct windata *winp; - - GetWINDOW(obj, winp); - waddstr(winp->window, STR2CSTR(str)); - } - return Qnil; -} - -/* def <<(str) */ -static VALUE -window_addstr2(obj, str) - VALUE obj; - VALUE str; -{ - window_addstr(obj, str); - return obj; -} - -/* def getch */ -static VALUE -window_getch(obj) - VALUE obj; -{ - struct windata *winp; - - rb_read_check(stdin); - GetWINDOW(obj, winp); - return UINT2NUM(wgetch(winp->window)); -} - -/* def getstr */ -static VALUE -window_getstr(obj) - VALUE obj; -{ - struct windata *winp; - char rtn[1024]; /* This should be big enough.. I hope */ - - GetWINDOW(obj, winp); - rb_read_check(stdin); -#if defined(HAVE_WGETNSTR) - wgetnstr(winp->window, rtn, 1023); -#else - wgetstr(winp->window, rtn); -#endif - return rb_tainted_str_new2(rtn); -} - -/* def delch */ -static VALUE -window_delch(obj) - VALUE obj; -{ - struct windata *winp; - - GetWINDOW(obj, winp); - wdelch(winp->window); - return Qnil; -} - -/* def delelteln */ -static VALUE -window_deleteln(obj) - VALUE obj; -{ -#if defined(HAVE_WDELETELN) || defined(wdeleteln) - struct windata *winp; - - GetWINDOW(obj, winp); - wdeleteln(winp->window); -#endif - return Qnil; -} - -static VALUE -window_scrollok(VALUE obj, VALUE bf) -{ - struct windata *winp; - - GetWINDOW(obj, winp); - scrollok(winp->window, RTEST(bf) ? TRUE : FALSE); - return Qnil; -} - -static VALUE -window_idlok(VALUE obj, VALUE bf) -{ - struct windata *winp; - int res; - - GetWINDOW(obj, winp); - idlok(winp->window, RTEST(bf) ? TRUE : FALSE); - return Qnil; -} - -static VALUE -window_setscrreg(VALUE obj, VALUE top, VALUE bottom) -{ - struct windata *winp; - int res; - - GetWINDOW(obj, winp); - res = wsetscrreg(winp->window, NUM2INT(top), NUM2INT(bottom)); - /* may have to raise exception on ERR */ - return (res == OK) ? Qtrue : Qfalse; -}; - -static VALUE -window_scroll(VALUE obj) -{ - struct windata *winp; - - GetWINDOW(obj, winp); - /* may have to raise exception on ERR */ - return (scroll(winp->window) == OK) ? Qtrue : Qfalse; -} - -static VALUE -window_scrl(VALUE obj, VALUE n) -{ - struct windata *winp; - - GetWINDOW(obj, winp); - /* may have to raise exception on ERR */ - return (wscrl(winp->window,NUM2INT(n)) == OK) ? Qtrue : Qfalse; -} - -static VALUE -window_attroff(VALUE obj, VALUE attrs) -{ - struct windata *winp; - - GetWINDOW(obj,winp); - return INT2FIX(wattroff(winp->window,NUM2INT(attrs))); -}; - -static VALUE -window_attron(VALUE obj, VALUE attrs) -{ - struct windata *winp; - VALUE val; - - GetWINDOW(obj,winp); - val = INT2FIX(wattron(winp->window,NUM2INT(attrs))); - if( rb_block_given_p() ){ - rb_yield(val); - wattroff(winp->window,NUM2INT(attrs)); - return val; - } - else{ - return val; - }; -}; - -static VALUE -window_attrset(VALUE obj, VALUE attrs) -{ - struct windata *winp; - - GetWINDOW(obj,winp); - return INT2FIX(wattrset(winp->window,NUM2INT(attrs))); -} - -static VALUE -window_bkgdset(VALUE obj, VALUE ch) -{ - struct windata *winp; - - GetWINDOW(obj,winp); - wbkgdset(winp->window, NUM2CHR(ch)); - return Qnil; -} - -static VALUE -window_bkgd(VALUE obj, VALUE ch) -{ - struct windata *winp; - - GetWINDOW(obj,winp); - return CHR2FIX(wbkgd(winp->window, NUM2CHR(ch))); -} - -static VALUE -window_getbkgd(VALUE obj) -{ - struct windata *winp; - - GetWINDOW(obj,winp); - return CHR2FIX(getbkgd(winp->window)); -} - -static VALUE -window_resize(VALUE obj, VALUE lines, VALUE columns) -{ -#if defined(HAVE_WRESIZE) - struct windata *winp; - - GetWINDOW(obj,winp); - return wresize(winp->window, NUM2INT(lines), NUM2INT(columns)) == OK ? Qtrue : Qfalse; -#else - return Qnil; -#endif -} - - -#ifdef HAVE_KEYPAD -static VALUE -window_keypad(VALUE obj, VALUE val) -{ - struct windata *winp; - - GetWINDOW(obj,winp); - /* keypad() of NetBSD's libcurses returns no value */ -#if defined(__NetBSD__) && !defined(NCURSES_VERSION) - keypad(winp->window,(RTEST(val) ? TRUE : FALSE)); - return Qnil; -#else - /* may have to raise exception on ERR */ - return (keypad(winp->window,RTEST(val) ? TRUE : FALSE)) == OK ? - Qtrue : Qfalse; -#endif -}; -#endif /* HAVE_KEYPAD */ - -/*------------------------- Initialization -------------------------*/ -void -Init_curses() -{ - mCurses = rb_define_module("Curses"); - mKey = rb_define_module_under(mCurses, "Key"); - -#ifdef USE_MOUSE - cMouseEvent = rb_define_class_under(mCurses,"MouseEvent",rb_cObject); - rb_undef_method(CLASS_OF(cMouseEvent),"new"); - rb_define_method(cMouseEvent, "eid", curs_mouse_id, 0); - rb_define_method(cMouseEvent, "x", curs_mouse_x, 0); - rb_define_method(cMouseEvent, "y", curs_mouse_y, 0); - rb_define_method(cMouseEvent, "z", curs_mouse_z, 0); - rb_define_method(cMouseEvent, "bstate", curs_mouse_bstate, 0); -#endif /* USE_MOUSE */ - - rb_define_module_function(mCurses, "init_screen", curses_init_screen, 0); - rb_define_module_function(mCurses, "close_screen", curses_close_screen, 0); - rb_define_module_function(mCurses, "closed?", curses_closed, 0); - rb_define_module_function(mCurses, "stdscr", curses_stdscr, 0); - rb_define_module_function(mCurses, "refresh", curses_refresh, 0); - rb_define_module_function(mCurses, "doupdate", curses_doupdate, 0); - rb_define_module_function(mCurses, "clear", curses_clear, 0); - rb_define_module_function(mCurses, "echo", curses_echo, 0); - rb_define_module_function(mCurses, "noecho", curses_noecho, 0); - rb_define_module_function(mCurses, "raw", curses_raw, 0); - rb_define_module_function(mCurses, "noraw", curses_noraw, 0); - rb_define_module_function(mCurses, "cbreak", curses_cbreak, 0); - rb_define_module_function(mCurses, "nocbreak", curses_nocbreak, 0); - rb_define_alias(mCurses, "crmode", "cbreak"); - rb_define_alias(mCurses, "nocrmode", "nocbreak"); - rb_define_module_function(mCurses, "nl", curses_nl, 0); - rb_define_module_function(mCurses, "nonl", curses_nonl, 0); - rb_define_module_function(mCurses, "beep", curses_beep, 0); - rb_define_module_function(mCurses, "flash", curses_flash, 0); - rb_define_module_function(mCurses, "ungetch", curses_ungetch, 1); - rb_define_module_function(mCurses, "setpos", curses_setpos, 2); - rb_define_module_function(mCurses, "standout", curses_standout, 0); - rb_define_module_function(mCurses, "standend", curses_standend, 0); - rb_define_module_function(mCurses, "inch", curses_inch, 0); - rb_define_module_function(mCurses, "addch", curses_addch, 1); - rb_define_module_function(mCurses, "insch", curses_insch, 1); - rb_define_module_function(mCurses, "addstr", curses_addstr, 1); - rb_define_module_function(mCurses, "getch", curses_getch, 0); - rb_define_module_function(mCurses, "getstr", curses_getstr, 0); - rb_define_module_function(mCurses, "delch", curses_delch, 0); - rb_define_module_function(mCurses, "deleteln", curses_deleteln, 0); - rb_define_module_function(mCurses, "keyname", curses_keyname, 1); - rb_define_module_function(mCurses, "lines", curses_lines, 0); - rb_define_module_function(mCurses, "cols", curses_cols, 0); - rb_define_module_function(mCurses, "curs_set", curses_curs_set, 1); - rb_define_module_function(mCurses, "scrl", curses_scrl, 1); - rb_define_module_function(mCurses, "setscrreg", curses_setscrreg, 2); - rb_define_module_function(mCurses, "attroff", curses_attroff, 1); - rb_define_module_function(mCurses, "attron", curses_attron, 1); - rb_define_module_function(mCurses, "attrset", curses_attrset, 1); - rb_define_module_function(mCurses, "bkgdset", curses_bkgdset, 1); - rb_define_module_function(mCurses, "bkgd", curses_bkgd, 1); - rb_define_module_function(mCurses, "resizeterm", curses_resizeterm, 2); - rb_define_module_function(mCurses, "resize", curses_resizeterm, 2); -#ifdef USE_COLOR - rb_define_module_function(mCurses, "start_color", curses_start_color, 0); - rb_define_module_function(mCurses, "init_pair", curses_init_pair, 3); - rb_define_module_function(mCurses, "init_color", curses_init_color, 4); - rb_define_module_function(mCurses, "has_colors?", curses_has_colors, 0); - rb_define_module_function(mCurses, "can_change_color?", - curses_can_change_color, 0); - rb_define_module_function(mCurses, "color_content", curses_color_content, 1); - rb_define_module_function(mCurses, "pair_content", curses_pair_content, 1); - rb_define_module_function(mCurses, "color_pair", curses_color_pair, 1); - rb_define_module_function(mCurses, "pair_number", curses_pair_number, 1); -#endif /* USE_COLOR */ -#ifdef USE_MOUSE - rb_define_module_function(mCurses, "getmouse", curses_getmouse, 0); - rb_define_module_function(mCurses, "ungetmouse", curses_getmouse, 1); - rb_define_module_function(mCurses, "mouseinterval", curses_mouseinterval, 1); - rb_define_module_function(mCurses, "mousemask", curses_mousemask, 1); -#endif /* USE_MOUSE */ - - cWindow = rb_define_class_under(mCurses, "Window", rb_cObject); - rb_define_singleton_method(cWindow, "new", window_s_new, 4); - rb_define_method(cWindow, "subwin", window_subwin, 4); - rb_define_method(cWindow, "close", window_close, 0); - rb_define_method(cWindow, "clear", window_clear, 0); - rb_define_method(cWindow, "refresh", window_refresh, 0); - rb_define_method(cWindow, "noutrefresh", window_noutrefresh, 0); - rb_define_method(cWindow, "box", window_box, -1); - rb_define_method(cWindow, "move", window_move, 2); - rb_define_method(cWindow, "setpos", window_setpos, 2); - rb_define_method(cWindow, "cury", window_cury, 0); - rb_define_method(cWindow, "curx", window_curx, 0); - rb_define_method(cWindow, "maxy", window_maxy, 0); - rb_define_method(cWindow, "maxx", window_maxx, 0); - rb_define_method(cWindow, "begy", window_begy, 0); - rb_define_method(cWindow, "begx", window_begx, 0); - rb_define_method(cWindow, "standout", window_standout, 0); - rb_define_method(cWindow, "standend", window_standend, 0); - rb_define_method(cWindow, "inch", window_inch, 0); - rb_define_method(cWindow, "addch", window_addch, 1); - rb_define_method(cWindow, "insch", window_insch, 1); - rb_define_method(cWindow, "addstr", window_addstr, 1); - rb_define_method(cWindow, "<<", window_addstr2, 1); - rb_define_method(cWindow, "getch", window_getch, 0); - rb_define_method(cWindow, "getstr", window_getstr, 0); - rb_define_method(cWindow, "delch", window_delch, 0); - rb_define_method(cWindow, "deleteln", window_deleteln, 0); - rb_define_method(cWindow, "scroll", window_scroll, 0); - rb_define_method(cWindow, "scrollok", window_scrollok, 1); - rb_define_method(cWindow, "idlok", window_idlok, 1); - rb_define_method(cWindow, "setscrreg", window_setscrreg, 2); - rb_define_method(cWindow, "scrl", window_scrl, 1); - rb_define_method(cWindow, "resize", window_resize, 2); -#ifdef HAVE_KEYPAD - rb_define_method(cWindow, "keypad", window_keypad, 1); - rb_define_method(cWindow, "keypad=", window_keypad, 1); -#endif -#ifdef USE_COLOR - rb_define_method(cWindow, "attroff", window_attroff, 1); - rb_define_method(cWindow, "attron", window_attron, 1); - rb_define_method(cWindow, "attrset", window_attrset, 1); - rb_define_method(cWindow, "bkgdset", window_bkgdset, 1); - rb_define_method(cWindow, "bkgd", window_bkgd, 1); - rb_define_method(cWindow, "getbkgd", window_getbkgd, 0); -#endif /* USE_COLOR */ - - -#define rb_curses_define_const(c) rb_define_const(mCurses,#c,UINT2NUM(c)) - -#ifdef USE_COLOR - rb_curses_define_const(A_ATTRIBUTES); -#ifdef A_NORMAL - rb_curses_define_const(A_NORMAL); -#endif - rb_curses_define_const(A_STANDOUT); - rb_curses_define_const(A_UNDERLINE); - rb_curses_define_const(A_REVERSE); - rb_curses_define_const(A_BLINK); - rb_curses_define_const(A_DIM); - rb_curses_define_const(A_BOLD); - rb_curses_define_const(A_PROTECT); -#ifdef A_INVIS /* for NetBSD */ - rb_curses_define_const(A_INVIS); -#endif - rb_curses_define_const(A_ALTCHARSET); - rb_curses_define_const(A_CHARTEXT); -#ifdef A_HORIZONTAL - rb_curses_define_const(A_HORIZONTAL); -#endif -#ifdef A_LEFT - rb_curses_define_const(A_LEFT); -#endif -#ifdef A_LOW - rb_curses_define_const(A_LOW); -#endif -#ifdef A_RIGHT - rb_curses_define_const(A_RIGHT); -#endif -#ifdef A_TOP - rb_curses_define_const(A_TOP); -#endif -#ifdef A_VERTICAL - rb_curses_define_const(A_VERTICAL); -#endif - rb_curses_define_const(A_COLOR); - -#ifdef COLORS - rb_curses_define_const(COLORS); -#endif - rb_curses_define_const(COLOR_BLACK); - rb_curses_define_const(COLOR_RED); - rb_curses_define_const(COLOR_GREEN); - rb_curses_define_const(COLOR_YELLOW); - rb_curses_define_const(COLOR_BLUE); - rb_curses_define_const(COLOR_MAGENTA); - rb_curses_define_const(COLOR_CYAN); - rb_curses_define_const(COLOR_WHITE); -#endif /* USE_COLOR */ -#ifdef USE_MOUSE -#ifdef BUTTON1_PRESSED - rb_curses_define_const(BUTTON1_PRESSED); -#endif -#ifdef BUTTON1_RELEASED - rb_curses_define_const(BUTTON1_RELEASED); -#endif -#ifdef BUTTON1_CLICKED - rb_curses_define_const(BUTTON1_CLICKED); -#endif -#ifdef BUTTON1_DOUBLE_CLICKED - rb_curses_define_const(BUTTON1_DOUBLE_CLICKED); -#endif -#ifdef BUTTON1_TRIPLE_CLICKED - rb_curses_define_const(BUTTON1_TRIPLE_CLICKED); -#endif -#ifdef BUTTON2_PRESSED - rb_curses_define_const(BUTTON2_PRESSED); -#endif -#ifdef BUTTON2_RELEASED - rb_curses_define_const(BUTTON2_RELEASED); -#endif -#ifdef BUTTON2_CLICKED - rb_curses_define_const(BUTTON2_CLICKED); -#endif -#ifdef BUTTON2_DOUBLE_CLICKED - rb_curses_define_const(BUTTON2_DOUBLE_CLICKED); -#endif -#ifdef BUTTON2_TRIPLE_CLICKED - rb_curses_define_const(BUTTON2_TRIPLE_CLICKED); -#endif -#ifdef BUTTON3_PRESSED - rb_curses_define_const(BUTTON3_PRESSED); -#endif -#ifdef BUTTON3_RELEASED - rb_curses_define_const(BUTTON3_RELEASED); -#endif -#ifdef BUTTON3_CLICKED - rb_curses_define_const(BUTTON3_CLICKED); -#endif -#ifdef BUTTON3_DOUBLE_CLICKED - rb_curses_define_const(BUTTON3_DOUBLE_CLICKED); -#endif -#ifdef BUTTON3_TRIPLE_CLICKED - rb_curses_define_const(BUTTON3_TRIPLE_CLICKED); -#endif -#ifdef BUTTON4_PRESSED - rb_curses_define_const(BUTTON4_PRESSED); -#endif -#ifdef BUTTON4_RELEASED - rb_curses_define_const(BUTTON4_RELEASED); -#endif -#ifdef BUTTON4_CLICKED - rb_curses_define_const(BUTTON4_CLICKED); -#endif -#ifdef BUTTON4_DOUBLE_CLICKED - rb_curses_define_const(BUTTON4_DOUBLE_CLICKED); -#endif -#ifdef BUTTON4_TRIPLE_CLICKED - rb_curses_define_const(BUTTON4_TRIPLE_CLICKED); -#endif -#ifdef BUTTON_SHIFT - rb_curses_define_const(BUTTON_SHIFT); -#endif -#ifdef BUTTON_CTRL - rb_curses_define_const(BUTTON_CTRL); -#endif -#ifdef BUTTON_ALT - rb_curses_define_const(BUTTON_ALT); -#endif -#ifdef ALL_MOUSE_EVENTS - rb_curses_define_const(ALL_MOUSE_EVENTS); -#endif -#ifdef REPORT_MOUSE_POSITION - rb_curses_define_const(REPORT_MOUSE_POSITION); -#endif -#endif /* USE_MOUSE */ - -#if defined(KEY_MOUSE) && defined(USE_MOUSE) - rb_curses_define_const(KEY_MOUSE); - rb_define_const(mKey, "MOUSE", INT2NUM(KEY_MOUSE)); -#endif -#ifdef KEY_MIN - rb_curses_define_const(KEY_MIN); - rb_define_const(mKey, "MIN", INT2NUM(KEY_MIN)); -#endif -#ifdef KEY_BREAK - rb_curses_define_const(KEY_BREAK); - rb_define_const(mKey, "BREAK", INT2NUM(KEY_BREAK)); -#endif -#ifdef KEY_DOWN - rb_curses_define_const(KEY_DOWN); - rb_define_const(mKey, "DOWN", INT2NUM(KEY_DOWN)); -#endif -#ifdef KEY_UP - rb_curses_define_const(KEY_UP); - rb_define_const(mKey, "UP", INT2NUM(KEY_UP)); -#endif -#ifdef KEY_LEFT - rb_curses_define_const(KEY_LEFT); - rb_define_const(mKey, "LEFT", INT2NUM(KEY_LEFT)); -#endif -#ifdef KEY_RIGHT - rb_curses_define_const(KEY_RIGHT); - rb_define_const(mKey, "RIGHT", INT2NUM(KEY_RIGHT)); -#endif -#ifdef KEY_HOME - rb_curses_define_const(KEY_HOME); - rb_define_const(mKey, "HOME", INT2NUM(KEY_HOME)); -#endif -#ifdef KEY_BACKSPACE - rb_curses_define_const(KEY_BACKSPACE); - rb_define_const(mKey, "BACKSPACE", INT2NUM(KEY_BACKSPACE)); -#endif -#ifdef KEY_F - /* KEY_F(n) : 0 <= n <= 63 */ - { - int i; - char c[8]; - for( i=0; i<64; i++ ){ - sprintf(c, "KEY_F%d", i); - rb_define_const(mCurses, c, INT2NUM(KEY_F(i))); - sprintf(c, "F%d", i); - rb_define_const(mKey, c, INT2NUM(KEY_F(i))); - }; - }; -#endif -#ifdef KEY_DL - rb_curses_define_const(KEY_DL); - rb_define_const(mKey, "DL", INT2NUM(KEY_DL)); -#endif -#ifdef KEY_IL - rb_curses_define_const(KEY_IL); - rb_define_const(mKey, "IL", INT2NUM(KEY_IL)); -#endif -#ifdef KEY_DC - rb_curses_define_const(KEY_DC); - rb_define_const(mKey, "DC", INT2NUM(KEY_DC)); -#endif -#ifdef KEY_IC - rb_curses_define_const(KEY_IC); - rb_define_const(mKey, "IC", INT2NUM(KEY_IC)); -#endif -#ifdef KEY_EIC - rb_curses_define_const(KEY_EIC); - rb_define_const(mKey, "EIC", INT2NUM(KEY_EIC)); -#endif -#ifdef KEY_CLEAR - rb_curses_define_const(KEY_CLEAR); - rb_define_const(mKey, "CLEAR", INT2NUM(KEY_CLEAR)); -#endif -#ifdef KEY_EOS - rb_curses_define_const(KEY_EOS); - rb_define_const(mKey, "EOS", INT2NUM(KEY_EOS)); -#endif -#ifdef KEY_EOL - rb_curses_define_const(KEY_EOL); - rb_define_const(mKey, "EOL", INT2NUM(KEY_EOL)); -#endif -#ifdef KEY_SF - rb_curses_define_const(KEY_SF); - rb_define_const(mKey, "SF", INT2NUM(KEY_SF)); -#endif -#ifdef KEY_SR - rb_curses_define_const(KEY_SR); - rb_define_const(mKey, "SR", INT2NUM(KEY_SR)); -#endif -#ifdef KEY_NPAGE - rb_curses_define_const(KEY_NPAGE); - rb_define_const(mKey, "NPAGE", INT2NUM(KEY_NPAGE)); -#endif -#ifdef KEY_PPAGE - rb_curses_define_const(KEY_PPAGE); - rb_define_const(mKey, "PPAGE", INT2NUM(KEY_PPAGE)); -#endif -#ifdef KEY_STAB - rb_curses_define_const(KEY_STAB); - rb_define_const(mKey, "STAB", INT2NUM(KEY_STAB)); -#endif -#ifdef KEY_CTAB - rb_curses_define_const(KEY_CTAB); - rb_define_const(mKey, "CTAB", INT2NUM(KEY_CTAB)); -#endif -#ifdef KEY_CATAB - rb_curses_define_const(KEY_CATAB); - rb_define_const(mKey, "CATAB", INT2NUM(KEY_CATAB)); -#endif -#ifdef KEY_ENTER - rb_curses_define_const(KEY_ENTER); - rb_define_const(mKey, "ENTER", INT2NUM(KEY_ENTER)); -#endif -#ifdef KEY_SRESET - rb_curses_define_const(KEY_SRESET); - rb_define_const(mKey, "SRESET", INT2NUM(KEY_SRESET)); -#endif -#ifdef KEY_RESET - rb_curses_define_const(KEY_RESET); - rb_define_const(mKey, "RESET", INT2NUM(KEY_RESET)); -#endif -#ifdef KEY_PRINT - rb_curses_define_const(KEY_PRINT); - rb_define_const(mKey, "PRINT", INT2NUM(KEY_PRINT)); -#endif -#ifdef KEY_LL - rb_curses_define_const(KEY_LL); - rb_define_const(mKey, "LL", INT2NUM(KEY_LL)); -#endif -#ifdef KEY_A1 - rb_curses_define_const(KEY_A1); - rb_define_const(mKey, "A1", INT2NUM(KEY_A1)); -#endif -#ifdef KEY_A3 - rb_curses_define_const(KEY_A3); - rb_define_const(mKey, "A3", INT2NUM(KEY_A3)); -#endif -#ifdef KEY_B2 - rb_curses_define_const(KEY_B2); - rb_define_const(mKey, "B2", INT2NUM(KEY_B2)); -#endif -#ifdef KEY_C1 - rb_curses_define_const(KEY_C1); - rb_define_const(mKey, "C1", INT2NUM(KEY_C1)); -#endif -#ifdef KEY_C3 - rb_curses_define_const(KEY_C3); - rb_define_const(mKey, "C3", INT2NUM(KEY_C3)); -#endif -#ifdef KEY_BTAB - rb_curses_define_const(KEY_BTAB); - rb_define_const(mKey, "BTAB", INT2NUM(KEY_BTAB)); -#endif -#ifdef KEY_BEG - rb_curses_define_const(KEY_BEG); - rb_define_const(mKey, "BEG", INT2NUM(KEY_BEG)); -#endif -#ifdef KEY_CANCEL - rb_curses_define_const(KEY_CANCEL); - rb_define_const(mKey, "CANCEL", INT2NUM(KEY_CANCEL)); -#endif -#ifdef KEY_CLOSE - rb_curses_define_const(KEY_CLOSE); - rb_define_const(mKey, "CLOSE", INT2NUM(KEY_CLOSE)); -#endif -#ifdef KEY_COMMAND - rb_curses_define_const(KEY_COMMAND); - rb_define_const(mKey, "COMMAND", INT2NUM(KEY_COMMAND)); -#endif -#ifdef KEY_COPY - rb_curses_define_const(KEY_COPY); - rb_define_const(mKey, "COPY", INT2NUM(KEY_COPY)); -#endif -#ifdef KEY_CREATE - rb_curses_define_const(KEY_CREATE); - rb_define_const(mKey, "CREATE", INT2NUM(KEY_CREATE)); -#endif -#ifdef KEY_END - rb_curses_define_const(KEY_END); - rb_define_const(mKey, "END", INT2NUM(KEY_END)); -#endif -#ifdef KEY_EXIT - rb_curses_define_const(KEY_EXIT); - rb_define_const(mKey, "EXIT", INT2NUM(KEY_EXIT)); -#endif -#ifdef KEY_FIND - rb_curses_define_const(KEY_FIND); - rb_define_const(mKey, "FIND", INT2NUM(KEY_FIND)); -#endif -#ifdef KEY_HELP - rb_curses_define_const(KEY_HELP); - rb_define_const(mKey, "HELP", INT2NUM(KEY_HELP)); -#endif -#ifdef KEY_MARK - rb_curses_define_const(KEY_MARK); - rb_define_const(mKey, "MARK", INT2NUM(KEY_MARK)); -#endif -#ifdef KEY_MESSAGE - rb_curses_define_const(KEY_MESSAGE); - rb_define_const(mKey, "MESSAGE", INT2NUM(KEY_MESSAGE)); -#endif -#ifdef KEY_MOVE - rb_curses_define_const(KEY_MOVE); - rb_define_const(mKey, "MOVE", INT2NUM(KEY_MOVE)); -#endif -#ifdef KEY_NEXT - rb_curses_define_const(KEY_NEXT); - rb_define_const(mKey, "NEXT", INT2NUM(KEY_NEXT)); -#endif -#ifdef KEY_OPEN - rb_curses_define_const(KEY_OPEN); - rb_define_const(mKey, "OPEN", INT2NUM(KEY_OPEN)); -#endif -#ifdef KEY_OPTIONS - rb_curses_define_const(KEY_OPTIONS); - rb_define_const(mKey, "OPTIONS", INT2NUM(KEY_OPTIONS)); -#endif -#ifdef KEY_PREVIOUS - rb_curses_define_const(KEY_PREVIOUS); - rb_define_const(mKey, "PREVIOUS", INT2NUM(KEY_PREVIOUS)); -#endif -#ifdef KEY_REDO - rb_curses_define_const(KEY_REDO); - rb_define_const(mKey, "REDO", INT2NUM(KEY_REDO)); -#endif -#ifdef KEY_REFERENCE - rb_curses_define_const(KEY_REFERENCE); - rb_define_const(mKey, "REFERENCE", INT2NUM(KEY_REFERENCE)); -#endif -#ifdef KEY_REFRESH - rb_curses_define_const(KEY_REFRESH); - rb_define_const(mKey, "REFRESH", INT2NUM(KEY_REFRESH)); -#endif -#ifdef KEY_REPLACE - rb_curses_define_const(KEY_REPLACE); - rb_define_const(mKey, "REPLACE", INT2NUM(KEY_REPLACE)); -#endif -#ifdef KEY_RESTART - rb_curses_define_const(KEY_RESTART); - rb_define_const(mKey, "RESTART", INT2NUM(KEY_RESTART)); -#endif -#ifdef KEY_RESUME - rb_curses_define_const(KEY_RESUME); - rb_define_const(mKey, "RESUME", INT2NUM(KEY_RESUME)); -#endif -#ifdef KEY_SAVE - rb_curses_define_const(KEY_SAVE); - rb_define_const(mKey, "SAVE", INT2NUM(KEY_SAVE)); -#endif -#ifdef KEY_SBEG - rb_curses_define_const(KEY_SBEG); - rb_define_const(mKey, "SBEG", INT2NUM(KEY_SBEG)); -#endif -#ifdef KEY_SCANCEL - rb_curses_define_const(KEY_SCANCEL); - rb_define_const(mKey, "SCANCEL", INT2NUM(KEY_SCANCEL)); -#endif -#ifdef KEY_SCOMMAND - rb_curses_define_const(KEY_SCOMMAND); - rb_define_const(mKey, "SCOMMAND", INT2NUM(KEY_SCOMMAND)); -#endif -#ifdef KEY_SCOPY - rb_curses_define_const(KEY_SCOPY); - rb_define_const(mKey, "SCOPY", INT2NUM(KEY_SCOPY)); -#endif -#ifdef KEY_SCREATE - rb_curses_define_const(KEY_SCREATE); - rb_define_const(mKey, "SCREATE", INT2NUM(KEY_SCREATE)); -#endif -#ifdef KEY_SDC - rb_curses_define_const(KEY_SDC); - rb_define_const(mKey, "SDC", INT2NUM(KEY_SDC)); -#endif -#ifdef KEY_SDL - rb_curses_define_const(KEY_SDL); - rb_define_const(mKey, "SDL", INT2NUM(KEY_SDL)); -#endif -#ifdef KEY_SELECT - rb_curses_define_const(KEY_SELECT); - rb_define_const(mKey, "SELECT", INT2NUM(KEY_SELECT)); -#endif -#ifdef KEY_SEND - rb_curses_define_const(KEY_SEND); - rb_define_const(mKey, "SEND", INT2NUM(KEY_SEND)); -#endif -#ifdef KEY_SEOL - rb_curses_define_const(KEY_SEOL); - rb_define_const(mKey, "SEOL", INT2NUM(KEY_SEOL)); -#endif -#ifdef KEY_SEXIT - rb_curses_define_const(KEY_SEXIT); - rb_define_const(mKey, "SEXIT", INT2NUM(KEY_SEXIT)); -#endif -#ifdef KEY_SFIND - rb_curses_define_const(KEY_SFIND); - rb_define_const(mKey, "SFIND", INT2NUM(KEY_SFIND)); -#endif -#ifdef KEY_SHELP - rb_curses_define_const(KEY_SHELP); - rb_define_const(mKey, "SHELP", INT2NUM(KEY_SHELP)); -#endif -#ifdef KEY_SHOME - rb_curses_define_const(KEY_SHOME); - rb_define_const(mKey, "SHOME", INT2NUM(KEY_SHOME)); -#endif -#ifdef KEY_SIC - rb_curses_define_const(KEY_SIC); - rb_define_const(mKey, "SIC", INT2NUM(KEY_SIC)); -#endif -#ifdef KEY_SLEFT - rb_curses_define_const(KEY_SLEFT); - rb_define_const(mKey, "SLEFT", INT2NUM(KEY_SLEFT)); -#endif -#ifdef KEY_SMESSAGE - rb_curses_define_const(KEY_SMESSAGE); - rb_define_const(mKey, "SMESSAGE", INT2NUM(KEY_SMESSAGE)); -#endif -#ifdef KEY_SMOVE - rb_curses_define_const(KEY_SMOVE); - rb_define_const(mKey, "SMOVE", INT2NUM(KEY_SMOVE)); -#endif -#ifdef KEY_SNEXT - rb_curses_define_const(KEY_SNEXT); - rb_define_const(mKey, "SNEXT", INT2NUM(KEY_SNEXT)); -#endif -#ifdef KEY_SOPTIONS - rb_curses_define_const(KEY_SOPTIONS); - rb_define_const(mKey, "SOPTIONS", INT2NUM(KEY_SOPTIONS)); -#endif -#ifdef KEY_SPREVIOUS - rb_curses_define_const(KEY_SPREVIOUS); - rb_define_const(mKey, "SPREVIOUS", INT2NUM(KEY_SPREVIOUS)); -#endif -#ifdef KEY_SPRINT - rb_curses_define_const(KEY_SPRINT); - rb_define_const(mKey, "SPRINT", INT2NUM(KEY_SPRINT)); -#endif -#ifdef KEY_SREDO - rb_curses_define_const(KEY_SREDO); - rb_define_const(mKey, "SREDO", INT2NUM(KEY_SREDO)); -#endif -#ifdef KEY_SREPLACE - rb_curses_define_const(KEY_SREPLACE); - rb_define_const(mKey, "SREPLACE", INT2NUM(KEY_SREPLACE)); -#endif -#ifdef KEY_SRIGHT - rb_curses_define_const(KEY_SRIGHT); - rb_define_const(mKey, "SRIGHT", INT2NUM(KEY_SRIGHT)); -#endif -#ifdef KEY_SRSUME - rb_curses_define_const(KEY_SRSUME); - rb_define_const(mKey, "SRSUME", INT2NUM(KEY_SRSUME)); -#endif -#ifdef KEY_SSAVE - rb_curses_define_const(KEY_SSAVE); - rb_define_const(mKey, "SSAVE", INT2NUM(KEY_SSAVE)); -#endif -#ifdef KEY_SSUSPEND - rb_curses_define_const(KEY_SSUSPEND); - rb_define_const(mKey, "SSUSPEND", INT2NUM(KEY_SSUSPEND)); -#endif -#ifdef KEY_SUNDO - rb_curses_define_const(KEY_SUNDO); - rb_define_const(mKey, "SUNDO", INT2NUM(KEY_SUNDO)); -#endif -#ifdef KEY_SUSPEND - rb_curses_define_const(KEY_SUSPEND); - rb_define_const(mKey, "SUSPEND", INT2NUM(KEY_SUSPEND)); -#endif -#ifdef KEY_UNDO - rb_curses_define_const(KEY_UNDO); - rb_define_const(mKey, "UNDO", INT2NUM(KEY_UNDO)); -#endif -#ifdef KEY_RESIZE - rb_curses_define_const(KEY_RESIZE); - rb_define_const(mKey, "RESIZE", INT2NUM(KEY_RESIZE)); -#endif -#ifdef KEY_MAX - rb_curses_define_const(KEY_MAX); - rb_define_const(mKey, "MAX", INT2NUM(KEY_MAX)); -#endif - { - int c; - char name[] = "KEY_CTRL_x"; - for( c = 'A'; c <= 'Z'; c++ ){ - sprintf(name, "KEY_CTRL_%c", c); - rb_define_const(mCurses, name, INT2FIX(c - 'A' + 1)); - }; - } -#undef rb_curses_define_const - - rb_set_end_proc(curses_finalize, 0); -} diff --git a/ext/curses/depend b/ext/curses/depend deleted file mode 100644 index ecb79e512d..0000000000 --- a/ext/curses/depend +++ /dev/null @@ -1 +0,0 @@ -curses.o: curses.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/curses/extconf.rb b/ext/curses/extconf.rb deleted file mode 100644 index 94443b45e6..0000000000 --- a/ext/curses/extconf.rb +++ /dev/null @@ -1,27 +0,0 @@ -require 'mkmf' - -dir_config('curses') -dir_config('ncurses') -dir_config('termcap') - -make=false -have_library("mytinfo", "tgetent") if /bow/ =~ RUBY_PLATFORM -if have_header("ncurses.h") and have_library("ncurses", "initscr") - make=true -elsif have_header("ncurses/curses.h") and have_library("ncurses", "initscr") - make=true -elsif have_header("curses_colr/curses.h") and have_library("cur_colr", "initscr") - make=true -else - have_library("termcap", "tgetent") - if have_header("curses.h") and have_library("curses", "initscr") - make=true - end -end - -if make - for f in %w(isendwin ungetch beep getnstr wgetnstr doupdate flash deleteln wdeleteln keypad keyname init_color wresize resizeterm) - have_func(f) - end - create_makefile("curses") -end diff --git a/ext/curses/hello.rb b/ext/curses/hello.rb deleted file mode 100644 index 7f57d801a3..0000000000 --- a/ext/curses/hello.rb +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/local/bin/ruby - -require "curses" -include Curses - -def show_message(message) - width = message.length + 6 - win = Window.new(5, width, - (lines - 5) / 2, (cols - width) / 2) - win.box(?|, ?-) - win.setpos(2, 3) - win.addstr(message) - win.refresh - win.getch - win.close -end - -init_screen -begin - crmode -# show_message("Hit any key") - setpos((lines - 5) / 2, (cols - 10) / 2) - addstr("Hit any key") - refresh - getch - show_message("Hello, World!") - refresh -ensure - close_screen -end diff --git a/ext/curses/mouse.rb b/ext/curses/mouse.rb deleted file mode 100644 index c42bc31f33..0000000000 --- a/ext/curses/mouse.rb +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/local/bin/ruby - -require "curses" -include Curses - -def show_message(*msgs) - message = msgs.join - width = message.length + 6 - win = Window.new(5, width, - (lines - 5) / 2, (cols - width) / 2) - win.keypad = true - win.attron(color_pair(COLOR_RED)){ - win.box(?|, ?-, ?+) - } - win.setpos(2, 3) - win.addstr(message) - win.refresh - win.getch - win.close -end - -init_screen -start_color -init_pair(COLOR_BLUE,COLOR_BLUE,COLOR_WHITE) -init_pair(COLOR_RED,COLOR_RED,COLOR_WHITE) -crmode -noecho -stdscr.keypad(true) - -begin - mousemask(BUTTON1_CLICKED|BUTTON2_CLICKED|BUTTON3_CLICKED|BUTTON4_CLICKED) - setpos((lines - 5) / 2, (cols - 10) / 2) - attron(color_pair(COLOR_BLUE)|A_BOLD){ - addstr("click") - } - refresh - while( true ) - c = getch - case c - when KEY_MOUSE - m = getmouse - if( m ) - show_message("getch = #{c.inspect}, ", - "mouse event = #{'0x%x' % m.bstate}, ", - "axis = (#{m.x},#{m.y},#{m.z})") - end - break - end - end - refresh -ensure - close_screen -end diff --git a/ext/curses/rain.rb b/ext/curses/rain.rb deleted file mode 100644 index 36f0f84de2..0000000000 --- a/ext/curses/rain.rb +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/local/bin/ruby -# rain for a curses test - -require "curses" -include Curses - -def onsig(sig) - close_screen - exit sig -end - -def ranf - rand(32767).to_f / 32767 -end - -# main # -for i in 1 .. 15 # SIGHUP .. SIGTERM - if trap(i, "SIG_IGN") != 0 then # 0 for SIG_IGN - trap(i) {|sig| onsig(sig) } - end -end - -init_screen -nl -noecho -srand - -xpos = {} -ypos = {} -r = lines - 4 -c = cols - 4 -for i in 0 .. 4 - xpos[i] = (c * ranf).to_i + 2 - ypos[i] = (r * ranf).to_i + 2 -end - -i = 0 -while TRUE - x = (c * ranf).to_i + 2 - y = (r * ranf).to_i + 2 - - - setpos(y, x); addstr(".") - - setpos(ypos[i], xpos[i]); addstr("o") - - i = if i == 0 then 4 else i - 1 end - setpos(ypos[i], xpos[i]); addstr("O") - - i = if i == 0 then 4 else i - 1 end - setpos(ypos[i] - 1, xpos[i]); addstr("-") - setpos(ypos[i], xpos[i] - 1); addstr("|.|") - setpos(ypos[i] + 1, xpos[i]); addstr("-") - - i = if i == 0 then 4 else i - 1 end - setpos(ypos[i] - 2, xpos[i]); addstr("-") - setpos(ypos[i] - 1, xpos[i] - 1); addstr("/ \\") - setpos(ypos[i], xpos[i] - 2); addstr("| O |") - setpos(ypos[i] + 1, xpos[i] - 1); addstr("\\ /") - setpos(ypos[i] + 2, xpos[i]); addstr("-") - - i = if i == 0 then 4 else i - 1 end - setpos(ypos[i] - 2, xpos[i]); addstr(" ") - setpos(ypos[i] - 1, xpos[i] - 1); addstr(" ") - setpos(ypos[i], xpos[i] - 2); addstr(" ") - setpos(ypos[i] + 1, xpos[i] - 1); addstr(" ") - setpos(ypos[i] + 2, xpos[i]); addstr(" ") - - - xpos[i] = x - ypos[i] = y - refresh - sleep(0.5) -end - -# end of main diff --git a/ext/curses/view.rb b/ext/curses/view.rb deleted file mode 100644 index 5ba1a8413c..0000000000 --- a/ext/curses/view.rb +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/local/bin/ruby - -require "curses" -include Curses - -# -# main -# - -if ARGV.size != 1 then - printf("usage: view file\n"); - exit -end -begin - fp = open(ARGV[0], "r") -rescue - raise "cannot open file: #{ARGV[1]}" -end - -# signal(SIGINT, finish) - -init_screen -#keypad(stdscr, TRUE) -nonl -cbreak -noecho -#scrollok(stdscr, TRUE) - -# slurp the file -data_lines = [] -fp.each_line { |l| - data_lines.push(l) -} -fp.close - - -lptr = 0 -while TRUE - i = 0 - while i < lines - setpos(i, 0) - #clrtoeol - addstr(data_lines[lptr + i]) #if data_lines[lptr + i] - i += 1 - end - refresh - - explicit = FALSE - n = 0 - while TRUE - c = getch.chr - if c =~ "[0-9]" then - n = 10 * n + c.to_i - else - break - end - end - - n = 1 if !explicit && n == 0 - - case c - when "n" #when KEY_DOWN - i = 0 - while i < n - if lptr + lines < data_lines.size then - lptr += 1 - else - break - end - i += 1 - end - #wscrl(i) - - when "p" #when KEY_UP - i = 0 - while i < n - if lptr > 0 then - lptr -= 1 - else - break - end - i += 1 - end - #wscrl(-i) - - when "q" - break - end - -end -close_screen diff --git a/ext/curses/view2.rb b/ext/curses/view2.rb deleted file mode 100644 index f953cdf7f5..0000000000 --- a/ext/curses/view2.rb +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/local/bin/ruby - -require "curses" - -if ARGV.size != 1 then - printf("usage: view file\n"); - exit -end -begin - fp = open(ARGV[0], "r") -rescue - raise "cannot open file: #{ARGV[1]}" -end - -# signal(SIGINT, finish) - -Curses.init_screen -Curses.nonl -Curses.cbreak -Curses.noecho - -$screen = Curses.stdscr - -$screen.scrollok(true) -#$screen.keypad(true) - -# slurp the file -$data_lines = [] -fp.each_line { |l| - $data_lines.push(l.chop) -} -fp.close - -$top = 0 -$data_lines[0..$screen.maxy-1].each_with_index{|line, idx| - $screen.setpos(idx, 0) - $screen.addstr(line) -} -$screen.setpos(0,0) -$screen.refresh - -def scroll_up - if( $top > 0 ) - $screen.scrl(-1) - $top -= 1 - str = $data_lines[$top] - if( str ) - $screen.setpos(0, 0) - $screen.addstr(str) - end - return true - else - return false - end -end - -def scroll_down - if( $top + $screen.maxy < $data_lines.length ) - $screen.scrl(1) - $top += 1 - str = $data_lines[$top + $screen.maxy - 1] - if( str ) - $screen.setpos($screen.maxy - 1, 0) - $screen.addstr(str) - end - return true - else - return false - end -end - -while true - result = true - c = Curses.getch - case c - when Curses::KEY_DOWN, Curses::KEY_CTRL_N - result = scroll_down - when Curses::KEY_UP, Curses::KEY_CTRL_P - result = scroll_up - when Curses::KEY_NPAGE, ? # white space - for i in 0..($screen.maxy - 2) - if( ! scroll_down ) - if( i == 0 ) - result = false - end - break - end - end - when Curses::KEY_PPAGE - for i in 0..($screen.maxy - 2) - if( ! scroll_up ) - if( i == 0 ) - result = false - end - break - end - end - when Curses::KEY_LEFT, Curses::KEY_CTRL_T - while( scroll_up ) - end - when Curses::KEY_RIGHT, Curses::KEY_CTRL_B - while( scroll_down ) - end - when ?q - break - else - $screen.setpos(0,0) - $screen.addstr("[unknown key `#{Curses.keyname(c)}'=#{c}] ") - end - if( !result ) - Curses.beep - end - $screen.setpos(0,0) -end -Curses.close_screen diff --git a/ext/dbm/.cvsignore b/ext/dbm/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/dbm/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/dbm/MANIFEST b/ext/dbm/MANIFEST deleted file mode 100644 index 8beec6783d..0000000000 --- a/ext/dbm/MANIFEST +++ /dev/null @@ -1,4 +0,0 @@ -MANIFEST -dbm.c -depend -extconf.rb diff --git a/ext/dbm/dbm.c b/ext/dbm/dbm.c deleted file mode 100644 index f81f7efcb1..0000000000 --- a/ext/dbm/dbm.c +++ /dev/null @@ -1,764 +0,0 @@ -/************************************************ - - dbm.c - - - $Author$ - $Date$ - created at: Mon Jan 24 15:59:52 JST 1994 - - Copyright (C) 1995-2001 Yukihiro Matsumoto - -************************************************/ - -#include "ruby.h" - -#ifdef HAVE_CDEFS_H -# include -#endif -#ifdef HAVE_SYS_CDEFS_H -# include -#endif -#include DBM_HDR -#include -#include - -static VALUE rb_cDBM, rb_eDBMError; - -struct dbmdata { - int di_size; - DBM *di_dbm; -}; - -static void -closed_dbm() -{ - rb_raise(rb_eDBMError, "closed DBM file"); -} - -#define GetDBM(obj, dbmp) {\ - Data_Get_Struct(obj, struct dbmdata, dbmp);\ - if (dbmp == 0) closed_dbm();\ - if (dbmp->di_dbm == 0) closed_dbm();\ -} - -static void -free_dbm(dbmp) - struct dbmdata *dbmp; -{ - if (dbmp) { - if (dbmp->di_dbm) dbm_close(dbmp->di_dbm); - free(dbmp); - } -} - -static VALUE -fdbm_close(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - - GetDBM(obj, dbmp); - dbm_close(dbmp->di_dbm); - dbmp->di_dbm = 0; - - return Qnil; -} - -static VALUE -fdbm_s_new(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0); - rb_obj_call_init(obj, argc, argv); - return obj; -} - -static VALUE -fdbm_initialize(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE file, vmode; - DBM *dbm; - struct dbmdata *dbmp; - int mode; - - if (rb_scan_args(argc, argv, "11", &file, &vmode) == 1) { - mode = 0666; /* default value */ - } - else if (NIL_P(vmode)) { - mode = -1; /* return nil if DB not exist */ - } - else { - mode = NUM2INT(vmode); - } - SafeStringValue(file); - - dbm = 0; - if (mode >= 0) { - dbm = dbm_open(RSTRING(file)->ptr, O_RDWR|O_CREAT, mode); - } - if (!dbm) { - dbm = dbm_open(RSTRING(file)->ptr, O_RDWR, 0); - } - if (!dbm) { - dbm = dbm_open(RSTRING(file)->ptr, O_RDONLY, 0); - } - - if (!dbm) { - if (mode == -1) return Qnil; - rb_sys_fail(RSTRING(file)->ptr); - } - - dbmp = ALLOC(struct dbmdata); - DATA_PTR(obj) = dbmp; - dbmp->di_dbm = dbm; - dbmp->di_size = -1; - - return obj; -} - -static VALUE -fdbm_s_open(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0); - - if (NIL_P(fdbm_initialize(argc, argv, obj))) { - return Qnil; - } - - if (rb_block_given_p()) { - return rb_ensure(rb_yield, obj, fdbm_close, obj); - } - - return obj; -} - -static VALUE -fdbm_fetch(obj, keystr, ifnone) - VALUE obj, keystr, ifnone; -{ - datum key, value; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(keystr); - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - value = dbm_fetch(dbm, key); - if (value.dptr == 0) { - if (ifnone == Qnil && rb_block_given_p()) - return rb_yield(rb_tainted_str_new(key.dptr, key.dsize)); - return ifnone; - } - return rb_tainted_str_new(value.dptr, value.dsize); -} - -static VALUE -fdbm_aref(obj, keystr) - VALUE obj, keystr; -{ - return fdbm_fetch(obj, keystr, Qnil); -} - -static VALUE -fdbm_fetch_m(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE keystr, valstr, ifnone; - - rb_scan_args(argc, argv, "11", &keystr, &ifnone); - valstr = fdbm_fetch(obj, keystr, ifnone); - if (argc == 1 && !rb_block_given_p() && NIL_P(valstr)) - rb_raise(rb_eIndexError, "key not found"); - - return valstr; -} - -static VALUE -fdbm_index(obj, valstr) - VALUE obj, valstr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(valstr); - val.dptr = RSTRING(valstr)->ptr; - val.dsize = RSTRING(valstr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - if (val.dsize == RSTRING(valstr)->len && - memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0) { - return rb_tainted_str_new(key.dptr, key.dsize); - } - } - return Qnil; -} - -static VALUE -fdbm_indexes(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE new; - int i; - - new = rb_ary_new2(argc); - for (i=0; i 0) { - rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc); - } - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - VALUE assoc; - val = dbm_fetch(dbm, key); - assoc = rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize), - rb_tainted_str_new(val.dptr, val.dsize)); - if (RTEST(rb_yield(assoc))) - rb_ary_push(new, assoc); - } - } - else { - for (i=0; iptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - value = dbm_fetch(dbm, key); - if (value.dptr == 0) { - if (rb_block_given_p()) return rb_yield(keystr); - return Qnil; - } - - /* need to save value before dbm_delete() */ - valstr = rb_tainted_str_new(value.dptr, value.dsize); - - if (dbm_delete(dbm, key)) { - dbmp->di_size = -1; - rb_raise(rb_eDBMError, "dbm_delete failed"); - } - else if (dbmp->di_size >= 0) { - dbmp->di_size--; - } - return valstr; -} - -static VALUE -fdbm_shift(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE keystr, valstr; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - dbmp->di_size = -1; - - key = dbm_firstkey(dbm); - if (!key.dptr) return Qnil; - val = dbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - dbm_delete(dbm, key); - - return rb_assoc_new(keystr, valstr); -} - -static VALUE -fdbm_delete_if(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE keystr, valstr; - VALUE ret, ary = rb_ary_new(); - int i, status = 0, n; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - n = dbmp->di_size; - dbmp->di_size = -1; - - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - ret = rb_protect(rb_yield, rb_assoc_new(rb_str_dup(keystr), valstr), &status); - if (status != 0) break; - if (RTEST(ret)) rb_ary_push(ary, keystr); - } - - for (i = 0; i < RARRAY(ary)->len; i++) { - keystr = RARRAY(ary)->ptr[i]; - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - if (dbm_delete(dbm, key)) { - rb_raise(rb_eDBMError, "dbm_delete failed"); - } - } - if (status) rb_jump_tag(status); - if (n > 0) dbmp->di_size = n - RARRAY(ary)->len; - - return obj; -} - -static VALUE -fdbm_clear(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - dbmp->di_size = -1; - while (key = dbm_firstkey(dbm), key.dptr) { - if (dbm_delete(dbm, key)) { - rb_raise(rb_eDBMError, "dbm_delete failed"); - } - } - dbmp->di_size = 0; - - return obj; -} - -static VALUE -fdbm_invert(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE keystr, valstr; - VALUE hash = rb_hash_new(); - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - rb_hash_aset(hash, valstr, keystr); - } - return hash; -} - -static VALUE -each_pair(obj) - VALUE obj; -{ - return rb_funcall(obj, rb_intern("each_pair"), 0, 0); -} - -static VALUE fdbm_store _((VALUE,VALUE,VALUE)); - -static VALUE -update_i(pair, dbm) - VALUE pair, dbm; -{ - Check_Type(pair, T_ARRAY); - if (RARRAY(pair)->len < 2) { - rb_raise(rb_eArgError, "pair must be [key, value]"); - } - fdbm_store(dbm, RARRAY(pair)->ptr[0], RARRAY(pair)->ptr[1]); - return Qnil; -} - -static VALUE -fdbm_update(obj, other) - VALUE obj, other; -{ - rb_iterate(each_pair, other, update_i, obj); - return obj; -} - -static VALUE -fdbm_replace(obj, other) - VALUE obj, other; -{ - fdbm_clear(obj); - rb_iterate(each_pair, other, update_i, obj); - return obj; -} - -static VALUE -fdbm_store(obj, keystr, valstr) - VALUE obj, keystr, valstr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - rb_secure(4); - keystr = rb_obj_as_string(keystr); - - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - valstr = rb_obj_as_string(valstr); - val.dptr = RSTRING(valstr)->ptr; - val.dsize = RSTRING(valstr)->len; - - GetDBM(obj, dbmp); - dbmp->di_size = -1; - dbm = dbmp->di_dbm; - if (dbm_store(dbm, key, val, DBM_REPLACE)) { -#ifdef HAVE_DBM_CLEARERR - dbm_clearerr(dbm); -#endif - if (errno == EPERM) rb_sys_fail(0); - rb_raise(rb_eDBMError, "dbm_store failed"); - } - - return valstr; -} - -static VALUE -fdbm_length(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - int i = 0; - - GetDBM(obj, dbmp); - if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size); - dbm = dbmp->di_dbm; - - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - i++; - } - dbmp->di_size = i; - - return INT2FIX(i); -} - -static VALUE -fdbm_empty_p(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - int i = 0; - - GetDBM(obj, dbmp); - if (dbmp->di_size < 0) { - dbm = dbmp->di_dbm; - - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - i++; - } - } - else { - i = dbmp->di_size; - } - if (i == 0) return Qtrue; - return Qfalse; -} - -static VALUE -fdbm_each_value(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - rb_yield(rb_tainted_str_new(val.dptr, val.dsize)); - } - return obj; -} - -static VALUE -fdbm_each_key(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - rb_yield(rb_tainted_str_new(key.dptr, key.dsize)); - } - return obj; -} - -static VALUE -fdbm_each_pair(obj) - VALUE obj; -{ - datum key, val; - DBM *dbm; - struct dbmdata *dbmp; - VALUE keystr, valstr; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - rb_yield(rb_assoc_new(keystr, valstr)); - } - - return obj; -} - -static VALUE -fdbm_keys(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - VALUE ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - rb_ary_push(ary, rb_tainted_str_new(key.dptr, key.dsize)); - } - - return ary; -} - -static VALUE -fdbm_values(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - rb_ary_push(ary, rb_tainted_str_new(val.dptr, val.dsize)); - } - - return ary; -} - -static VALUE -fdbm_has_key(obj, keystr) - VALUE obj, keystr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(keystr); - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - val = dbm_fetch(dbm, key); - if (val.dptr) return Qtrue; - return Qfalse; -} - -static VALUE -fdbm_has_value(obj, valstr) - VALUE obj, valstr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(valstr); - val.dptr = RSTRING(valstr)->ptr; - val.dsize = RSTRING(valstr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - if (val.dsize == RSTRING(valstr)->len && - memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0) - return Qtrue; - } - return Qfalse; -} - -static VALUE -fdbm_to_a(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - rb_ary_push(ary, rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize), - rb_tainted_str_new(val.dptr, val.dsize))); - } - - return ary; -} - -static VALUE -fdbm_to_hash(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE hash; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - hash = rb_hash_new(); - for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) { - val = dbm_fetch(dbm, key); - rb_hash_aset(hash, rb_tainted_str_new(key.dptr, key.dsize), - rb_tainted_str_new(val.dptr, val.dsize)); - } - - return hash; -} - -static VALUE -fdbm_reject(obj) - VALUE obj; -{ - return rb_hash_delete_if(fdbm_to_hash(obj)); -} - -void -Init_dbm() -{ - rb_cDBM = rb_define_class("DBM", rb_cObject); - rb_eDBMError = rb_define_class("DBMError", rb_eStandardError); - rb_include_module(rb_cDBM, rb_mEnumerable); - - rb_define_singleton_method(rb_cDBM, "new", fdbm_s_new, -1); - rb_define_singleton_method(rb_cDBM, "open", fdbm_s_open, -1); - - rb_define_method(rb_cDBM, "initialize", fdbm_initialize, -1); - rb_define_method(rb_cDBM, "close", fdbm_close, 0); - rb_define_method(rb_cDBM, "[]", fdbm_aref, 1); - rb_define_method(rb_cDBM, "fetch", fdbm_fetch_m, -1); - rb_define_method(rb_cDBM, "[]=", fdbm_store, 2); - rb_define_method(rb_cDBM, "store", fdbm_store, 2); - rb_define_method(rb_cDBM, "index", fdbm_index, 1); - rb_define_method(rb_cDBM, "indexes", fdbm_indexes, -1); - rb_define_method(rb_cDBM, "indices", fdbm_indexes, -1); - rb_define_method(rb_cDBM, "select", fdbm_select, -1); - rb_define_method(rb_cDBM, "length", fdbm_length, 0); - rb_define_method(rb_cDBM, "size", fdbm_length, 0); - rb_define_method(rb_cDBM, "empty?", fdbm_empty_p, 0); - rb_define_method(rb_cDBM, "each", fdbm_each_pair, 0); - rb_define_method(rb_cDBM, "each_value", fdbm_each_value, 0); - rb_define_method(rb_cDBM, "each_key", fdbm_each_key, 0); - rb_define_method(rb_cDBM, "each_pair", fdbm_each_pair, 0); - rb_define_method(rb_cDBM, "keys", fdbm_keys, 0); - rb_define_method(rb_cDBM, "values", fdbm_values, 0); - rb_define_method(rb_cDBM, "shift", fdbm_shift, 0); - rb_define_method(rb_cDBM, "delete", fdbm_delete, 1); - rb_define_method(rb_cDBM, "delete_if", fdbm_delete_if, 0); - rb_define_method(rb_cDBM, "reject!", fdbm_delete_if, 0); - rb_define_method(rb_cDBM, "reject", fdbm_reject, 0); - rb_define_method(rb_cDBM, "clear", fdbm_clear, 0); - rb_define_method(rb_cDBM,"invert", fdbm_invert, 0); - rb_define_method(rb_cDBM,"update", fdbm_update, 1); - rb_define_method(rb_cDBM,"replace", fdbm_replace, 1); - - rb_define_method(rb_cDBM, "include?", fdbm_has_key, 1); - rb_define_method(rb_cDBM, "has_key?", fdbm_has_key, 1); - rb_define_method(rb_cDBM, "member?", fdbm_has_key, 1); - rb_define_method(rb_cDBM, "has_value?", fdbm_has_value, 1); - rb_define_method(rb_cDBM, "key?", fdbm_has_key, 1); - rb_define_method(rb_cDBM, "value?", fdbm_has_value, 1); - - rb_define_method(rb_cDBM, "to_a", fdbm_to_a, 0); - rb_define_method(rb_cDBM, "to_hash", fdbm_to_hash, 0); -} diff --git a/ext/dbm/depend b/ext/dbm/depend deleted file mode 100644 index 5fae80b096..0000000000 --- a/ext/dbm/depend +++ /dev/null @@ -1 +0,0 @@ -dbm.o: dbm.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/dbm/extconf.rb b/ext/dbm/extconf.rb deleted file mode 100644 index 51b1bfd81b..0000000000 --- a/ext/dbm/extconf.rb +++ /dev/null @@ -1,56 +0,0 @@ -require 'mkmf' - -dir_config("dbm") - -dblib = with_config("dbm-type", nil) - -$dbm_conf_headers = { - "db" => ["db.h"], - "db1" => ["db1/ndbm.h", "db1.h", "ndbm.h"], - "db2" => ["db2/db.h", "db2.h", "db.h"], - "dbm" => ["ndbm.h"], - "gdbm" => ["gdbm-ndbm.h", "ndbm.h"], -} - -def db_check(db) - $dbm_conf_db_prefix = "" - $dbm_conf_have_gdbm = false - hsearch = "" - - case db - when /^db2?$/ - $dbm_conf_db_prefix = "__db_n" - hsearch = "-DDB_DBM_HSEARCH " - when "gdbm" - $dbm_conf_have_gdbm = true - end - - if have_func(db_prefix("dbm_open")) || have_library(db, db_prefix("dbm_open")) - for hdr in $dbm_conf_headers.fetch(db, ["ndbm.h"]) - if have_header(hdr.dup) - $CFLAGS += " " + hsearch + "-DDBM_HDR='<"+hdr+">'" - return true - end - end - end - return false -end - -def db_prefix(func) - $dbm_conf_db_prefix+func -end - -if dblib - db_check(dblib) -else - for dblib in %w(db db2 db1 dbm gdbm) - db_check(dblib) and break - end -end - -have_header("cdefs.h") -have_header("sys/cdefs.h") -if /DBM_HDR/ =~ $CFLAGS and have_func(db_prefix("dbm_open")) - have_func(db_prefix("dbm_clearerr")) unless $dbm_conf_have_gdbm - create_makefile("dbm") -end diff --git a/ext/dbm/testdbm.rb b/ext/dbm/testdbm.rb deleted file mode 100644 index 0be627d346..0000000000 --- a/ext/dbm/testdbm.rb +++ /dev/null @@ -1,590 +0,0 @@ -require 'runit/testcase' -require 'runit/cui/testrunner' - -if $".grep(/\bdbm.so\b/).empty? - begin - require './dbm' - rescue LoadError - require 'dbm' - end -end - -def uname_s - require 'rbconfig' - case Config::CONFIG['host_os'] - when 'cygwin' - require 'Win32API' - uname = Win32API.new 'cygwin1', 'uname', 'P', 'I' - utsname = ' ' * 100 - raise 'cannot get system name' if uname.call(utsname) == -1 - - utsname.unpack('A20' * 5)[0] - else - Config::CONFIG['host_os'] - end -end - -SYSTEM = uname_s - -class TestDBM < RUNIT::TestCase - def setup - @path = "tmptest_dbm_" - assert_instance_of(DBM, @dbm = DBM.new(@path)) - - # prepare to make readonly DBM file - DBM.open("tmptest_dbm_rdonly", 0400) {|dbm| - dbm['foo'] = 'FOO' - } - assert_instance_of(DBM, @dbm_rdonly = DBM.new("tmptest_dbm_rdonly", nil)) - end - def teardown - assert_nil(@dbm.close) - assert_nil(@dbm_rdonly.close) - GC.start - File.delete *Dir.glob("tmptest_dbm*").to_a - p Dir.glob("tmptest_dbm*") if $DEBUG - end - - def check_size(expect, dbm=@dbm) - assert_equals(expect, dbm.size) - n = 0 - dbm.each { n+=1 } - assert_equals(expect, n) - if expect == 0 - assert_equals(true, dbm.empty?) - else - assert_equals(false, dbm.empty?) - end - end - - def test_version - STDERR.print DBM::VERSION - end - - def test_s_new_has_no_block - # DBM.new ignore the block - foo = true - assert_instance_of(DBM, dbm = DBM.new("tmptest_dbm") { foo = false }) - assert_equals(foo, true) - assert_nil(dbm.close) - end - def test_s_open_no_create - assert_nil(dbm = DBM.open("tmptest_dbm", nil)) - ensure - dbm.close if dbm - end - def test_s_open_with_block - assert_equals(DBM.open("tmptest_dbm") { :foo }, :foo) - end - def test_s_open_lock - fork() { - assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644)) - sleep 2 - } - begin - sleep 1 - assert_exception(Errno::EWOULDBLOCK) { - begin - assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644)) - rescue Errno::EAGAIN, Errno::EACCES, Errno::EINVAL - raise Errno::EWOULDBLOCK - end - } - ensure - Process.wait - end - end - -=begin - # Is it guaranteed on many OS? - def test_s_open_lock_one_process - # locking on one process - assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644)) - assert_exception(Errno::EWOULDBLOCK) { - begin - DBM.open("tmptest_dbm", 0644) - rescue Errno::EAGAIN - raise Errno::EWOULDBLOCK - end - } - end -=end - - def test_s_open_nolock - # dbm 1.8.0 specific - if not defined? DBM::NOLOCK - return - end - - fork() { - assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644, - DBM::NOLOCK)) - sleep 2 - } - sleep 1 - begin - dbm2 = nil - assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { - assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644)) - } - ensure - Process.wait - dbm2.close if dbm2 - end - - p Dir.glob("tmptest_dbm*") if $DEBUG - - fork() { - assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644)) - sleep 2 - } - begin - sleep 1 - dbm2 = nil - assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { - # this test is failed on Cygwin98 (???) - assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644, - DBM::NOLOCK)) - } - ensure - Process.wait - dbm2.close if dbm2 - end - end - - def test_s_open_error - assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0)) - assert_exception(Errno::EACCES) { - DBM.open("tmptest_dbm", 0) - } - dbm.close - end - - def test_close - assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm")) - assert_nil(dbm.close) - - # closed DBM file - assert_exception(DBMError) { dbm.close } - end - - def test_aref - assert_equals('bar', @dbm['foo'] = 'bar') - assert_equals('bar', @dbm['foo']) - - assert_nil(@dbm['bar']) - end - - def test_fetch - assert_equals('bar', @dbm['foo']='bar') - assert_equals('bar', @dbm.fetch('foo')) - - # key not found - assert_exception(IndexError) { - @dbm.fetch('bar') - } - - # test for `ifnone' arg - assert_equals('baz', @dbm.fetch('bar', 'baz')) - - # test for `ifnone' block - assert_equals('foobar', @dbm.fetch('bar') {|key| 'foo' + key }) - end - - def test_aset - num = 0 - 2.times {|i| - assert_equals('foo', @dbm['foo'] = 'foo') - assert_equals('foo', @dbm['foo']) - assert_equals('bar', @dbm['foo'] = 'bar') - assert_equals('bar', @dbm['foo']) - - num += 1 if i == 0 - assert_equals(num, @dbm.size) - - # assign nil - assert_equals('', @dbm['bar'] = '') - assert_equals('', @dbm['bar']) - - num += 1 if i == 0 - assert_equals(num, @dbm.size) - - # empty string - assert_equals('', @dbm[''] = '') - assert_equals('', @dbm['']) - - num += 1 if i == 0 - assert_equals(num, @dbm.size) - - # Fixnum - assert_equals('200', @dbm['100'] = '200') - assert_equals('200', @dbm['100']) - - num += 1 if i == 0 - assert_equals(num, @dbm.size) - - # Big key and value - assert_equals('y' * 100, @dbm['x' * 100] = 'y' * 100) - assert_equals('y' * 100, @dbm['x' * 100]) - - num += 1 if i == 0 - assert_equals(num, @dbm.size) - } - end - - def test_index - assert_equals('bar', @dbm['foo'] = 'bar') - assert_equals('foo', @dbm.index('bar')) - assert_nil(@dbm['bar']) - end - - def test_indexes - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - assert_equals(values.reverse, @dbm.indexes(*keys.reverse)) - end - - def test_select - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - assert_equals(values.reverse, @dbm.select(*keys.reverse)) - end - - def test_select_with_block - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - ret = @dbm.select {|k,v| - assert_equals(k.upcase, v) - k != "bar" - } - assert_equals([['baz', 'BAZ'], ['foo', 'FOO']], - ret.sort) - end - - def test_length - num = 10 - assert_equals(0, @dbm.size) - num.times {|i| - i = i.to_s - @dbm[i] = i - } - assert_equals(num, @dbm.size) - - @dbm.shift - - assert_equals(num - 1, @dbm.size) - end - - def test_empty? - assert_equals(true, @dbm.empty?) - @dbm['foo'] = 'FOO' - assert_equals(false, @dbm.empty?) - end - - def test_each_pair - n = 0 - @dbm.each_pair { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - - n = 0 - ret = @dbm.each_pair {|key, val| - assert_not_nil(i = keys.index(key)) - assert_equals(val, values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@dbm, ret) - end - - def test_each_value - n = 0 - @dbm.each_value { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - - n = 0 - ret = @dbm.each_value {|val| - assert_not_nil(key = @dbm.index(val)) - assert_not_nil(i = keys.index(key)) - assert_equals(val, values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@dbm, ret) - end - - def test_each_key - n = 0 - @dbm.each_key { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - - n = 0 - ret = @dbm.each_key {|key| - assert_not_nil(i = keys.index(key)) - assert_equals(@dbm[key], values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@dbm, ret) - end - - def test_keys - assert_equals([], @dbm.keys) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - - assert_equals(keys.sort, @dbm.keys.sort) - assert_equals(values.sort, @dbm.values.sort) - end - - def test_values - test_keys - end - - def test_shift - assert_nil(@dbm.shift) - assert_equals(0, @dbm.size) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - - ret_keys = [] - ret_values = [] - while ret = @dbm.shift - ret_keys.push ret[0] - ret_values.push ret[1] - - assert_equals(keys.size - ret_keys.size, @dbm.size) - end - - assert_equals(keys.sort, ret_keys.sort) - assert_equals(values.sort, ret_values.sort) - end - - def test_delete - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - key = keys[1] - - assert_nil(@dbm.delete(key)) - assert_equals(0, @dbm.size) - - @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values - - assert_equals('BAR', @dbm.delete(key)) - assert_nil(@dbm[key]) - assert_equals(2, @dbm.size) - - assert_nil(@dbm.delete(key)) - - if /^CYGWIN_9/ !~ SYSTEM - assert_exception(DBMError) { - @dbm_rdonly.delete("foo") - } - - assert_nil(@dbm_rdonly.delete("bar")) - end - end - def test_delete_with_block - key = 'no called block' - @dbm[key] = 'foo' - assert_equals('foo', @dbm.delete(key) {|k| k.replace 'called block'}) - assert_equals('no called block', key) - assert_equals(0, @dbm.size) - - key = 'no called block' - assert_equals(:blockval, - @dbm.delete(key) {|k| k.replace 'called block'; :blockval}) - assert_equals('called block', key) - assert_equals(0, @dbm.size) - end - - def test_delete_if - v = "0" - 100.times {@dbm[v] = v; v = v.next} - - ret = @dbm.delete_if {|key, val| key.to_i < 50} - assert_equals(@dbm, ret) - check_size(50, @dbm) - - ret = @dbm.delete_if {|key, val| key.to_i >= 50} - assert_equals(@dbm, ret) - check_size(0, @dbm) - - # break - v = "0" - 100.times {@dbm[v] = v; v = v.next} - check_size(100, @dbm) - n = 0; - @dbm.delete_if {|key, val| - break if n > 50 - n+=1 - true - } - assert_equals(51, n) - check_size(49, @dbm) - - @dbm.clear - - # raise - v = "0" - 100.times {@dbm[v] = v; v = v.next} - check_size(100, @dbm) - n = 0; - begin - @dbm.delete_if {|key, val| - raise "runtime error" if n > 50 - n+=1 - true - } - rescue - end - assert_equals(51, n) - check_size(49, @dbm) - end - - def test_reject - v = "0" - 100.times {@dbm[v] = v; v = v.next} - - hash = @dbm.reject {|key, val| key.to_i < 50} - assert_instance_of(Hash, hash) - assert_equals(100, @dbm.size) - - assert_equals(50, hash.size) - hash.each_pair {|key,val| - assert_equals(false, key.to_i < 50) - assert_equals(key, val) - } - - hash = @dbm.reject {|key, val| key.to_i < 100} - assert_instance_of(Hash, hash) - assert_equals(true, hash.empty?) - end - - def test_clear - v = "1" - 100.times {v = v.next; @dbm[v] = v} - - assert_equals(@dbm, @dbm.clear) - - # validate DBM#size - i = 0 - @dbm.each { i += 1 } - assert_equals(@dbm.size, i) - assert_equals(0, i) - end - - def test_invert - v = "0" - 100.times {@dbm[v] = v; v = v.next} - - hash = @dbm.invert - assert_instance_of(Hash, hash) - assert_equals(100, hash.size) - hash.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_update - hash = {} - v = "0" - 100.times {v = v.next; hash[v] = v} - - @dbm["101"] = "101" - @dbm.update hash - assert_equals(101, @dbm.size) - @dbm.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_replace - hash = {} - v = "0" - 100.times {v = v.next; hash[v] = v} - - @dbm["101"] = "101" - @dbm.replace hash - assert_equals(100, @dbm.size) - @dbm.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_haskey? - assert_equals('bar', @dbm['foo']='bar') - assert_equals(true, @dbm.has_key?('foo')) - assert_equals(false, @dbm.has_key?('bar')) - end - - def test_has_value? - assert_equals('bar', @dbm['foo']='bar') - assert_equals(true, @dbm.has_value?('bar')) - assert_equals(false, @dbm.has_value?('foo')) - end - - def test_to_a - v = "0" - 100.times {v = v.next; @dbm[v] = v} - - ary = @dbm.to_a - assert_instance_of(Array, ary) - assert_equals(100, ary.size) - ary.each {|key,val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_to_hash - v = "0" - 100.times {v = v.next; @dbm[v] = v} - - hash = @dbm.to_hash - assert_instance_of(Hash, hash) - assert_equals(100, hash.size) - hash.each {|key,val| - assert_equals(key.to_i, val.to_i) - } - end -end - -if $0 == __FILE__ - if ARGV.size == 0 - suite = RUNIT::TestSuite.new - suite.add_test(TestDBM.suite) - else - suite = RUNIT::TestSuite.new - ARGV.each do |testmethod| - suite.add_test(TestDBM.new(testmethod)) - end - end - - RUNIT::CUI::TestRunner.run(suite) -end diff --git a/ext/digest/.cvsignore b/ext/digest/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/digest/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/digest/MANIFEST b/ext/digest/MANIFEST deleted file mode 100644 index fd26581c63..0000000000 --- a/ext/digest/MANIFEST +++ /dev/null @@ -1,39 +0,0 @@ -MANIFEST -defs.h -digest.c -digest.h -digest.txt -digest.txt.ja -extconf.rb -lib/md5.rb -lib/sha1.rb -md5/MANIFEST -md5/extconf.rb -md5/md5.c -md5/md5.h -md5/md5init.c -md5/depend -rmd160/MANIFEST -rmd160/extconf.rb -rmd160/rmd160.c -rmd160/rmd160.h -rmd160/rmd160hl.c -rmd160/rmd160init.c -rmd160/depend -sha1/MANIFEST -sha1/extconf.rb -sha1/sha1.c -sha1/sha1.h -sha1/sha1hl.c -sha1/sha1init.c -sha1/depend -sha2/MANIFEST -sha2/extconf.rb -sha2/sha2.c -sha2/sha2.h -sha2/sha2hl.c -sha2/sha2init.c -sha2/depend -test.rb -test.sh -depend diff --git a/ext/digest/defs.h b/ext/digest/defs.h deleted file mode 100644 index df7df377b9..0000000000 --- a/ext/digest/defs.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -*- C -*- - * $Id$ - */ - -#ifndef DEFS_H -#define DEFS_H - -#include "ruby.h" -#include - -#if defined(HAVE_SYS_CDEFS_H) -# include -#endif -#if !defined(__BEGIN_DECLS) -# define __BEGIN_DECLS -# define __END_DECLS -#endif - -#if defined(HAVE_INTTYPES_H) -# include -#else - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; -# if SIZEOF_LONG == 8 - typedef unsigned long uint64_t; -# elif defined(__GNUC__) - typedef unsigned long long uint64_t; -# elif defined(_MSC_VER) - typedef unsigned _int64 uint64_t; -# else -# define NO_UINT64_T -# endif -#endif - -#endif /* DEFS_H */ diff --git a/ext/digest/depend b/ext/digest/depend deleted file mode 100644 index 43601a208f..0000000000 --- a/ext/digest/depend +++ /dev/null @@ -1,2 +0,0 @@ -digest.o: digest.c digest.h $(hdrdir)/ruby.h $(topdir)/config.h \ - $(hdrdir)/defines.h $(hdrdir)/intern.h diff --git a/ext/digest/digest.c b/ext/digest/digest.c deleted file mode 100644 index 3d47685aac..0000000000 --- a/ext/digest/digest.c +++ /dev/null @@ -1,343 +0,0 @@ -/************************************************ - - digest.c - - - $Author$ - created at: Fri May 25 08:57:27 JST 2001 - - Copyright (C) 1995-2001 Yukihiro Matsumoto - Copyright (C) 2001 Akinori MUSHA - - $RoughId: digest.c,v 1.16 2001/07/13 15:38:27 knu Exp $ - $Id$ - -************************************************/ - -/* - * This module provides an interface to the following hash algorithms: - * - * - the MD5 Message-Digest Algorithm by the RSA Data Security, - * Inc., described in RFC 1321 - * - * - the SHA-1 Secure Hash Algorithm by NIST (the US' National - * Institute of Standards and Technology), described in FIPS PUB - * 180-1. - * - * - the SHA-256/384/512 Secure Hash Algorithm by NIST (the US' - * National Institute of Standards and Technology), described in - * FIPS PUB 180-2. - * - * - the RIPEMD-160 cryptographic hash function, designed by Hans - * Dobbertin, Antoon Bosselaers, and Bart Preneel. - */ - -#include "digest.h" - -static VALUE mDigest, cDigest_Base; -static ID id_metadata; - -/* - * Digest::Base - */ - -static algo_t * -get_digest_base_metadata(class) - VALUE class; -{ - VALUE obj; - algo_t *algo; - - if (rb_cvar_defined(class, id_metadata) == Qfalse) - rb_notimplement(); - - obj = rb_cvar_get(class, id_metadata); - - Data_Get_Struct(obj, algo_t, algo); - - return algo; -} - -static VALUE -rb_digest_base_s_new(argc, argv, class) - int argc; - VALUE* argv; - VALUE class; -{ - algo_t *algo; - VALUE obj; - void *pctx; - - if (class == cDigest_Base) - rb_raise(rb_eNotImpError, "Digest::Base is an abstract class"); - - algo = get_digest_base_metadata(class); - - pctx = xmalloc(algo->ctx_size); - algo->init_func(pctx); - - obj = Data_Wrap_Struct(class, 0, free, pctx); - - rb_obj_call_init(obj, argc, argv); - - return obj; -} - -static VALUE -rb_digest_base_s_digest(class, str) - VALUE class; - VALUE str; -{ - algo_t *algo; - void *pctx; - size_t len; - unsigned char *digest; - VALUE obj; - - if (class == cDigest_Base) - rb_raise(rb_eNotImpError, "Digest::Base is an abstract class"); - -#ifdef StringValue - StringValue(str); -#else - Check_Type(str, T_STRING); -#endif - - algo = get_digest_base_metadata(class); - - pctx = xmalloc(algo->ctx_size); - algo->init_func(pctx); - algo->update_func(pctx, RSTRING(str)->ptr, RSTRING(str)->len); - - len = algo->digest_len; - - digest = xmalloc(len); - algo->final_func(digest, pctx); - - obj = rb_str_new(digest, len); - - free(digest); - free(pctx); - - return obj; -} - -static VALUE -rb_digest_base_s_hexdigest(class, str) - VALUE class; - VALUE str; -{ - algo_t *algo; - void *pctx; - size_t len; - unsigned char *hexdigest; - VALUE obj; - - if (class == cDigest_Base) - rb_raise(rb_eNotImpError, "Digest::Base is an abstract class"); - -#ifdef StringValue - StringValue(str); -#else - Check_Type(str, T_STRING); -#endif - - algo = get_digest_base_metadata(class); - - pctx = xmalloc(algo->ctx_size); - algo->init_func(pctx); - algo->update_func(pctx, RSTRING(str)->ptr, RSTRING(str)->len); - - len = algo->digest_len * 2; - - hexdigest = xmalloc(len + 1); /* +1 is for '\0' */ - algo->end_func(pctx, hexdigest); - - obj = rb_str_new(hexdigest, len); - - free(hexdigest); - free(pctx); - - return obj; -} - -static VALUE -rb_digest_base_clone(self) - VALUE self; -{ - algo_t *algo; - void *pctx1, *pctx2; - VALUE class; - - class = CLASS_OF(self); - algo = get_digest_base_metadata(class); - Data_Get_Struct(self, void, pctx1); - - pctx2 = xmalloc(algo->ctx_size); - memcpy(pctx2, pctx1, algo->ctx_size); - - return Data_Wrap_Struct(class, 0, free, pctx2); -} - -static VALUE -rb_digest_base_update(self, str) - VALUE self, str; -{ - algo_t *algo; - void *pctx; - -#ifdef StringValue - StringValue(str); -#else - Check_Type(str, T_STRING); -#endif - - algo = get_digest_base_metadata(CLASS_OF(self)); - Data_Get_Struct(self, void, pctx); - - algo->update_func(pctx, RSTRING(str)->ptr, RSTRING(str)->len); - - return self; -} - -static VALUE -rb_digest_base_init(argc, argv, self) - int argc; - VALUE* argv; - VALUE self; -{ - VALUE arg; - - rb_scan_args(argc, argv, "01", &arg); - - if (!NIL_P(arg)) rb_digest_base_update(self, arg); - - return self; -} - -static VALUE -rb_digest_base_digest(self) - VALUE self; -{ - algo_t *algo; - void *pctx1, *pctx2; - unsigned char *digest; - size_t len; - VALUE str; - - algo = get_digest_base_metadata(CLASS_OF(self)); - Data_Get_Struct(self, void, pctx1); - - len = algo->ctx_size; - - pctx2 = xmalloc(len); - memcpy(pctx2, pctx1, len); - - len = algo->digest_len; - - digest = xmalloc(len); - algo->final_func(digest, pctx2); - - str = rb_str_new(digest, len); - - free(digest); - free(pctx2); - - return str; -} - -static VALUE -rb_digest_base_hexdigest(self) - VALUE self; -{ - algo_t *algo; - void *pctx1, *pctx2; - unsigned char *hexdigest; - size_t len; - VALUE str; - - algo = get_digest_base_metadata(CLASS_OF(self)); - Data_Get_Struct(self, void, pctx1); - - len = algo->ctx_size; - - pctx2 = xmalloc(len); - memcpy(pctx2, pctx1, len); - - len = algo->digest_len * 2; - - hexdigest = xmalloc(len + 1); /* +1 is for '\0' */ - algo->end_func(pctx2, hexdigest); - - str = rb_str_new(hexdigest, len); - - free(hexdigest); - free(pctx2); - - return str; -} - -static VALUE -rb_digest_base_equal(self, other) - VALUE self, other; -{ - algo_t *algo; - VALUE class; - VALUE str1, str2; - - class = CLASS_OF(self); - algo = get_digest_base_metadata(class); - - if (CLASS_OF(other) == class) { - void *pctx1, *pctx2; - - Data_Get_Struct(self, void, pctx1); - Data_Get_Struct(other, void, pctx2); - - return algo->equal_func(pctx1, pctx2) ? Qtrue : Qfalse; - } - -#ifdef StringValue - StringValue(other); -#else - Check_Type(other, T_STRING); -#endif - str2 = other; - - if (RSTRING(str2)->len == algo->digest_len) - str1 = rb_digest_base_digest(self); - else - str1 = rb_digest_base_hexdigest(self); - - if (RSTRING(str1)->len == RSTRING(str2)->len - && rb_str_cmp(str1, str2) == 0) - return Qtrue; - - return Qfalse; -} - -/* - * Init - */ - -void -Init_digest() -{ - mDigest = rb_define_module("Digest"); - - cDigest_Base = rb_define_class_under(mDigest, "Base", rb_cObject); - - rb_define_singleton_method(cDigest_Base, "new", rb_digest_base_s_new, -1); - rb_define_singleton_method(cDigest_Base, "digest", rb_digest_base_s_digest, 1); - rb_define_singleton_method(cDigest_Base, "hexdigest", rb_digest_base_s_hexdigest, 1); - - rb_define_method(cDigest_Base, "initialize", rb_digest_base_init, -1); - rb_define_method(cDigest_Base, "clone", rb_digest_base_clone, 0); - rb_define_method(cDigest_Base, "update", rb_digest_base_update, 1); - rb_define_method(cDigest_Base, "<<", rb_digest_base_update, 1); - rb_define_method(cDigest_Base, "digest", rb_digest_base_digest, 0); - rb_define_method(cDigest_Base, "hexdigest", rb_digest_base_hexdigest, 0); - rb_define_method(cDigest_Base, "to_s", rb_digest_base_hexdigest, 0); - rb_define_method(cDigest_Base, "==", rb_digest_base_equal, 1); - - id_metadata = rb_intern("metadata"); -} diff --git a/ext/digest/digest.h b/ext/digest/digest.h deleted file mode 100644 index 5e846df040..0000000000 --- a/ext/digest/digest.h +++ /dev/null @@ -1,32 +0,0 @@ -/************************************************ - - digest.c - - - $Author$ - created at: Fri May 25 08:54:56 JST 2001 - - - Copyright (C) 2001 Akinori MUSHA - - $RoughId: digest.h,v 1.3 2001/07/13 15:38:27 knu Exp $ - $Id$ - -************************************************/ - -#include "ruby.h" - -typedef void (*hash_init_func_t) _((void *)); -typedef void (*hash_update_func_t) _((void *, unsigned char *, size_t)); -typedef void (*hash_end_func_t) _((void *, unsigned char *)); -typedef void (*hash_final_func_t) _((unsigned char *, void *)); -typedef int (*hash_equal_func_t) _((void *, void *)); - -typedef struct { - size_t digest_len; - size_t ctx_size; - hash_init_func_t init_func; - hash_update_func_t update_func; - hash_end_func_t end_func; - hash_final_func_t final_func; - hash_equal_func_t equal_func; -} algo_t; diff --git a/ext/digest/digest.txt b/ext/digest/digest.txt deleted file mode 100644 index 5797dd18f9..0000000000 --- a/ext/digest/digest.txt +++ /dev/null @@ -1,113 +0,0 @@ -.\" digest.txt - -*- Indented-Text -*- created at: Fri May 25 08:13:50 JST 2001 -$RoughId: digest.txt,v 1.9 2001/07/13 19:46:51 knu Exp $ -$Id$ - -** MD5(Class) - -A class to implement the MD5 Message-Digest Algorithm by RSA Data -Security, Inc., described in RFC1321. - -Superclass: Digest::Base - -require 'digest/md5' - -** SHA1(Class) - -A class to implement the SHA-1 Secure Hash Algorithm by NIST (the US' -National Institute of Standards and Technology), described in FIPS PUB -180-1. - -Superclass: Digest::Base - -require 'digest/sha1' - -** SHA256(Class) -** SHA384(Class) -** SHA512(Class) - -Classes to implement the SHA-256/384/512 Secure Hash Algorithm(s) by -NIST (the US' National Institute of Standards and Technology), -described in FIPS PUB 180-2. - -Superclass: Digest::Base - -require 'digest/sha2' - -** RMD160(Class) - -A class to implement the RIPEMD-160 cryptographic hash function, -designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel. - -Superclass: Digest::Base - -require 'digest/rmd160' - - -Those above classes provide a common interface as shown below. - - -Class Methods: - - new([str]) - - Creates a new digest object. If a string argument is given, - it is added to the object. (see update.) - - digest(str) - - Immediately calculates and return the hash of the given - strings as a string. Equivalent to new(str).digest. - - hexdigest(str) - - Immediately calculates and return the hash of the given - strings as a string of hexadecimal digits. Equivalent to - new(str).hexdigest. - -Methods: - - clone - - Creates a copy of the digest object. - - digest - - Returns the hash of the added strings as a string of 16 bytes - for MD5, 20 bytes for SHA1 and RMD160, 32 bytes for SHA256, 48 - bytes for SHA384, and 64 bytes for SHA512. - - hexdigest - to_s - - Returns the hash of the added strings as a string of 32 - hexadecimal digits for MD5, 40 hexadecimal digits for SHA1 and - RMD160, 64 hexadecimal digits for SHA256, 96 hexadecimal - digits for SHA384, and 128 hexadecimal digits for SHA512. - This method is equal to: - - def hexdigest - digest.unpack("H*")[0] - end - - update(str) - << str - - Appends the string str to the digest object. Repeated calls - are equivalent to a single call with the concatenation of all - the arguments, i.e. m.update(a); m.update(b) is equivalent to - m.update(a + b) and m << a << b is equivalent to m << a + b. - - == md - - Checks if the object is equal to the given digest object. - - == str - - Regards the value as either a digest value or a hexdigest - value (depending on the length) and checks if the object is - equal to the given string. - -------------------------------------------------------- -Local variables: -fill-column: 70 -end: diff --git a/ext/digest/digest.txt.ja b/ext/digest/digest.txt.ja deleted file mode 100644 index 8997d25b9d..0000000000 --- a/ext/digest/digest.txt.ja +++ /dev/null @@ -1,111 +0,0 @@ -.\" digest.txt.ja - -*- Indented-Text -*- created at: Fri May 25 08:22:19 JST 2001 -$RoughId: digest.txt.jp,v 1.8 2001/07/13 15:38:27 knu Exp $ -$Id$ - -** MD5(¥¯¥é¥¹) - -RFC1321¤Ëµ­½Ò¤µ¤ì¤Æ¤¤¤ëRSA Data Security, Inc. ¤Î MD5 Message-Digest -Algorithm¤ò¼ÂÁõ¤¹¤ë¥¯¥é¥¹¡£ - -Superclass: Digest::Base - -require 'digest/md5' - -** SHA1(¥¯¥é¥¹) - -FIPS PUB 180-1¤Ëµ­½Ò¤µ¤ì¤Æ¤¤¤ëNIST (the US' National Institute of -Standards and Technology) ¤Î SHA-1 Secure Hash Algorithm¤ò¼ÂÁõ¤¹¤ë¥¯¥é¥¹¡£ - -Superclass: Digest::Base - -require 'digest/sha1' - -** SHA256(¥¯¥é¥¹) -** SHA384(¥¯¥é¥¹) -** SHA512(¥¯¥é¥¹) - -FIPS PUB 180-2¤Ëµ­½Ò¤µ¤ì¤Æ¤¤¤ëNIST (the US' National Institute of -Standards and Technology) ¤Î SHA-256/384/512 Secure Hash Algorithm¤ò -¼ÂÁõ¤¹¤ë¥¯¥é¥¹¡£ - -Superclass: Digest::Base - -require 'digest/sha2' - -** RMD160(¥¯¥é¥¹) - -Hans Dobbertin, Antoon Bosselaers, Bart Preneel ¤Ë¤è¤Ã¤ÆÀ߷פµ¤ì¤¿ -RIPEMD-160 ¥Ï¥Ã¥·¥å´Ø¿ô¤ò¼ÂÁõ¤¹¤ë¥¯¥é¥¹¡£ - -Superclass: Digest::Base - -require 'digest/rmd160' - - -¤³¤ì¤é¤Î¥¯¥é¥¹¤Ï°Ê²¼¤Î¤è¤¦¤Ê¶¦Ä̤Υ¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤òÄ󶡤¹¤ë¡£ - - -Class Methods: - - new([str]) - - ¿·¤·¤¤¥À¥¤¥¸¥§¥¹¥È¥ª¥Ö¥¸¥§¥¯¥È¤òÀ¸À®¤¹¤ë¡¥Ê¸»úÎó°ú¿ô¤¬Í¿¤¨¤é¤ì¤ë - ¤È¤½¤ì¤òÄɲ乤ë(see update)¡£ - - digest(str) - - Í¿¤¨¤é¤ì¤¿Ê¸»úÎó¤ËÂФ¹¤ë¥Ï¥Ã¥·¥åÃͤòʸ»úÎó¤ÇÊÖ¤¹¡£ - new(str).digest ¤ÈÅù²Á¡£ - - hexdigest(str) - - Í¿¤¨¤é¤ì¤¿Ê¸»úÎó¤ËÂФ¹¤ë¥Ï¥Ã¥·¥åÃͤò¡¢ASCII¥³¡¼¥É¤ò»È¤Ã¤Æ - 16¿Ê¿ô¤ÎÎó¤ò¼¨¤¹Ê¸»úÎó¤Ë¥¨¥ó¥³¡¼¥É¤·¤ÆÊÖ¤¹¡£ - new(str).hexdigest ¤ÈÅù²Á¡£ - -Methods: - - clone - - ¥À¥¤¥¸¥§¥¹¥È¥ª¥Ö¥¸¥§¥¯¥È¤ÎÊ£À½¤òºî¤ë¡£ - - digest - - º£¤Þ¤Ç¤ËÄɲä·¤¿Ê¸»úÎó¤ËÂФ¹¤ë¥Ï¥Ã¥·¥åÃͤòʸ»úÎó¤ÇÊÖ¤¹¡£MD5¤Ç¤Ï - 16¥Ð¥¤¥ÈĹ¡¢SHA1¤ª¤è¤ÓRMD160¤Ç¤Ï20¥Ð¥¤¥ÈĹ¡¢SHA256¤Ç¤Ï32¥Ð¥¤¥ÈĹ¡¢ - SHA384¤Ç¤Ï48¥Ð¥¤¥ÈĹ¡¢SHA512¤Ç¤Ï64¥Ð¥¤¥ÈĹ¤È¤Ê¤ë¡£ - - hexdigest - to_s - - º£¤Þ¤Ç¤ËÄɲä·¤¿Ê¸»úÎó¤ËÂФ¹¤ë¥Ï¥Ã¥·¥åÃͤò¡¢ASCII¥³¡¼¥É¤ò»È¤Ã¤Æ - 16¿Ê¿ô¤ÎÎó¤ò¼¨¤¹Ê¸»úÎó¤Ë¥¨¥ó¥³¡¼¥É¤·¤ÆÊÖ¤¹¡£MD5¤Ç¤Ï32¥Ð¥¤¥ÈĹ¡¢ - SHA1¤ª¤è¤ÓRMD160¤Ç¤Ï40¥Ð¥¤¥ÈĹ¡¢SHA256¤Ç¤Ï64¥Ð¥¤¥ÈĹ¡¢SHA384¤Ç¤Ï - 96¥Ð¥¤¥ÈĹ¡¢SHA512¤Ç¤Ï128¥Ð¥¤¥ÈĹ¤È¤Ê¤ë¡£Ruby¤Ç½ñ¤¯¤È°Ê²¼¤ÈƱ¤¸¡£ - - def hexdigest - digest.unpack("H*")[0] - end - - update(str) - << str - - ʸ»úÎó¤òÄɲ乤롣ʣ¿ô²óupdate¤ò¸Æ¤Ö¤³¤È¤Ïʸ»úÎó¤òÏ¢·ë¤·¤Æ - update¤ò¸Æ¤Ö¤³¤È¤ÈÅù¤·¤¤¡£¤¹¤Ê¤ï¤Á m.update(a); m.update(b) ¤Ï - m.update(a + b) ¤È¡¢ m << a << b ¤Ï m << a + b ¤È¤½¤ì¤¾¤ìÅù²Á - ¤Ç¤¢¤ë¡£ - - == md - - Í¿¤¨¤é¤ì¤¿¥À¥¤¥¸¥§¥¹¥È¥ª¥Ö¥¸¥§¥¯¥È¤ÈÈæ³Ó¤¹¤ë¡£ - - == str - - Í¿¤¨¤é¤ì¤¿Ê¸»úÎó¤ò digest ÃÍ¡¢¤â¤·¤¯¤Ï hexdigest ÃͤÈÈæ³Ó¤¹¤ë¡£ - ¤¤¤º¤ì¤ÎÃͤȸ«¤ë¤«¤ÏÍ¿¤¨¤é¤ì¤¿Ê¸»úÎó¤ÎŤµ¤Ë¤è¤Ã¤Æ¼«Æ°È½ÊÌ - ¤µ¤ì¤ë¡£ - -------------------------------------------------------- -Local variables: -fill-column: 70 -end: diff --git a/ext/digest/extconf.rb b/ext/digest/extconf.rb deleted file mode 100644 index cd512622a4..0000000000 --- a/ext/digest/extconf.rb +++ /dev/null @@ -1,6 +0,0 @@ -# $RoughId: extconf.rb,v 1.6 2001/07/13 15:38:27 knu Exp $ -# $Id$ - -require "mkmf" - -create_makefile("digest") diff --git a/ext/digest/lib/md5.rb b/ext/digest/lib/md5.rb deleted file mode 100644 index 1d05d7d04e..0000000000 --- a/ext/digest/lib/md5.rb +++ /dev/null @@ -1,14 +0,0 @@ -# just for compatibility; requiring "md5" is obsoleted -# -# $RoughId: md5.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ -# $Id$ - -require 'digest/md5' - -MD5 = Digest::MD5 - -class MD5 - def self.md5(*args) - new(*args) - end -end diff --git a/ext/digest/lib/sha1.rb b/ext/digest/lib/sha1.rb deleted file mode 100644 index c4ac6f66ea..0000000000 --- a/ext/digest/lib/sha1.rb +++ /dev/null @@ -1,14 +0,0 @@ -# just for compatibility; requiring "sha1" is obsoleted -# -# $RoughId: sha1.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ -# $Id$ - -require 'digest/sha1' - -SHA1 = Digest::SHA1 - -class SHA1 - def self.sha1(*args) - new(*args) - end -end diff --git a/ext/digest/md5/.cvsignore b/ext/digest/md5/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/digest/md5/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/digest/md5/MANIFEST b/ext/digest/md5/MANIFEST deleted file mode 100644 index 923af92ed2..0000000000 --- a/ext/digest/md5/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -extconf.rb -md5.c -md5.h -md5init.c -depend diff --git a/ext/digest/md5/depend b/ext/digest/md5/depend deleted file mode 100644 index 30ad482101..0000000000 --- a/ext/digest/md5/depend +++ /dev/null @@ -1,5 +0,0 @@ -md5.o: md5.c md5.h $(srcdir)/../defs.h $(hdrdir)/ruby.h $(topdir)/config.h \ - $(hdrdir)/defines.h $(hdrdir)/intern.h -md5init.o: md5init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h md5.h \ - $(srcdir)/../defs.h diff --git a/ext/digest/md5/extconf.rb b/ext/digest/md5/extconf.rb deleted file mode 100644 index 93a14025d0..0000000000 --- a/ext/digest/md5/extconf.rb +++ /dev/null @@ -1,19 +0,0 @@ -# $RoughId: extconf.rb,v 1.3 2001/08/14 19:54:51 knu Exp $ -# $Id$ - -require "mkmf" - -$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.." - -$objs = [ - "md5.#{$OBJEXT}", - "md5init.#{$OBJEXT}", -] - -have_header("sys/cdefs.h") - -have_header("inttypes.h") - -have_header("unistd.h") - -create_makefile("digest/md5") diff --git a/ext/digest/md5/md5.c b/ext/digest/md5/md5.c deleted file mode 100644 index 6b61f031c4..0000000000 --- a/ext/digest/md5/md5.c +++ /dev/null @@ -1,432 +0,0 @@ -/* - Copyright (C) 1999, 2000 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ - -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321. - It is derived directly from the text of the RFC and not from the - reference implementation. - - The original and principal author of md5.c is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 2000-07-03 lpd Patched to eliminate warnings about "constant is - unsigned in ANSI C, signed in traditional"; - made test program self-checking. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). - 1999-05-03 lpd Original version. - */ - -/*$OrigId: md5c.c,v 1.2 2001/03/26 08:57:14 matz Exp $ */ -/*$RoughId: md5.c,v 1.2 2001/07/13 19:48:41 knu Exp $ */ -/*$Id$ */ - -#include "md5.h" - -#ifdef TEST -/* - * Compile with -DTEST to create a self-contained executable test program. - * The test program should print out the same values as given in section - * A.5 of RFC 1321, reproduced below. - */ -#include -main() -{ - static const char *const test[7*2] = { - "", "d41d8cd98f00b204e9800998ecf8427e", - "a", "0cc175b9c0f1b6a831c399e269772661", - "abc", "900150983cd24fb0d6963f7d28e17f72", - "message digest", "f96b697d7cb7938d525a2f31aaf161d0", - "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b", - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", - "d174ab98d277d9f5a5611c2c9f419d9f", - "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a" - }; - int i; - - for (i = 0; i < 7*2; i += 2) { - MD5_CTX state; - uint8_t digest[16]; - char hex_output[16*2 + 1]; - int di; - - MD5_Init(&state); - MD5_Update(&state, (const uint8_t *)test[i], strlen(test[i])); - MD5_Final(digest, &state); - printf("MD5 (\"%s\") = ", test[i]); - for (di = 0; di < 16; ++di) - sprintf(hex_output + di * 2, "%02x", digest[di]); - puts(hex_output); - if (strcmp(hex_output, test[i + 1])) - printf("**** ERROR, should be: %s\n", test[i + 1]); - } - return 0; -} -#endif /* TEST */ - - -/* - * For reference, here is the program that computed the T values. - */ -#ifdef COMPUTE_T_VALUES -#include -main() -{ - int i; - for (i = 1; i <= 64; ++i) { - unsigned long v = (unsigned long)(4294967296.0 * fabs(sin((double)i))); - - /* - * The following nonsense is only to avoid compiler warnings about - * "integer constant is unsigned in ANSI C, signed with -traditional". - */ - if (v >> 31) { - printf("#define T%d /* 0x%08lx */ (T_MASK ^ 0x%08lx)\n", i, - v, (unsigned long)(unsigned int)(~v)); - } else { - printf("#define T%d 0x%08lx\n", i, v); - } - } - return 0; -} -#endif /* COMPUTE_T_VALUES */ -/* - * End of T computation program. - */ -#ifdef T_MASK -#undef T_MASK -#endif -#define T_MASK ((uint32_t)~0) -#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) -#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) -#define T3 0x242070db -#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) -#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) -#define T6 0x4787c62a -#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) -#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) -#define T9 0x698098d8 -#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) -#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) -#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) -#define T13 0x6b901122 -#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) -#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) -#define T16 0x49b40821 -#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) -#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) -#define T19 0x265e5a51 -#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) -#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) -#define T22 0x02441453 -#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) -#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) -#define T25 0x21e1cde6 -#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) -#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) -#define T28 0x455a14ed -#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) -#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) -#define T31 0x676f02d9 -#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) -#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) -#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) -#define T35 0x6d9d6122 -#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) -#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) -#define T38 0x4bdecfa9 -#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) -#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) -#define T41 0x289b7ec6 -#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) -#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) -#define T44 0x04881d05 -#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) -#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) -#define T47 0x1fa27cf8 -#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) -#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) -#define T50 0x432aff97 -#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) -#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) -#define T53 0x655b59c3 -#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) -#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) -#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) -#define T57 0x6fa87e4f -#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) -#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) -#define T60 0x4e0811a1 -#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) -#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) -#define T63 0x2ad7d2bb -#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) - - -static void -md5_process(MD5_CTX *pms, const uint8_t *data /*[64]*/) -{ - uint32_t - a = pms->state[0], b = pms->state[1], - c = pms->state[2], d = pms->state[3]; - uint32_t t; - -#ifdef WORDS_BIGENDIAN - - /* - * On big-endian machines, we must arrange the bytes in the right - * order. (This also works on machines of unknown byte order.) - */ - uint32_t X[16]; - const uint8_t *xp = data; - int i; - - for (i = 0; i < 16; ++i, xp += 4) - X[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); - -#else - - /* - * On little-endian machines, we can process properly aligned data - * without copying it. - */ - uint32_t xbuf[16]; - const uint32_t *X; - - if (!((data - (const uint8_t *)0) & 3)) { - /* data are properly aligned */ - X = (const uint32_t *)data; - } else { - /* not aligned */ - memcpy(xbuf, data, 64); - X = xbuf; - } -#endif - -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - - /* Round 1. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ -#define F(x, y, z) (((x) & (y)) | (~(x) & (z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + F(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 7, T1); - SET(d, a, b, c, 1, 12, T2); - SET(c, d, a, b, 2, 17, T3); - SET(b, c, d, a, 3, 22, T4); - SET(a, b, c, d, 4, 7, T5); - SET(d, a, b, c, 5, 12, T6); - SET(c, d, a, b, 6, 17, T7); - SET(b, c, d, a, 7, 22, T8); - SET(a, b, c, d, 8, 7, T9); - SET(d, a, b, c, 9, 12, T10); - SET(c, d, a, b, 10, 17, T11); - SET(b, c, d, a, 11, 22, T12); - SET(a, b, c, d, 12, 7, T13); - SET(d, a, b, c, 13, 12, T14); - SET(c, d, a, b, 14, 17, T15); - SET(b, c, d, a, 15, 22, T16); -#undef SET - - /* Round 2. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ -#define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + G(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 1, 5, T17); - SET(d, a, b, c, 6, 9, T18); - SET(c, d, a, b, 11, 14, T19); - SET(b, c, d, a, 0, 20, T20); - SET(a, b, c, d, 5, 5, T21); - SET(d, a, b, c, 10, 9, T22); - SET(c, d, a, b, 15, 14, T23); - SET(b, c, d, a, 4, 20, T24); - SET(a, b, c, d, 9, 5, T25); - SET(d, a, b, c, 14, 9, T26); - SET(c, d, a, b, 3, 14, T27); - SET(b, c, d, a, 8, 20, T28); - SET(a, b, c, d, 13, 5, T29); - SET(d, a, b, c, 2, 9, T30); - SET(c, d, a, b, 7, 14, T31); - SET(b, c, d, a, 12, 20, T32); -#undef SET - - /* Round 3. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + H(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 5, 4, T33); - SET(d, a, b, c, 8, 11, T34); - SET(c, d, a, b, 11, 16, T35); - SET(b, c, d, a, 14, 23, T36); - SET(a, b, c, d, 1, 4, T37); - SET(d, a, b, c, 4, 11, T38); - SET(c, d, a, b, 7, 16, T39); - SET(b, c, d, a, 10, 23, T40); - SET(a, b, c, d, 13, 4, T41); - SET(d, a, b, c, 0, 11, T42); - SET(c, d, a, b, 3, 16, T43); - SET(b, c, d, a, 6, 23, T44); - SET(a, b, c, d, 9, 4, T45); - SET(d, a, b, c, 12, 11, T46); - SET(c, d, a, b, 15, 16, T47); - SET(b, c, d, a, 2, 23, T48); -#undef SET - - /* Round 4. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ -#define I(x, y, z) ((y) ^ ((x) | ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + I(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 6, T49); - SET(d, a, b, c, 7, 10, T50); - SET(c, d, a, b, 14, 15, T51); - SET(b, c, d, a, 5, 21, T52); - SET(a, b, c, d, 12, 6, T53); - SET(d, a, b, c, 3, 10, T54); - SET(c, d, a, b, 10, 15, T55); - SET(b, c, d, a, 1, 21, T56); - SET(a, b, c, d, 8, 6, T57); - SET(d, a, b, c, 15, 10, T58); - SET(c, d, a, b, 6, 15, T59); - SET(b, c, d, a, 13, 21, T60); - SET(a, b, c, d, 4, 6, T61); - SET(d, a, b, c, 11, 10, T62); - SET(c, d, a, b, 2, 15, T63); - SET(b, c, d, a, 9, 21, T64); -#undef SET - - /* Then perform the following additions. (That is increment each - of the four registers by the value it had before this block - was started.) */ - pms->state[0] += a; - pms->state[1] += b; - pms->state[2] += c; - pms->state[3] += d; -} - -void -MD5_Init(MD5_CTX *pms) -{ - pms->count[0] = pms->count[1] = 0; - pms->state[0] = 0x67452301; - pms->state[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; - pms->state[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; - pms->state[3] = 0x10325476; -} - -void -MD5_Update(MD5_CTX *pms, const uint8_t *data, size_t nbytes) -{ - const uint8_t *p = data; - size_t left = nbytes; - size_t offset = (pms->count[0] >> 3) & 63; - uint32_t nbits = (uint32_t)(nbytes << 3); - - if (nbytes <= 0) - return; - - /* Update the message length. */ - pms->count[1] += nbytes >> 29; - pms->count[0] += nbits; - if (pms->count[0] < nbits) - pms->count[1]++; - - /* Process an initial partial block. */ - if (offset) { - size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - - memcpy(pms->buffer + offset, p, copy); - if (offset + copy < 64) - return; - p += copy; - left -= copy; - md5_process(pms, pms->buffer); - } - - /* Process full blocks. */ - for (; left >= 64; p += 64, left -= 64) - md5_process(pms, p); - - /* Process a final partial block. */ - if (left) - memcpy(pms->buffer, p, left); -} - -void -MD5_Final(uint8_t *digest, MD5_CTX *pms) -{ - static const uint8_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - uint8_t data[8]; - size_t i; - - /* Save the length before padding. */ - for (i = 0; i < 8; ++i) - data[i] = (uint8_t)(pms->count[i >> 2] >> ((i & 3) << 3)); - /* Pad to 56 bytes mod 64. */ - MD5_Update(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); - /* Append the length. */ - MD5_Update(pms, data, 8); - for (i = 0; i < 16; ++i) - digest[i] = (uint8_t)(pms->state[i >> 2] >> ((i & 3) << 3)); -} - -void -MD5_End(MD5_CTX *pctx, uint8_t *hexdigest) -{ - unsigned char digest[16]; - size_t i; - - MD5_Final(digest, pctx); - - for (i = 0; i < 16; i++) - sprintf(hexdigest + i * 2, "%02x", digest[i]); -} - -int MD5_Equal(MD5_CTX* pctx1, MD5_CTX* pctx2) { - return memcmp(pctx1->count, pctx2->count, sizeof(pctx1->count)) == 0 - && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0 - && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0; -} diff --git a/ext/digest/md5/md5.h b/ext/digest/md5/md5.h deleted file mode 100644 index fc41380d38..0000000000 --- a/ext/digest/md5/md5.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - Copyright (C) 1999 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321. - It is derived directly from the text of the RFC and not from the - reference implementation. - - The original and principal author of md5.h is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); - added conditionalization for C++ compilation from Martin - Purschke . - 1999-05-03 lpd Original version. - */ - -/* $OrigId: md5.h,v 1.2 2001/03/26 08:57:14 matz Exp $ */ -/* $RoughId: md5.h,v 1.3 2002/02/24 08:14:31 knu Exp $ */ -/* $Id$ */ - -#ifndef MD5_INCLUDED -# define MD5_INCLUDED - -#include "defs.h" - -/* - * This code has some adaptations for the Ghostscript environment, but it - * will compile and run correctly in any environment with 8-bit chars and - * 32-bit ints. Specifically, it assumes that if the following are - * defined, they have the same meaning as in Ghostscript: P1, P2, P3. - */ - -/* Define the state of the MD5 Algorithm. */ -typedef struct md5_state_s { - uint32_t count[2]; /* message length in bits, lsw first */ - uint32_t state[4]; /* digest buffer */ - uint8_t buffer[64]; /* accumulate block */ -} MD5_CTX; - -#ifdef RUBY -#define MD5_Init rb_Digest_MD5_Init -#define MD5_Update rb_Digest_MD5_Update -#define MD5_Final rb_Digest_MD5_Final -#define MD5_End rb_Digest_MD5_End -#define MD5_Equal rb_Digest_MD5_Equal -#endif - -void MD5_Init _((MD5_CTX *pms)); -void MD5_Update _((MD5_CTX *pms, const uint8_t *data, size_t nbytes)); -void MD5_Final _((uint8_t *digest, MD5_CTX *pms)); -void MD5_End _((MD5_CTX *pctx, uint8_t *hexdigest)); -int MD5_Equal _((MD5_CTX *pctx1, MD5_CTX *pctx2)); - -#define MD5_BLOCK_LENGTH 64 -#define MD5_DIGEST_LENGTH 16 -#define MD5_DIGEST_STRING_LENGTH (MD5_DIGEST_LENGTH * 2 + 1) - -#endif /* MD5_INCLUDED */ diff --git a/ext/digest/md5/md5init.c b/ext/digest/md5/md5init.c deleted file mode 100644 index 90ab707433..0000000000 --- a/ext/digest/md5/md5init.c +++ /dev/null @@ -1,34 +0,0 @@ -/* $RoughId: md5init.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */ -/* $Id$ */ - -#include "digest.h" -#include "md5.h" - -static algo_t md5 = { - MD5_DIGEST_LENGTH, - sizeof(MD5_CTX), - (hash_init_func_t)MD5_Init, - (hash_update_func_t)MD5_Update, - (hash_end_func_t)MD5_End, - (hash_final_func_t)MD5_Final, - (hash_equal_func_t)MD5_Equal, -}; - -void -Init_md5() -{ - VALUE mDigest, cDigest_Base, cDigest_MD5; - ID id_metadata; - - rb_require("digest.so"); - - mDigest = rb_path2class("Digest"); - cDigest_Base = rb_path2class("Digest::Base"); - - cDigest_MD5 = rb_define_class_under(mDigest, "MD5", cDigest_Base); - - id_metadata = rb_intern("metadata"); - - rb_cvar_set(cDigest_MD5, id_metadata, - Data_Wrap_Struct(rb_cObject, 0, 0, &md5), Qtrue); -} diff --git a/ext/digest/rmd160/.cvsignore b/ext/digest/rmd160/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/digest/rmd160/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/digest/rmd160/MANIFEST b/ext/digest/rmd160/MANIFEST deleted file mode 100644 index 017976de0d..0000000000 --- a/ext/digest/rmd160/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -extconf.rb -rmd160.c -rmd160.h -rmd160hl.c -rmd160init.c -depend diff --git a/ext/digest/rmd160/depend b/ext/digest/rmd160/depend deleted file mode 100644 index 7cf1d5e639..0000000000 --- a/ext/digest/rmd160/depend +++ /dev/null @@ -1,7 +0,0 @@ -rmd160.o: rmd160.c rmd160.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h -rmd160hl.o: rmd160hl.c rmd160.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h -rmd160init.o: rmd160init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h \ - rmd160.h $(srcdir)/../defs.h diff --git a/ext/digest/rmd160/extconf.rb b/ext/digest/rmd160/extconf.rb deleted file mode 100644 index ce53c77b55..0000000000 --- a/ext/digest/rmd160/extconf.rb +++ /dev/null @@ -1,20 +0,0 @@ -# $RoughId: extconf.rb,v 1.3 2001/08/14 19:54:51 knu Exp $ -# $Id$ - -require "mkmf" - -$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.." - -$objs = [ - "rmd160.#{$OBJEXT}", - "rmd160hl.#{$OBJEXT}", - "rmd160init.#{$OBJEXT}", -] - -have_header("sys/cdefs.h") - -have_header("inttypes.h") - -have_header("unistd.h") - -create_makefile("digest/rmd160") diff --git a/ext/digest/rmd160/rmd160.c b/ext/digest/rmd160/rmd160.c deleted file mode 100644 index 2de3c99b29..0000000000 --- a/ext/digest/rmd160/rmd160.c +++ /dev/null @@ -1,464 +0,0 @@ -/* $NetBSD: rmd160.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $ */ -/* $RoughId: rmd160.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */ -/* $Id$ */ - -/********************************************************************\ - * - * FILE: rmd160.c - * - * CONTENTS: A sample C-implementation of the RIPEMD-160 - * hash-function. - * TARGET: any computer with an ANSI C compiler - * - * AUTHOR: Antoon Bosselaers, ESAT-COSIC - * (Arranged for libc by Todd C. Miller) - * DATE: 1 March 1996 - * VERSION: 1.0 - * - * Copyright (c) Katholieke Universiteit Leuven - * 1996, All Rights Reserved - * -\********************************************************************/ - -#include "rmd160.h" - -#ifndef lint -/* __RCSID("$NetBSD: rmd160.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $"); */ -#endif /* not lint */ - -/* header files */ - -#ifdef HAVE_SYS_ENDIAN_H_ -#include -#endif - -#ifdef HAVE_MACHINE_ENDIAN_H_ -#include -#endif - -/* #include "namespace.h" */ - -#include -#include -#include -#include - -#ifndef _DIAGASSERT -#define _DIAGASSERT(cond) assert(cond) -#endif - - -/********************************************************************/ - -/* macro definitions */ - -/* collect four bytes into one word: */ -#define BYTES_TO_DWORD(strptr) \ - (((uint32_t) *((strptr)+3) << 24) | \ - ((uint32_t) *((strptr)+2) << 16) | \ - ((uint32_t) *((strptr)+1) << 8) | \ - ((uint32_t) *(strptr))) - -/* ROL(x, n) cyclically rotates x over n bits to the left */ -/* x must be of an unsigned 32 bits type and 0 <= n < 32. */ -#define ROL(x, n) (((x) << (n)) | ((x) >> (32-(n)))) - -/* the three basic functions F(), G() and H() */ -#define F(x, y, z) ((x) ^ (y) ^ (z)) -#define G(x, y, z) (((x) & (y)) | (~(x) & (z))) -#define H(x, y, z) (((x) | ~(y)) ^ (z)) -#define I(x, y, z) (((x) & (z)) | ((y) & ~(z))) -#define J(x, y, z) ((x) ^ ((y) | ~(z))) - -/* the eight basic operations FF() through III() */ -#define FF(a, b, c, d, e, x, s) { \ - (a) += F((b), (c), (d)) + (x); \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define GG(a, b, c, d, e, x, s) { \ - (a) += G((b), (c), (d)) + (x) + 0x5a827999U; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define HH(a, b, c, d, e, x, s) { \ - (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1U; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define II(a, b, c, d, e, x, s) { \ - (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcU; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define JJ(a, b, c, d, e, x, s) { \ - (a) += J((b), (c), (d)) + (x) + 0xa953fd4eU; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define FFF(a, b, c, d, e, x, s) { \ - (a) += F((b), (c), (d)) + (x); \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define GGG(a, b, c, d, e, x, s) { \ - (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9U; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define HHH(a, b, c, d, e, x, s) { \ - (a) += H((b), (c), (d)) + (x) + 0x6d703ef3U; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define III(a, b, c, d, e, x, s) { \ - (a) += I((b), (c), (d)) + (x) + 0x5c4dd124U; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} -#define JJJ(a, b, c, d, e, x, s) { \ - (a) += J((b), (c), (d)) + (x) + 0x50a28be6U; \ - (a) = ROL((a), (s)) + (e); \ - (c) = ROL((c), 10); \ -} - -/********************************************************************/ - -void -RMD160_Init(RMD160_CTX *context) -{ - - _DIAGASSERT(context != NULL); - - /* ripemd-160 initialization constants */ - context->state[0] = 0x67452301U; - context->state[1] = 0xefcdab89U; - context->state[2] = 0x98badcfeU; - context->state[3] = 0x10325476U; - context->state[4] = 0xc3d2e1f0U; - context->length[0] = context->length[1] = 0; - context->buflen = 0; -} - -/********************************************************************/ - -void -RMD160_Transform(uint32_t state[5], const uint32_t block[16]) -{ - uint32_t aa, bb, cc, dd, ee; - uint32_t aaa, bbb, ccc, ddd, eee; - - _DIAGASSERT(state != NULL); - _DIAGASSERT(block != NULL); - - aa = aaa = state[0]; - bb = bbb = state[1]; - cc = ccc = state[2]; - dd = ddd = state[3]; - ee = eee = state[4]; - - /* round 1 */ - FF(aa, bb, cc, dd, ee, block[ 0], 11); - FF(ee, aa, bb, cc, dd, block[ 1], 14); - FF(dd, ee, aa, bb, cc, block[ 2], 15); - FF(cc, dd, ee, aa, bb, block[ 3], 12); - FF(bb, cc, dd, ee, aa, block[ 4], 5); - FF(aa, bb, cc, dd, ee, block[ 5], 8); - FF(ee, aa, bb, cc, dd, block[ 6], 7); - FF(dd, ee, aa, bb, cc, block[ 7], 9); - FF(cc, dd, ee, aa, bb, block[ 8], 11); - FF(bb, cc, dd, ee, aa, block[ 9], 13); - FF(aa, bb, cc, dd, ee, block[10], 14); - FF(ee, aa, bb, cc, dd, block[11], 15); - FF(dd, ee, aa, bb, cc, block[12], 6); - FF(cc, dd, ee, aa, bb, block[13], 7); - FF(bb, cc, dd, ee, aa, block[14], 9); - FF(aa, bb, cc, dd, ee, block[15], 8); - - /* round 2 */ - GG(ee, aa, bb, cc, dd, block[ 7], 7); - GG(dd, ee, aa, bb, cc, block[ 4], 6); - GG(cc, dd, ee, aa, bb, block[13], 8); - GG(bb, cc, dd, ee, aa, block[ 1], 13); - GG(aa, bb, cc, dd, ee, block[10], 11); - GG(ee, aa, bb, cc, dd, block[ 6], 9); - GG(dd, ee, aa, bb, cc, block[15], 7); - GG(cc, dd, ee, aa, bb, block[ 3], 15); - GG(bb, cc, dd, ee, aa, block[12], 7); - GG(aa, bb, cc, dd, ee, block[ 0], 12); - GG(ee, aa, bb, cc, dd, block[ 9], 15); - GG(dd, ee, aa, bb, cc, block[ 5], 9); - GG(cc, dd, ee, aa, bb, block[ 2], 11); - GG(bb, cc, dd, ee, aa, block[14], 7); - GG(aa, bb, cc, dd, ee, block[11], 13); - GG(ee, aa, bb, cc, dd, block[ 8], 12); - - /* round 3 */ - HH(dd, ee, aa, bb, cc, block[ 3], 11); - HH(cc, dd, ee, aa, bb, block[10], 13); - HH(bb, cc, dd, ee, aa, block[14], 6); - HH(aa, bb, cc, dd, ee, block[ 4], 7); - HH(ee, aa, bb, cc, dd, block[ 9], 14); - HH(dd, ee, aa, bb, cc, block[15], 9); - HH(cc, dd, ee, aa, bb, block[ 8], 13); - HH(bb, cc, dd, ee, aa, block[ 1], 15); - HH(aa, bb, cc, dd, ee, block[ 2], 14); - HH(ee, aa, bb, cc, dd, block[ 7], 8); - HH(dd, ee, aa, bb, cc, block[ 0], 13); - HH(cc, dd, ee, aa, bb, block[ 6], 6); - HH(bb, cc, dd, ee, aa, block[13], 5); - HH(aa, bb, cc, dd, ee, block[11], 12); - HH(ee, aa, bb, cc, dd, block[ 5], 7); - HH(dd, ee, aa, bb, cc, block[12], 5); - - /* round 4 */ - II(cc, dd, ee, aa, bb, block[ 1], 11); - II(bb, cc, dd, ee, aa, block[ 9], 12); - II(aa, bb, cc, dd, ee, block[11], 14); - II(ee, aa, bb, cc, dd, block[10], 15); - II(dd, ee, aa, bb, cc, block[ 0], 14); - II(cc, dd, ee, aa, bb, block[ 8], 15); - II(bb, cc, dd, ee, aa, block[12], 9); - II(aa, bb, cc, dd, ee, block[ 4], 8); - II(ee, aa, bb, cc, dd, block[13], 9); - II(dd, ee, aa, bb, cc, block[ 3], 14); - II(cc, dd, ee, aa, bb, block[ 7], 5); - II(bb, cc, dd, ee, aa, block[15], 6); - II(aa, bb, cc, dd, ee, block[14], 8); - II(ee, aa, bb, cc, dd, block[ 5], 6); - II(dd, ee, aa, bb, cc, block[ 6], 5); - II(cc, dd, ee, aa, bb, block[ 2], 12); - - /* round 5 */ - JJ(bb, cc, dd, ee, aa, block[ 4], 9); - JJ(aa, bb, cc, dd, ee, block[ 0], 15); - JJ(ee, aa, bb, cc, dd, block[ 5], 5); - JJ(dd, ee, aa, bb, cc, block[ 9], 11); - JJ(cc, dd, ee, aa, bb, block[ 7], 6); - JJ(bb, cc, dd, ee, aa, block[12], 8); - JJ(aa, bb, cc, dd, ee, block[ 2], 13); - JJ(ee, aa, bb, cc, dd, block[10], 12); - JJ(dd, ee, aa, bb, cc, block[14], 5); - JJ(cc, dd, ee, aa, bb, block[ 1], 12); - JJ(bb, cc, dd, ee, aa, block[ 3], 13); - JJ(aa, bb, cc, dd, ee, block[ 8], 14); - JJ(ee, aa, bb, cc, dd, block[11], 11); - JJ(dd, ee, aa, bb, cc, block[ 6], 8); - JJ(cc, dd, ee, aa, bb, block[15], 5); - JJ(bb, cc, dd, ee, aa, block[13], 6); - - /* parallel round 1 */ - JJJ(aaa, bbb, ccc, ddd, eee, block[ 5], 8); - JJJ(eee, aaa, bbb, ccc, ddd, block[14], 9); - JJJ(ddd, eee, aaa, bbb, ccc, block[ 7], 9); - JJJ(ccc, ddd, eee, aaa, bbb, block[ 0], 11); - JJJ(bbb, ccc, ddd, eee, aaa, block[ 9], 13); - JJJ(aaa, bbb, ccc, ddd, eee, block[ 2], 15); - JJJ(eee, aaa, bbb, ccc, ddd, block[11], 15); - JJJ(ddd, eee, aaa, bbb, ccc, block[ 4], 5); - JJJ(ccc, ddd, eee, aaa, bbb, block[13], 7); - JJJ(bbb, ccc, ddd, eee, aaa, block[ 6], 7); - JJJ(aaa, bbb, ccc, ddd, eee, block[15], 8); - JJJ(eee, aaa, bbb, ccc, ddd, block[ 8], 11); - JJJ(ddd, eee, aaa, bbb, ccc, block[ 1], 14); - JJJ(ccc, ddd, eee, aaa, bbb, block[10], 14); - JJJ(bbb, ccc, ddd, eee, aaa, block[ 3], 12); - JJJ(aaa, bbb, ccc, ddd, eee, block[12], 6); - - /* parallel round 2 */ - III(eee, aaa, bbb, ccc, ddd, block[ 6], 9); - III(ddd, eee, aaa, bbb, ccc, block[11], 13); - III(ccc, ddd, eee, aaa, bbb, block[ 3], 15); - III(bbb, ccc, ddd, eee, aaa, block[ 7], 7); - III(aaa, bbb, ccc, ddd, eee, block[ 0], 12); - III(eee, aaa, bbb, ccc, ddd, block[13], 8); - III(ddd, eee, aaa, bbb, ccc, block[ 5], 9); - III(ccc, ddd, eee, aaa, bbb, block[10], 11); - III(bbb, ccc, ddd, eee, aaa, block[14], 7); - III(aaa, bbb, ccc, ddd, eee, block[15], 7); - III(eee, aaa, bbb, ccc, ddd, block[ 8], 12); - III(ddd, eee, aaa, bbb, ccc, block[12], 7); - III(ccc, ddd, eee, aaa, bbb, block[ 4], 6); - III(bbb, ccc, ddd, eee, aaa, block[ 9], 15); - III(aaa, bbb, ccc, ddd, eee, block[ 1], 13); - III(eee, aaa, bbb, ccc, ddd, block[ 2], 11); - - /* parallel round 3 */ - HHH(ddd, eee, aaa, bbb, ccc, block[15], 9); - HHH(ccc, ddd, eee, aaa, bbb, block[ 5], 7); - HHH(bbb, ccc, ddd, eee, aaa, block[ 1], 15); - HHH(aaa, bbb, ccc, ddd, eee, block[ 3], 11); - HHH(eee, aaa, bbb, ccc, ddd, block[ 7], 8); - HHH(ddd, eee, aaa, bbb, ccc, block[14], 6); - HHH(ccc, ddd, eee, aaa, bbb, block[ 6], 6); - HHH(bbb, ccc, ddd, eee, aaa, block[ 9], 14); - HHH(aaa, bbb, ccc, ddd, eee, block[11], 12); - HHH(eee, aaa, bbb, ccc, ddd, block[ 8], 13); - HHH(ddd, eee, aaa, bbb, ccc, block[12], 5); - HHH(ccc, ddd, eee, aaa, bbb, block[ 2], 14); - HHH(bbb, ccc, ddd, eee, aaa, block[10], 13); - HHH(aaa, bbb, ccc, ddd, eee, block[ 0], 13); - HHH(eee, aaa, bbb, ccc, ddd, block[ 4], 7); - HHH(ddd, eee, aaa, bbb, ccc, block[13], 5); - - /* parallel round 4 */ - GGG(ccc, ddd, eee, aaa, bbb, block[ 8], 15); - GGG(bbb, ccc, ddd, eee, aaa, block[ 6], 5); - GGG(aaa, bbb, ccc, ddd, eee, block[ 4], 8); - GGG(eee, aaa, bbb, ccc, ddd, block[ 1], 11); - GGG(ddd, eee, aaa, bbb, ccc, block[ 3], 14); - GGG(ccc, ddd, eee, aaa, bbb, block[11], 14); - GGG(bbb, ccc, ddd, eee, aaa, block[15], 6); - GGG(aaa, bbb, ccc, ddd, eee, block[ 0], 14); - GGG(eee, aaa, bbb, ccc, ddd, block[ 5], 6); - GGG(ddd, eee, aaa, bbb, ccc, block[12], 9); - GGG(ccc, ddd, eee, aaa, bbb, block[ 2], 12); - GGG(bbb, ccc, ddd, eee, aaa, block[13], 9); - GGG(aaa, bbb, ccc, ddd, eee, block[ 9], 12); - GGG(eee, aaa, bbb, ccc, ddd, block[ 7], 5); - GGG(ddd, eee, aaa, bbb, ccc, block[10], 15); - GGG(ccc, ddd, eee, aaa, bbb, block[14], 8); - - /* parallel round 5 */ - FFF(bbb, ccc, ddd, eee, aaa, block[12] , 8); - FFF(aaa, bbb, ccc, ddd, eee, block[15] , 5); - FFF(eee, aaa, bbb, ccc, ddd, block[10] , 12); - FFF(ddd, eee, aaa, bbb, ccc, block[ 4] , 9); - FFF(ccc, ddd, eee, aaa, bbb, block[ 1] , 12); - FFF(bbb, ccc, ddd, eee, aaa, block[ 5] , 5); - FFF(aaa, bbb, ccc, ddd, eee, block[ 8] , 14); - FFF(eee, aaa, bbb, ccc, ddd, block[ 7] , 6); - FFF(ddd, eee, aaa, bbb, ccc, block[ 6] , 8); - FFF(ccc, ddd, eee, aaa, bbb, block[ 2] , 13); - FFF(bbb, ccc, ddd, eee, aaa, block[13] , 6); - FFF(aaa, bbb, ccc, ddd, eee, block[14] , 5); - FFF(eee, aaa, bbb, ccc, ddd, block[ 0] , 15); - FFF(ddd, eee, aaa, bbb, ccc, block[ 3] , 13); - FFF(ccc, ddd, eee, aaa, bbb, block[ 9] , 11); - FFF(bbb, ccc, ddd, eee, aaa, block[11] , 11); - - /* combine results */ - ddd += cc + state[1]; /* final result for state[0] */ - state[1] = state[2] + dd + eee; - state[2] = state[3] + ee + aaa; - state[3] = state[4] + aa + bbb; - state[4] = state[0] + bb + ccc; - state[0] = ddd; -} - -/********************************************************************/ - -void -RMD160_Update(RMD160_CTX *context, const uint8_t *data, size_t nbytes) -{ - uint32_t X[16]; - uint32_t ofs = 0; - uint32_t i; -#ifdef WORDS_BIGENDIAN - uint32_t j; -#endif - - _DIAGASSERT(context != NULL); - _DIAGASSERT(data != NULL); - - /* update length[] */ - if (context->length[0] + nbytes < context->length[0]) - context->length[1]++; /* overflow to msb of length */ - context->length[0] += nbytes; - - (void)memset(X, 0, sizeof(X)); - - if ( context->buflen + nbytes < 64 ) - { - (void)memcpy(context->bbuffer + context->buflen, data, nbytes); - context->buflen += nbytes; - } - else - { - /* process first block */ - ofs = 64 - context->buflen; - (void)memcpy(context->bbuffer + context->buflen, data, ofs); -#ifndef WORDS_BIGENDIAN - (void)memcpy(X, context->bbuffer, sizeof(X)); -#else - for (j=0; j < 16; j++) - X[j] = BYTES_TO_DWORD(context->bbuffer + (4 * j)); -#endif - RMD160_Transform(context->state, X); - nbytes -= ofs; - - /* process remaining complete blocks */ - for (i = 0; i < (nbytes >> 6); i++) { -#ifndef WORDS_BIGENDIAN - (void)memcpy(X, data + (64 * i) + ofs, sizeof(X)); -#else - for (j=0; j < 16; j++) - X[j] = BYTES_TO_DWORD(data + (64 * i) + (4 * j) + ofs); -#endif - RMD160_Transform(context->state, X); - } - - /* - * Put last bytes from data into context's buffer - */ - context->buflen = nbytes & 63; - memcpy(context->bbuffer, data + (64 * i) + ofs, context->buflen); - } -} - -/********************************************************************/ - -void -RMD160_Final(uint8_t digest[20], RMD160_CTX *context) -{ - uint32_t i; - uint32_t X[16]; -#ifdef WORDS_BIGENDIAN - uint32_t j; -#endif - - _DIAGASSERT(digest != NULL); - _DIAGASSERT(context != NULL); - - /* append the bit m_n == 1 */ - context->bbuffer[context->buflen] = (uint8_t)'\200'; - - (void)memset(context->bbuffer + context->buflen + 1, 0, - 63 - context->buflen); -#ifndef WORDS_BIGENDIAN - (void)memcpy(X, context->bbuffer, sizeof(X)); -#else - for (j=0; j < 16; j++) - X[j] = BYTES_TO_DWORD(context->bbuffer + (4 * j)); -#endif - if ((context->buflen) > 55) { - /* length goes to next block */ - RMD160_Transform(context->state, X); - (void)memset(X, 0, sizeof(X)); - } - - /* append length in bits */ - X[14] = context->length[0] << 3; - X[15] = (context->length[0] >> 29) | - (context->length[1] << 3); - RMD160_Transform(context->state, X); - - if (digest != NULL) { - for (i = 0; i < 20; i += 4) { - /* extracts the 8 least significant bits. */ - digest[i] = context->state[i>>2]; - digest[i + 1] = (context->state[i>>2] >> 8); - digest[i + 2] = (context->state[i>>2] >> 16); - digest[i + 3] = (context->state[i>>2] >> 24); - } - } -} - -int RMD160_Equal(RMD160_CTX* pctx1, RMD160_CTX* pctx2) { - return pctx1->buflen == pctx2->buflen - && memcmp(pctx1->length, pctx2->length, sizeof(pctx1->length)) == 0 - && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0 - && memcmp(pctx1->bbuffer, pctx2->bbuffer, sizeof(pctx1->bbuffer)) == 0; -} - -/************************ end of file rmd160.c **********************/ diff --git a/ext/digest/rmd160/rmd160.h b/ext/digest/rmd160/rmd160.h deleted file mode 100644 index 24f9a025f0..0000000000 --- a/ext/digest/rmd160/rmd160.h +++ /dev/null @@ -1,68 +0,0 @@ -/* $NetBSD: rmd160.h,v 1.2 2000/07/07 10:47:06 ad Exp $ */ -/* $RoughId: rmd160.h,v 1.3 2002/02/24 08:14:31 knu Exp $ */ -/* $Id$ */ - -/********************************************************************\ - * - * FILE: rmd160.h - * - * CONTENTS: Header file for a sample C-implementation of the - * RIPEMD-160 hash-function. - * TARGET: any computer with an ANSI C compiler - * - * AUTHOR: Antoon Bosselaers, ESAT-COSIC - * DATE: 1 March 1996 - * VERSION: 1.0 - * - * Copyright (c) Katholieke Universiteit Leuven - * 1996, All Rights Reserved - * -\********************************************************************/ - -/* - * from OpenBSD: rmd160.h,v 1.4 1999/08/16 09:59:04 millert Exp - */ - -#ifndef _RMD160_H_ -#define _RMD160_H_ - -#include "defs.h" - -typedef struct { - uint32_t state[5]; /* state (ABCDE) */ - uint32_t length[2]; /* number of bits */ - uint8_t bbuffer[64]; /* overflow buffer */ - uint32_t buflen; /* number of chars in bbuffer */ -} RMD160_CTX; - -#ifdef RUBY -#define RMD160_Init rb_Digest_RMD160_Init -#define RMD160_Transform rb_Digest_RMD160_Transform -#define RMD160_Update rb_Digest_RMD160_Update -#define RMD160_Final rb_Digest_RMD160_Final -#define RMD160_Equal rb_Digest_RMD160_Equal -#ifndef _KERNEL -#define RMD160_End rb_Digest_RMD160_End -#define RMD160_File rb_Digest_RMD160_File -#define RMD160_Data rb_Digest_RMD160_Data -#endif /* _KERNEL */ -#endif - -__BEGIN_DECLS -void RMD160_Init _((RMD160_CTX *)); -void RMD160_Transform _((uint32_t[5], const uint32_t[16])); -void RMD160_Update _((RMD160_CTX *, const uint8_t *, size_t)); -void RMD160_Final _((uint8_t[20], RMD160_CTX *)); -int RMD160_Equal _((RMD160_CTX *, RMD160_CTX *)); -#ifndef _KERNEL -char *RMD160_End _((RMD160_CTX *, char *)); -char *RMD160_File _((char *, char *)); -char *RMD160_Data _((const uint8_t *, size_t, char *)); -#endif /* _KERNEL */ -__END_DECLS - -#define RMD160_BLOCK_LENGTH 64 -#define RMD160_DIGEST_LENGTH 20 -#define RMD160_DIGEST_STRING_LENGTH (RMD160_DIGEST_LENGTH * 2 + 1) - -#endif /* !_RMD160_H_ */ diff --git a/ext/digest/rmd160/rmd160hl.c b/ext/digest/rmd160/rmd160hl.c deleted file mode 100644 index 4c5e0217d9..0000000000 --- a/ext/digest/rmd160/rmd160hl.c +++ /dev/null @@ -1,96 +0,0 @@ -/* $NetBSD: rmd160hl.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $ */ -/* $RoughId: rmd160hl.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */ -/* $Id$ */ - -/* rmd160hl.c - * ---------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * wrote this file. As long as you retain this notice you - * can do whatever you want with this stuff. If we meet some day, and you think - * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp - * ---------------------------------------------------------------------------- - * - * from OpenBSD: rmd160hl.c,v 1.2 1999/08/17 09:13:12 millert Exp $ - */ - -#include "rmd160.h" - -#ifndef lint -/* __RCSID("$NetBSD: rmd160hl.c,v 1.1.1.1 2001/03/06 11:21:05 agc Exp $"); */ -#endif /* not lint */ - -/* #include "namespace.h" */ - -#include -#include -#include -#include -#include -#if defined(HAVE_UNISTD_H) -# include -#endif - -#ifndef _DIAGASSERT -#define _DIAGASSERT(cond) assert(cond) -#endif - - -char * -RMD160_End(RMD160_CTX *ctx, char *buf) -{ - size_t i; - char *p = buf; - uint8_t digest[20]; - static const char hex[]="0123456789abcdef"; - - _DIAGASSERT(ctx != NULL); - /* buf may be NULL */ - - if (p == NULL && (p = malloc(41)) == NULL) - return 0; - - RMD160_Final(digest,ctx); - for (i = 0; i < 20; i++) { - p[i + i] = hex[(uint32_t)digest[i] >> 4]; - p[i + i + 1] = hex[digest[i] & 0x0f]; - } - p[i + i] = '\0'; - return(p); -} - -char * -RMD160_File(char *filename, char *buf) -{ - uint8_t buffer[BUFSIZ]; - RMD160_CTX ctx; - int fd, num, oerrno; - - _DIAGASSERT(filename != NULL); - /* XXX: buf may be NULL ? */ - - RMD160_Init(&ctx); - - if ((fd = open(filename, O_RDONLY)) < 0) - return(0); - - while ((num = read(fd, buffer, sizeof(buffer))) > 0) - RMD160_Update(&ctx, buffer, (size_t)num); - - oerrno = errno; - close(fd); - errno = oerrno; - return(num < 0 ? 0 : RMD160_End(&ctx, buf)); -} - -char * -RMD160_Data(const uint8_t *data, size_t len, char *buf) -{ - RMD160_CTX ctx; - - _DIAGASSERT(data != NULL); - /* XXX: buf may be NULL ? */ - - RMD160_Init(&ctx); - RMD160_Update(&ctx, data, len); - return(RMD160_End(&ctx, buf)); -} diff --git a/ext/digest/rmd160/rmd160init.c b/ext/digest/rmd160/rmd160init.c deleted file mode 100644 index 6955c2b64b..0000000000 --- a/ext/digest/rmd160/rmd160init.c +++ /dev/null @@ -1,34 +0,0 @@ -/* $RoughId: rmd160init.c,v 1.3 2001/07/13 20:00:43 knu Exp $ */ -/* $Id$ */ - -#include "digest.h" -#include "rmd160.h" - -static algo_t rmd160 = { - RMD160_DIGEST_LENGTH, - sizeof(RMD160_CTX), - (hash_init_func_t)RMD160_Init, - (hash_update_func_t)RMD160_Update, - (hash_end_func_t)RMD160_End, - (hash_final_func_t)RMD160_Final, - (hash_equal_func_t)RMD160_Equal, -}; - -void -Init_rmd160() -{ - VALUE mDigest, cDigest_Base, cDigest_RMD160; - ID id_metadata; - - rb_require("digest.so"); - - mDigest = rb_path2class("Digest"); - cDigest_Base = rb_path2class("Digest::Base"); - - cDigest_RMD160 = rb_define_class_under(mDigest, "RMD160", cDigest_Base); - - id_metadata = rb_intern("metadata"); - - rb_cvar_set(cDigest_RMD160, id_metadata, - Data_Wrap_Struct(rb_cObject, 0, 0, &rmd160), Qtrue); -} diff --git a/ext/digest/sha1/.cvsignore b/ext/digest/sha1/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/digest/sha1/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/digest/sha1/MANIFEST b/ext/digest/sha1/MANIFEST deleted file mode 100644 index 99b83addfd..0000000000 --- a/ext/digest/sha1/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -extconf.rb -sha1.c -sha1.h -sha1hl.c -sha1init.c -depend diff --git a/ext/digest/sha1/depend b/ext/digest/sha1/depend deleted file mode 100644 index 31a5da06cf..0000000000 --- a/ext/digest/sha1/depend +++ /dev/null @@ -1,7 +0,0 @@ -sha1.o: sha1.c sha1.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h -sha1hl.o: sha1hl.c sha1.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h -sha1init.o: sha1init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h \ - sha1.h $(srcdir)/../defs.h diff --git a/ext/digest/sha1/extconf.rb b/ext/digest/sha1/extconf.rb deleted file mode 100644 index 45e374e369..0000000000 --- a/ext/digest/sha1/extconf.rb +++ /dev/null @@ -1,20 +0,0 @@ -# $RoughId: extconf.rb,v 1.3 2001/08/14 19:54:51 knu Exp $ -# $Id$ - -require "mkmf" - -$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.." - -$objs = [ - "sha1.#{$OBJEXT}", - "sha1hl.#{$OBJEXT}", - "sha1init.#{$OBJEXT}", -] - -have_header("sys/cdefs.h") - -have_header("inttypes.h") - -have_header("unistd.h") - -create_makefile("digest/sha1") diff --git a/ext/digest/sha1/sha1.c b/ext/digest/sha1/sha1.c deleted file mode 100644 index 1012ef8751..0000000000 --- a/ext/digest/sha1/sha1.c +++ /dev/null @@ -1,283 +0,0 @@ -/* $NetBSD: sha1.c,v 1.2 2001/03/22 09:51:48 agc Exp $ */ -/* $OpenBSD: sha1.c,v 1.9 1997/07/23 21:12:32 kstailey Exp $ */ -/* $RoughId: sha1.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */ -/* $Id$ */ - -/* - * SHA-1 in C - * By Steve Reid - * 100% Public Domain - * - * Test Vectors (from FIPS PUB 180-1) - * "abc" - * A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D - * "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - * 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 - * A million repetitions of "a" - * 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F - */ - -#include "sha1.h" - -#define SHA1HANDSOFF /* Copies data before messing with it. */ - -#if defined(_KERNEL) || defined(_STANDALONE) -#include -#include -#define _DIAGASSERT(x) (void)0 -#else -/* #include "namespace.h" */ -#include -#include -#endif - -#ifndef _DIAGASSERT -#define _DIAGASSERT(cond) assert(cond) -#endif - -/* - * XXX Kludge until there is resolution regarding mem*() functions - * XXX in the kernel. - */ -#if defined(_KERNEL) || defined(_STANDALONE) -#define memcpy(s, d, l) bcopy((d), (s), (l)) -#endif - -#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -/* - * blk0() and blk() perform the initial expand. - * I got the idea of expanding during the round function from SSLeay - */ -#ifndef WORDS_BIGENDIAN -# define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ - |(rol(block->l[i],8)&0x00FF00FF)) -#else -# define blk0(i) block->l[i] -#endif -#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ - ^block->l[(i+2)&15]^block->l[i&15],1)) - -/* - * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1 - */ -#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); -#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); -#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); - - -typedef union { - uint8_t c[64]; - uint32_t l[16]; -} CHAR64LONG16; - -#ifdef __sparc_v9__ -void do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *); -void do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *); -void do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *); -void do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *); - -#define nR0(v,w,x,y,z,i) R0(*v,*w,*x,*y,*z,i) -#define nR1(v,w,x,y,z,i) R1(*v,*w,*x,*y,*z,i) -#define nR2(v,w,x,y,z,i) R2(*v,*w,*x,*y,*z,i) -#define nR3(v,w,x,y,z,i) R3(*v,*w,*x,*y,*z,i) -#define nR4(v,w,x,y,z,i) R4(*v,*w,*x,*y,*z,i) - -void -do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block) -{ - nR0(a,b,c,d,e, 0); nR0(e,a,b,c,d, 1); nR0(d,e,a,b,c, 2); nR0(c,d,e,a,b, 3); - nR0(b,c,d,e,a, 4); nR0(a,b,c,d,e, 5); nR0(e,a,b,c,d, 6); nR0(d,e,a,b,c, 7); - nR0(c,d,e,a,b, 8); nR0(b,c,d,e,a, 9); nR0(a,b,c,d,e,10); nR0(e,a,b,c,d,11); - nR0(d,e,a,b,c,12); nR0(c,d,e,a,b,13); nR0(b,c,d,e,a,14); nR0(a,b,c,d,e,15); - nR1(e,a,b,c,d,16); nR1(d,e,a,b,c,17); nR1(c,d,e,a,b,18); nR1(b,c,d,e,a,19); -} - -void -do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block) -{ - nR2(a,b,c,d,e,20); nR2(e,a,b,c,d,21); nR2(d,e,a,b,c,22); nR2(c,d,e,a,b,23); - nR2(b,c,d,e,a,24); nR2(a,b,c,d,e,25); nR2(e,a,b,c,d,26); nR2(d,e,a,b,c,27); - nR2(c,d,e,a,b,28); nR2(b,c,d,e,a,29); nR2(a,b,c,d,e,30); nR2(e,a,b,c,d,31); - nR2(d,e,a,b,c,32); nR2(c,d,e,a,b,33); nR2(b,c,d,e,a,34); nR2(a,b,c,d,e,35); - nR2(e,a,b,c,d,36); nR2(d,e,a,b,c,37); nR2(c,d,e,a,b,38); nR2(b,c,d,e,a,39); -} - -void -do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block) -{ - nR3(a,b,c,d,e,40); nR3(e,a,b,c,d,41); nR3(d,e,a,b,c,42); nR3(c,d,e,a,b,43); - nR3(b,c,d,e,a,44); nR3(a,b,c,d,e,45); nR3(e,a,b,c,d,46); nR3(d,e,a,b,c,47); - nR3(c,d,e,a,b,48); nR3(b,c,d,e,a,49); nR3(a,b,c,d,e,50); nR3(e,a,b,c,d,51); - nR3(d,e,a,b,c,52); nR3(c,d,e,a,b,53); nR3(b,c,d,e,a,54); nR3(a,b,c,d,e,55); - nR3(e,a,b,c,d,56); nR3(d,e,a,b,c,57); nR3(c,d,e,a,b,58); nR3(b,c,d,e,a,59); -} - -void -do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block) -{ - nR4(a,b,c,d,e,60); nR4(e,a,b,c,d,61); nR4(d,e,a,b,c,62); nR4(c,d,e,a,b,63); - nR4(b,c,d,e,a,64); nR4(a,b,c,d,e,65); nR4(e,a,b,c,d,66); nR4(d,e,a,b,c,67); - nR4(c,d,e,a,b,68); nR4(b,c,d,e,a,69); nR4(a,b,c,d,e,70); nR4(e,a,b,c,d,71); - nR4(d,e,a,b,c,72); nR4(c,d,e,a,b,73); nR4(b,c,d,e,a,74); nR4(a,b,c,d,e,75); - nR4(e,a,b,c,d,76); nR4(d,e,a,b,c,77); nR4(c,d,e,a,b,78); nR4(b,c,d,e,a,79); -} -#endif - -/* - * Hash a single 512-bit block. This is the core of the algorithm. - */ -void SHA1_Transform(state, buffer) - uint32_t state[5]; - const uint8_t buffer[64]; -{ - uint32_t a, b, c, d, e; - CHAR64LONG16 *block; - -#ifdef SHA1HANDSOFF - CHAR64LONG16 workspace; -#endif - - _DIAGASSERT(buffer != 0); - _DIAGASSERT(state != 0); - -#ifdef SHA1HANDSOFF - block = &workspace; - (void)memcpy(block, buffer, 64); -#else - block = (CHAR64LONG16 *)(void *)buffer; -#endif - - /* Copy context->state[] to working vars */ - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - -#ifdef __sparc_v9__ - do_R01(&a, &b, &c, &d, &e, block); - do_R2(&a, &b, &c, &d, &e, block); - do_R3(&a, &b, &c, &d, &e, block); - do_R4(&a, &b, &c, &d, &e, block); -#else - /* 4 rounds of 20 operations each. Loop unrolled. */ - R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); - R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); - R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); - R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); - R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); - R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); - R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); - R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); - R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); - R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); - R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); - R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); - R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); - R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); - R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); - R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); - R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); - R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); - R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); - R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); -#endif - - /* Add the working vars back into context.state[] */ - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - - /* Wipe variables */ - a = b = c = d = e = 0; -} - - -/* - * SHA1_Init - Initialize new context - */ -void SHA1_Init(context) - SHA1_CTX *context; -{ - - _DIAGASSERT(context != 0); - - /* SHA1 initialization constants */ - context->state[0] = 0x67452301; - context->state[1] = 0xEFCDAB89; - context->state[2] = 0x98BADCFE; - context->state[3] = 0x10325476; - context->state[4] = 0xC3D2E1F0; - context->count[0] = context->count[1] = 0; -} - - -/* - * Run your data through this. - */ -void SHA1_Update(context, data, len) - SHA1_CTX *context; - const uint8_t *data; - size_t len; -{ - uint32_t i, j; - - _DIAGASSERT(context != 0); - _DIAGASSERT(data != 0); - - j = context->count[0]; - if ((context->count[0] += len << 3) < j) - context->count[1] += (len>>29)+1; - j = (j >> 3) & 63; - if ((j + len) > 63) { - (void)memcpy(&context->buffer[j], data, (i = 64-j)); - SHA1_Transform(context->state, context->buffer); - for ( ; i + 63 < len; i += 64) - SHA1_Transform(context->state, &data[i]); - j = 0; - } else { - i = 0; - } - (void)memcpy(&context->buffer[j], &data[i], len - i); -} - - -/* - * Add padding and return the message digest. - */ -void SHA1_Final(digest, context) - uint8_t digest[20]; - SHA1_CTX* context; -{ - size_t i; - uint8_t finalcount[8]; - - _DIAGASSERT(digest != 0); - _DIAGASSERT(context != 0); - - for (i = 0; i < 8; i++) { - finalcount[i] = (uint8_t)((context->count[(i >= 4 ? 0 : 1)] - >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ - } - SHA1_Update(context, (const uint8_t *)"\200", 1); - while ((context->count[0] & 504) != 448) - SHA1_Update(context, (const uint8_t *)"\0", 1); - SHA1_Update(context, finalcount, 8); /* Should cause a SHA1_Transform() */ - - if (digest) { - for (i = 0; i < 20; i++) - digest[i] = (uint8_t) - ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); - } -} - -int SHA1_Equal(SHA1_CTX* pctx1, SHA1_CTX* pctx2) { - return memcmp(pctx1->count, pctx2->count, sizeof(pctx1->count)) == 0 - && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0 - && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0; -} diff --git a/ext/digest/sha1/sha1.h b/ext/digest/sha1/sha1.h deleted file mode 100644 index 2303cecc2b..0000000000 --- a/ext/digest/sha1/sha1.h +++ /dev/null @@ -1,50 +0,0 @@ -/* $NetBSD: sha1.h,v 1.2 1998/05/29 22:55:44 thorpej Exp $ */ -/* $RoughId: sha1.h,v 1.3 2002/02/24 08:14:32 knu Exp $ */ -/* $Id$ */ - -/* - * SHA-1 in C - * By Steve Reid - * 100% Public Domain - */ - -#ifndef _SYS_SHA1_H_ -#define _SYS_SHA1_H_ - -#include "defs.h" - -typedef struct { - uint32_t state[5]; - uint32_t count[2]; - uint8_t buffer[64]; -} SHA1_CTX; - -#ifdef RUBY -#define SHA1_Transform rb_Digest_SHA1_Transform -#define SHA1_Init rb_Digest_SHA1_Init -#define SHA1_Update rb_Digest_SHA1_Update -#define SHA1_Final rb_Digest_SHA1_Final -#define SHA1_Equal rb_Digest_SHA1_Equal -#ifndef _KERNEL -#define SHA1_End rb_Digest_SHA1_End -#define SHA1_File rb_Digest_SHA1_File -#define SHA1_Data rb_Digest_SHA1_Data -#endif /* _KERNEL */ -#endif - -void SHA1_Transform _((uint32_t state[5], const uint8_t buffer[64])); -void SHA1_Init _((SHA1_CTX *context)); -void SHA1_Update _((SHA1_CTX *context, const uint8_t *data, size_t len)); -void SHA1_Final _((uint8_t digest[20], SHA1_CTX *context)); -int SHA1_Equal _((SHA1_CTX *pctx1, SHA1_CTX *pctx2)); -#ifndef _KERNEL -char *SHA1_End _((SHA1_CTX *, char *)); -char *SHA1_File _((char *, char *)); -char *SHA1_Data _((const uint8_t *, size_t, char *)); -#endif /* _KERNEL */ - -#define SHA1_BLOCK_LENGTH 64 -#define SHA1_DIGEST_LENGTH 20 -#define SHA1_DIGEST_STRING_LENGTH (SHA1_DIGEST_LENGTH * 2 + 1) - -#endif /* _SYS_SHA1_H_ */ diff --git a/ext/digest/sha1/sha1hl.c b/ext/digest/sha1/sha1hl.c deleted file mode 100644 index d1a236b22c..0000000000 --- a/ext/digest/sha1/sha1hl.c +++ /dev/null @@ -1,102 +0,0 @@ -/* $NetBSD: sha1hl.c,v 1.2 2001/03/10 15:55:14 tron Exp $ */ -/* $RoughId: sha1hl.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */ -/* $Id$ */ - -/* sha1hl.c - * ---------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * wrote this file. As long as you retain this notice you - * can do whatever you want with this stuff. If we meet some day, and you think - * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp - * ---------------------------------------------------------------------------- - */ - -/* #include "namespace.h" */ - -#include "sha1.h" -#include - -#include -#include -#include -#include -#if defined(HAVE_UNISTD_H) -# include -#endif - -#if defined(LIBC_SCCS) && !defined(lint) -/* __RCSID("$NetBSD: sha1hl.c,v 1.2 2001/03/10 15:55:14 tron Exp $"); */ -#endif /* LIBC_SCCS and not lint */ - -#ifndef _DIAGASSERT -#define _DIAGASSERT(cond) assert(cond) -#endif - - -/* ARGSUSED */ -char * -SHA1_End(ctx, buf) - SHA1_CTX *ctx; - char *buf; -{ - int i; - char *p = buf; - uint8_t digest[20]; - static const char hex[]="0123456789abcdef"; - - _DIAGASSERT(ctx != NULL); - /* buf may be NULL */ - - if (p == NULL && (p = malloc(41)) == NULL) - return 0; - - SHA1_Final(digest,ctx); - for (i = 0; i < 20; i++) { - p[i + i] = hex[((uint32_t)digest[i]) >> 4]; - p[i + i + 1] = hex[digest[i] & 0x0f]; - } - p[i + i] = '\0'; - return(p); -} - -char * -SHA1_File (filename, buf) - char *filename; - char *buf; -{ - uint8_t buffer[BUFSIZ]; - SHA1_CTX ctx; - int fd, num, oerrno; - - _DIAGASSERT(filename != NULL); - /* XXX: buf may be NULL ? */ - - SHA1_Init(&ctx); - - if ((fd = open(filename,O_RDONLY)) < 0) - return(0); - - while ((num = read(fd, buffer, sizeof(buffer))) > 0) - SHA1_Update(&ctx, buffer, (size_t)num); - - oerrno = errno; - close(fd); - errno = oerrno; - return(num < 0 ? 0 : SHA1_End(&ctx, buf)); -} - -char * -SHA1_Data (data, len, buf) - const uint8_t *data; - size_t len; - char *buf; -{ - SHA1_CTX ctx; - - _DIAGASSERT(data != NULL); - /* XXX: buf may be NULL ? */ - - SHA1_Init(&ctx); - SHA1_Update(&ctx, data, len); - return(SHA1_End(&ctx, buf)); -} diff --git a/ext/digest/sha1/sha1init.c b/ext/digest/sha1/sha1init.c deleted file mode 100644 index 70bc4f9f52..0000000000 --- a/ext/digest/sha1/sha1init.c +++ /dev/null @@ -1,34 +0,0 @@ -/* $RoughId: sha1init.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */ -/* $Id$ */ - -#include "digest.h" -#include "sha1.h" - -static algo_t sha1 = { - SHA1_DIGEST_LENGTH, - sizeof(SHA1_CTX), - (hash_init_func_t)SHA1_Init, - (hash_update_func_t)SHA1_Update, - (hash_end_func_t)SHA1_End, - (hash_final_func_t)SHA1_Final, - (hash_equal_func_t)SHA1_Equal, -}; - -void -Init_sha1() -{ - VALUE mDigest, cDigest_Base, cDigest_SHA1; - ID id_metadata; - - rb_require("digest.so"); - - mDigest = rb_path2class("Digest"); - cDigest_Base = rb_path2class("Digest::Base"); - - cDigest_SHA1 = rb_define_class_under(mDigest, "SHA1", cDigest_Base); - - id_metadata = rb_intern("metadata"); - - rb_cvar_set(cDigest_SHA1, id_metadata, - Data_Wrap_Struct(rb_cObject, 0, 0, &sha1), Qtrue); -} diff --git a/ext/digest/sha2/.cvsignore b/ext/digest/sha2/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/digest/sha2/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/digest/sha2/MANIFEST b/ext/digest/sha2/MANIFEST deleted file mode 100644 index f117b94771..0000000000 --- a/ext/digest/sha2/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -extconf.rb -sha2.c -sha2.h -sha2hl.c -sha2init.c -depend diff --git a/ext/digest/sha2/depend b/ext/digest/sha2/depend deleted file mode 100644 index 2587415fdc..0000000000 --- a/ext/digest/sha2/depend +++ /dev/null @@ -1,7 +0,0 @@ -sha2.o: sha2.c sha2.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h -sha2hl.o: sha2hl.c sha2.h $(srcdir)/../defs.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h -sha2init.o: sha2init.c $(srcdir)/../digest.h $(hdrdir)/ruby.h \ - $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/intern.h \ - sha2.h $(srcdir)/../defs.h diff --git a/ext/digest/sha2/extconf.rb b/ext/digest/sha2/extconf.rb deleted file mode 100644 index c982aa64de..0000000000 --- a/ext/digest/sha2/extconf.rb +++ /dev/null @@ -1,28 +0,0 @@ -# $RoughId: extconf.rb,v 1.4 2001/08/14 19:54:51 knu Exp $ -# $Id$ - -require "mkmf" - -$CFLAGS << " -DHAVE_CONFIG_H -I#{File.dirname(__FILE__)}/.." - -$objs = [ - "sha2.#{$OBJEXT}", - "sha2hl.#{$OBJEXT}", - "sha2init.#{$OBJEXT}", -] - -have_header("sys/cdefs.h") - -have_header("inttypes.h") - -have_header("unistd.h") - -if try_cpp(< - * - * Copyright 2000 Aaron D. Gifford. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holder nor the names of contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - */ - -/* $RoughId: sha2.c,v 1.3 2002/02/26 22:03:36 knu Exp $ */ -/* $Id$ */ - -#include -#include /* memcpy()/memset() or bcopy()/bzero() */ -#include /* assert() */ -#include "sha2.h" - -/* - * ASSERT NOTE: - * Some sanity checking code is included using assert(). On my FreeBSD - * system, this additional code can be removed by compiling with NDEBUG - * defined. Check your own systems manpage on assert() to see how to - * compile WITHOUT the sanity checking code on your system. - * - * UNROLLED TRANSFORM LOOP NOTE: - * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform - * loop version for the hash transform rounds (defined using macros - * later in this file). Either define on the command line, for example: - * - * cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c - * - * or define below: - * - * #define SHA2_UNROLL_TRANSFORM - * - */ - - -/*** SHA-256/384/512 Machine Architecture Definitions *****************/ -typedef uint8_t sha2_byte; /* Exactly 1 byte */ -typedef uint32_t sha2_word32; /* Exactly 4 bytes */ -typedef uint64_t sha2_word64; /* Exactly 8 bytes */ - -#if defined(__GNUC__) -#define ULL(number) number##ULL -#else -#define ULL(number) (uint64_t)(number) -#endif - - -/*** SHA-256/384/512 Various Length Definitions ***********************/ -/* NOTE: Most of these are in sha2.h */ -#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) -#define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16) -#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) - - -/*** ENDIAN REVERSAL MACROS *******************************************/ -#ifndef WORDS_BIGENDIAN -#define REVERSE32(w,x) { \ - sha2_word32 tmp = (w); \ - tmp = (tmp >> 16) | (tmp << 16); \ - (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ -} -#define REVERSE64(w,x) { \ - sha2_word64 tmp = (w); \ - tmp = (tmp >> 32) | (tmp << 32); \ - tmp = ((tmp & ULL(0xff00ff00ff00ff00)) >> 8) | \ - ((tmp & ULL(0x00ff00ff00ff00ff)) << 8); \ - (x) = ((tmp & ULL(0xffff0000ffff0000)) >> 16) | \ - ((tmp & ULL(0x0000ffff0000ffff)) << 16); \ -} -#endif - -/* - * Macro for incrementally adding the unsigned 64-bit integer n to the - * unsigned 128-bit integer (represented using a two-element array of - * 64-bit words): - */ -#define ADDINC128(w,n) { \ - (w)[0] += (sha2_word64)(n); \ - if ((w)[0] < (n)) { \ - (w)[1]++; \ - } \ -} - -/* - * Macros for copying blocks of memory and for zeroing out ranges - * of memory. Using these macros makes it easy to switch from - * using memset()/memcpy() and using bzero()/bcopy(). - * - * Please define either SHA2_USE_MEMSET_MEMCPY or define - * SHA2_USE_BZERO_BCOPY depending on which function set you - * choose to use: - */ -#if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY) -/* Default to memset()/memcpy() if no option is specified */ -#define SHA2_USE_MEMSET_MEMCPY 1 -#endif -#if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY) -/* Abort with an error if BOTH options are defined */ -#error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both! -#endif - -#ifdef SHA2_USE_MEMSET_MEMCPY -#define MEMSET_BZERO(p,l) memset((p), 0, (l)) -#define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l)) -#endif -#ifdef SHA2_USE_BZERO_BCOPY -#define MEMSET_BZERO(p,l) bzero((p), (l)) -#define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l)) -#endif - - -/*** THE SIX LOGICAL FUNCTIONS ****************************************/ -/* - * Bit shifting and rotation (used by the six SHA-XYZ logical functions: - * - * NOTE: The naming of R and S appears backwards here (R is a SHIFT and - * S is a ROTATION) because the SHA-256/384/512 description document - * (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this - * same "backwards" definition. - */ -/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */ -#define R(b,x) ((x) >> (b)) -/* 32-bit Rotate-right (used in SHA-256): */ -#define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b)))) -/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */ -#define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b)))) - -/* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */ -#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) -#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) - -/* Four of six logical functions used in SHA-256: */ -#define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) -#define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) -#define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x))) -#define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) - -/* Four of six logical functions used in SHA-384 and SHA-512: */ -#define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x))) -#define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x))) -#define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x))) -#define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x))) - -/*** INTERNAL FUNCTION PROTOTYPES *************************************/ -/* NOTE: These should not be accessed directly from outside this - * library -- they are intended for private internal visibility/use - * only. - */ -void SHA512_Last(SHA512_CTX*); -void SHA256_Transform(SHA256_CTX*, const sha2_word32*); -void SHA512_Transform(SHA512_CTX*, const sha2_word64*); - - -/*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/ -/* Hash constant words K for SHA-256: */ -const static sha2_word32 K256[64] = { - 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, - 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, - 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, - 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, - 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, - 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, - 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, - 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, - 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, - 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, - 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, - 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, - 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, - 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, - 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, - 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL -}; - -/* Initial hash value H for SHA-256: */ -const static sha2_word32 sha256_initial_hash_value[8] = { - 0x6a09e667UL, - 0xbb67ae85UL, - 0x3c6ef372UL, - 0xa54ff53aUL, - 0x510e527fUL, - 0x9b05688cUL, - 0x1f83d9abUL, - 0x5be0cd19UL -}; - -/* Hash constant words K for SHA-384 and SHA-512: */ -const static sha2_word64 K512[80] = { - ULL(0x428a2f98d728ae22), ULL(0x7137449123ef65cd), - ULL(0xb5c0fbcfec4d3b2f), ULL(0xe9b5dba58189dbbc), - ULL(0x3956c25bf348b538), ULL(0x59f111f1b605d019), - ULL(0x923f82a4af194f9b), ULL(0xab1c5ed5da6d8118), - ULL(0xd807aa98a3030242), ULL(0x12835b0145706fbe), - ULL(0x243185be4ee4b28c), ULL(0x550c7dc3d5ffb4e2), - ULL(0x72be5d74f27b896f), ULL(0x80deb1fe3b1696b1), - ULL(0x9bdc06a725c71235), ULL(0xc19bf174cf692694), - ULL(0xe49b69c19ef14ad2), ULL(0xefbe4786384f25e3), - ULL(0x0fc19dc68b8cd5b5), ULL(0x240ca1cc77ac9c65), - ULL(0x2de92c6f592b0275), ULL(0x4a7484aa6ea6e483), - ULL(0x5cb0a9dcbd41fbd4), ULL(0x76f988da831153b5), - ULL(0x983e5152ee66dfab), ULL(0xa831c66d2db43210), - ULL(0xb00327c898fb213f), ULL(0xbf597fc7beef0ee4), - ULL(0xc6e00bf33da88fc2), ULL(0xd5a79147930aa725), - ULL(0x06ca6351e003826f), ULL(0x142929670a0e6e70), - ULL(0x27b70a8546d22ffc), ULL(0x2e1b21385c26c926), - ULL(0x4d2c6dfc5ac42aed), ULL(0x53380d139d95b3df), - ULL(0x650a73548baf63de), ULL(0x766a0abb3c77b2a8), - ULL(0x81c2c92e47edaee6), ULL(0x92722c851482353b), - ULL(0xa2bfe8a14cf10364), ULL(0xa81a664bbc423001), - ULL(0xc24b8b70d0f89791), ULL(0xc76c51a30654be30), - ULL(0xd192e819d6ef5218), ULL(0xd69906245565a910), - ULL(0xf40e35855771202a), ULL(0x106aa07032bbd1b8), - ULL(0x19a4c116b8d2d0c8), ULL(0x1e376c085141ab53), - ULL(0x2748774cdf8eeb99), ULL(0x34b0bcb5e19b48a8), - ULL(0x391c0cb3c5c95a63), ULL(0x4ed8aa4ae3418acb), - ULL(0x5b9cca4f7763e373), ULL(0x682e6ff3d6b2b8a3), - ULL(0x748f82ee5defb2fc), ULL(0x78a5636f43172f60), - ULL(0x84c87814a1f0ab72), ULL(0x8cc702081a6439ec), - ULL(0x90befffa23631e28), ULL(0xa4506cebde82bde9), - ULL(0xbef9a3f7b2c67915), ULL(0xc67178f2e372532b), - ULL(0xca273eceea26619c), ULL(0xd186b8c721c0c207), - ULL(0xeada7dd6cde0eb1e), ULL(0xf57d4f7fee6ed178), - ULL(0x06f067aa72176fba), ULL(0x0a637dc5a2c898a6), - ULL(0x113f9804bef90dae), ULL(0x1b710b35131c471b), - ULL(0x28db77f523047d84), ULL(0x32caab7b40c72493), - ULL(0x3c9ebe0a15c9bebc), ULL(0x431d67c49c100d4c), - ULL(0x4cc5d4becb3e42b6), ULL(0x597f299cfc657e2a), - ULL(0x5fcb6fab3ad6faec), ULL(0x6c44198c4a475817) -}; - -/* Initial hash value H for SHA-384 */ -const static sha2_word64 sha384_initial_hash_value[8] = { - ULL(0xcbbb9d5dc1059ed8), - ULL(0x629a292a367cd507), - ULL(0x9159015a3070dd17), - ULL(0x152fecd8f70e5939), - ULL(0x67332667ffc00b31), - ULL(0x8eb44a8768581511), - ULL(0xdb0c2e0d64f98fa7), - ULL(0x47b5481dbefa4fa4) -}; - -/* Initial hash value H for SHA-512 */ -const static sha2_word64 sha512_initial_hash_value[8] = { - ULL(0x6a09e667f3bcc908), - ULL(0xbb67ae8584caa73b), - ULL(0x3c6ef372fe94f82b), - ULL(0xa54ff53a5f1d36f1), - ULL(0x510e527fade682d1), - ULL(0x9b05688c2b3e6c1f), - ULL(0x1f83d9abfb41bd6b), - ULL(0x5be0cd19137e2179) -}; - - -/*** SHA-256: *********************************************************/ -void SHA256_Init(SHA256_CTX* context) { - if (context == (SHA256_CTX*)0) { - return; - } - MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); - MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH); - context->bitcount = 0; -} - -#ifdef SHA2_UNROLL_TRANSFORM - -/* Unrolled SHA-256 round macros: */ - -#ifndef WORDS_BIGENDIAN - -#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ - REVERSE32(*data++, W256[j]); \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ - K256[j] + W256[j]; \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ - j++ - - -#else - -#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ - K256[j] + (W256[j] = *data++); \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ - j++ - -#endif - -#define ROUND256(a,b,c,d,e,f,g,h) \ - s0 = W256[(j+1)&0x0f]; \ - s0 = sigma0_256(s0); \ - s1 = W256[(j+14)&0x0f]; \ - s1 = sigma1_256(s1); \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \ - (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ - j++ - -void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { - sha2_word32 a, b, c, d, e, f, g, h, s0, s1; - sha2_word32 T1, *W256; - int j; - - W256 = (sha2_word32*)context->buffer; - - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; - - j = 0; - do { - /* Rounds 0 to 15 (unrolled): */ - ROUND256_0_TO_15(a,b,c,d,e,f,g,h); - ROUND256_0_TO_15(h,a,b,c,d,e,f,g); - ROUND256_0_TO_15(g,h,a,b,c,d,e,f); - ROUND256_0_TO_15(f,g,h,a,b,c,d,e); - ROUND256_0_TO_15(e,f,g,h,a,b,c,d); - ROUND256_0_TO_15(d,e,f,g,h,a,b,c); - ROUND256_0_TO_15(c,d,e,f,g,h,a,b); - ROUND256_0_TO_15(b,c,d,e,f,g,h,a); - } while (j < 16); - - /* Now for the remaining rounds to 64: */ - do { - ROUND256(a,b,c,d,e,f,g,h); - ROUND256(h,a,b,c,d,e,f,g); - ROUND256(g,h,a,b,c,d,e,f); - ROUND256(f,g,h,a,b,c,d,e); - ROUND256(e,f,g,h,a,b,c,d); - ROUND256(d,e,f,g,h,a,b,c); - ROUND256(c,d,e,f,g,h,a,b); - ROUND256(b,c,d,e,f,g,h,a); - } while (j < 64); - - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; - - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = 0; -} - -#else /* SHA2_UNROLL_TRANSFORM */ - -void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { - sha2_word32 a, b, c, d, e, f, g, h, s0, s1; - sha2_word32 T1, T2, *W256; - int j; - - W256 = (sha2_word32*)context->buffer; - - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; - - j = 0; - do { -#ifndef WORDS_BIGENDIAN - /* Copy data while converting to host byte order */ - REVERSE32(*data++,W256[j]); - /* Apply the SHA-256 compression function to update a..h */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; -#else - /* Apply the SHA-256 compression function to update a..h with copy */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); -#endif - T2 = Sigma0_256(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; - - j++; - } while (j < 16); - - do { - /* Part of the message block expansion: */ - s0 = W256[(j+1)&0x0f]; - s0 = sigma0_256(s0); - s1 = W256[(j+14)&0x0f]; - s1 = sigma1_256(s1); - - /* Apply the SHA-256 compression function to update a..h */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + - (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); - T2 = Sigma0_256(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; - - j++; - } while (j < 64); - - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; - - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = T2 = 0; -} - -#endif /* SHA2_UNROLL_TRANSFORM */ - -void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) { - unsigned int freespace, usedspace; - - if (len == 0) { - /* Calling with no data is valid - we do nothing */ - return; - } - - /* Sanity check: */ - assert(context != NULL && data != NULL); - - usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; - if (usedspace > 0) { - /* Calculate how much free space is available in the buffer */ - freespace = SHA256_BLOCK_LENGTH - usedspace; - - if (len >= freespace) { - /* Fill the buffer completely and process it */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); - context->bitcount += freespace << 3; - len -= freespace; - data += freespace; - SHA256_Transform(context, (sha2_word32*)context->buffer); - } else { - /* The buffer is not yet full */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, len); - context->bitcount += len << 3; - /* Clean up: */ - usedspace = freespace = 0; - return; - } - } - while (len >= SHA256_BLOCK_LENGTH) { - /* Process as many complete blocks as we can */ - SHA256_Transform(context, (const sha2_word32*)data); - context->bitcount += SHA256_BLOCK_LENGTH << 3; - len -= SHA256_BLOCK_LENGTH; - data += SHA256_BLOCK_LENGTH; - } - if (len > 0) { - /* There's left-overs, so save 'em */ - MEMCPY_BCOPY(context->buffer, data, len); - context->bitcount += len << 3; - } - /* Clean up: */ - usedspace = freespace = 0; -} - -void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) { - sha2_word32 *d = (sha2_word32*)digest; - unsigned int usedspace; - - /* Sanity check: */ - assert(context != NULL); - - /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; -#ifndef WORDS_BIGENDIAN - /* Convert FROM host byte order */ - REVERSE64(context->bitcount,context->bitcount); -#endif - if (usedspace > 0) { - /* Begin padding with a 1 bit: */ - context->buffer[usedspace++] = 0x80; - - if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { - /* Set-up for the last transform: */ - MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); - } else { - if (usedspace < SHA256_BLOCK_LENGTH) { - MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); - } - /* Do second-to-last transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); - - /* And set-up for the last transform: */ - MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); - } - } else { - /* Set-up for the last transform: */ - MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); - - /* Begin padding with a 1 bit: */ - *context->buffer = 0x80; - } - /* Set the bit count: */ - *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount; - - /* Final transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); - -#ifndef WORDS_BIGENDIAN - { - /* Convert TO host byte order */ - int j; - for (j = 0; j < 8; j++) { - REVERSE32(context->state[j],context->state[j]); - *d++ = context->state[j]; - } - } -#else - MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH); -#endif - } - - /* Clean up state data: */ - MEMSET_BZERO(context, sizeof(SHA256_CTX)); - usedspace = 0; -} - -int SHA256_Equal(SHA256_CTX* pctx1, SHA256_CTX* pctx2) { - return pctx1->bitcount == pctx2->bitcount - && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0 - && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0; -} - -/*** SHA-512: *********************************************************/ -void SHA512_Init(SHA512_CTX* context) { - if (context == (SHA512_CTX*)0) { - return; - } - MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); - MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); - context->bitcount[0] = context->bitcount[1] = 0; -} - -#ifdef SHA2_UNROLL_TRANSFORM - -/* Unrolled SHA-512 round macros: */ -#ifndef WORDS_BIGENDIAN - -#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ - REVERSE64(*data++, W512[j]); \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ - K512[j] + W512[j]; \ - (d) += T1, \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \ - j++ - - -#else - -#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ - K512[j] + (W512[j] = *data++); \ - (d) += T1; \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ - j++ - -#endif - -#define ROUND512(a,b,c,d,e,f,g,h) \ - s0 = W512[(j+1)&0x0f]; \ - s0 = sigma0_512(s0); \ - s1 = W512[(j+14)&0x0f]; \ - s1 = sigma1_512(s1); \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \ - (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \ - (d) += T1; \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ - j++ - -void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { - sha2_word64 a, b, c, d, e, f, g, h, s0, s1; - sha2_word64 T1, *W512 = (sha2_word64*)context->buffer; - int j; - - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; - - j = 0; - do { - ROUND512_0_TO_15(a,b,c,d,e,f,g,h); - ROUND512_0_TO_15(h,a,b,c,d,e,f,g); - ROUND512_0_TO_15(g,h,a,b,c,d,e,f); - ROUND512_0_TO_15(f,g,h,a,b,c,d,e); - ROUND512_0_TO_15(e,f,g,h,a,b,c,d); - ROUND512_0_TO_15(d,e,f,g,h,a,b,c); - ROUND512_0_TO_15(c,d,e,f,g,h,a,b); - ROUND512_0_TO_15(b,c,d,e,f,g,h,a); - } while (j < 16); - - /* Now for the remaining rounds up to 79: */ - do { - ROUND512(a,b,c,d,e,f,g,h); - ROUND512(h,a,b,c,d,e,f,g); - ROUND512(g,h,a,b,c,d,e,f); - ROUND512(f,g,h,a,b,c,d,e); - ROUND512(e,f,g,h,a,b,c,d); - ROUND512(d,e,f,g,h,a,b,c); - ROUND512(c,d,e,f,g,h,a,b); - ROUND512(b,c,d,e,f,g,h,a); - } while (j < 80); - - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; - - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = 0; -} - -#else /* SHA2_UNROLL_TRANSFORM */ - -void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { - sha2_word64 a, b, c, d, e, f, g, h, s0, s1; - sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer; - int j; - - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; - - j = 0; - do { -#ifndef WORDS_BIGENDIAN - /* Convert TO host byte order */ - REVERSE64(*data++, W512[j]); - /* Apply the SHA-512 compression function to update a..h */ - T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; -#else - /* Apply the SHA-512 compression function to update a..h with copy */ - T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++); -#endif - T2 = Sigma0_512(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; - - j++; - } while (j < 16); - - do { - /* Part of the message block expansion: */ - s0 = W512[(j+1)&0x0f]; - s0 = sigma0_512(s0); - s1 = W512[(j+14)&0x0f]; - s1 = sigma1_512(s1); - - /* Apply the SHA-512 compression function to update a..h */ - T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + - (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); - T2 = Sigma0_512(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; - - j++; - } while (j < 80); - - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; - - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = T2 = 0; -} - -#endif /* SHA2_UNROLL_TRANSFORM */ - -void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) { - unsigned int freespace, usedspace; - - if (len == 0) { - /* Calling with no data is valid - we do nothing */ - return; - } - - /* Sanity check: */ - assert(context != NULL && data != NULL); - - usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; - if (usedspace > 0) { - /* Calculate how much free space is available in the buffer */ - freespace = SHA512_BLOCK_LENGTH - usedspace; - - if (len >= freespace) { - /* Fill the buffer completely and process it */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); - ADDINC128(context->bitcount, freespace << 3); - len -= freespace; - data += freespace; - SHA512_Transform(context, (const sha2_word64*)context->buffer); - } else { - /* The buffer is not yet full */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, len); - ADDINC128(context->bitcount, len << 3); - /* Clean up: */ - usedspace = freespace = 0; - return; - } - } - while (len >= SHA512_BLOCK_LENGTH) { - /* Process as many complete blocks as we can */ - SHA512_Transform(context, (const sha2_word64*)data); - ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); - len -= SHA512_BLOCK_LENGTH; - data += SHA512_BLOCK_LENGTH; - } - if (len > 0) { - /* There's left-overs, so save 'em */ - MEMCPY_BCOPY(context->buffer, data, len); - ADDINC128(context->bitcount, len << 3); - } - /* Clean up: */ - usedspace = freespace = 0; -} - -void SHA512_Last(SHA512_CTX* context) { - unsigned int usedspace; - - usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; -#ifndef WORDS_BIGENDIAN - /* Convert FROM host byte order */ - REVERSE64(context->bitcount[0],context->bitcount[0]); - REVERSE64(context->bitcount[1],context->bitcount[1]); -#endif - if (usedspace > 0) { - /* Begin padding with a 1 bit: */ - context->buffer[usedspace++] = 0x80; - - if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { - /* Set-up for the last transform: */ - MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace); - } else { - if (usedspace < SHA512_BLOCK_LENGTH) { - MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace); - } - /* Do second-to-last transform: */ - SHA512_Transform(context, (const sha2_word64*)context->buffer); - - /* And set-up for the last transform: */ - MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2); - } - } else { - /* Prepare for final transform: */ - MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH); - - /* Begin padding with a 1 bit: */ - *context->buffer = 0x80; - } - /* Store the length of input data (in bits): */ - *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1]; - *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0]; - - /* Final transform: */ - SHA512_Transform(context, (const sha2_word64*)context->buffer); -} - -void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) { - sha2_word64 *d = (sha2_word64*)digest; - - /* Sanity check: */ - assert(context != NULL); - - /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - SHA512_Last(context); - - /* Save the hash data for output: */ -#ifndef WORDS_BIGENDIAN - { - /* Convert TO host byte order */ - int j; - for (j = 0; j < 8; j++) { - REVERSE64(context->state[j],context->state[j]); - *d++ = context->state[j]; - } - } -#else - MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH); -#endif - } - - /* Zero out state data */ - MEMSET_BZERO(context, sizeof(SHA512_CTX)); -} - -int SHA512_Equal(SHA512_CTX* pctx1, SHA512_CTX* pctx2) { - return memcmp(pctx1->bitcount, pctx2->bitcount, sizeof(pctx1->bitcount)) == 0 - && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0 - && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0; -} - -/*** SHA-384: *********************************************************/ -void SHA384_Init(SHA384_CTX* context) { - if (context == (SHA384_CTX*)0) { - return; - } - MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); - MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH); - context->bitcount[0] = context->bitcount[1] = 0; -} - -void SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) { - SHA512_Update((SHA512_CTX*)context, data, len); -} - -void SHA384_Final(sha2_byte digest[], SHA384_CTX* context) { - sha2_word64 *d = (sha2_word64*)digest; - - /* Sanity check: */ - assert(context != NULL); - - /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - SHA512_Last((SHA512_CTX*)context); - - /* Save the hash data for output: */ -#ifndef WORDS_BIGENDIAN - { - /* Convert TO host byte order */ - int j; - for (j = 0; j < 6; j++) { - REVERSE64(context->state[j],context->state[j]); - *d++ = context->state[j]; - } - } -#else - MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH); -#endif - } - - /* Zero out state data */ - MEMSET_BZERO(context, sizeof(SHA384_CTX)); -} - -int SHA384_Equal(SHA384_CTX* pctx1, SHA384_CTX* pctx2) { - return memcmp(pctx1->bitcount, pctx2->bitcount, sizeof(pctx1->bitcount)) == 0 - && memcmp(pctx1->state, pctx2->state, sizeof(pctx1->state)) == 0 - && memcmp(pctx1->buffer, pctx2->buffer, sizeof(pctx1->buffer)) == 0; -} diff --git a/ext/digest/sha2/sha2.h b/ext/digest/sha2/sha2.h deleted file mode 100644 index 4689ad93ce..0000000000 --- a/ext/digest/sha2/sha2.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * sha2.h - * - * Version 1.0.0beta1 - * - * Written by Aaron D. Gifford - * - * Copyright 2000 Aaron D. Gifford. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holder nor the names of contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - */ - -/* $RoughId: sha2.h,v 1.3 2002/02/24 08:14:32 knu Exp $ */ -/* $Id$ */ - -#ifndef __SHA2_H__ -#define __SHA2_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "defs.h" - - -/*** SHA-256/384/512 Various Length Definitions ***********************/ -#define SHA256_BLOCK_LENGTH 64 -#define SHA256_DIGEST_LENGTH 32 -#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) -#define SHA384_BLOCK_LENGTH 128 -#define SHA384_DIGEST_LENGTH 48 -#define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1) -#define SHA512_BLOCK_LENGTH 128 -#define SHA512_DIGEST_LENGTH 64 -#define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) - - -/*** SHA-256/384/512 Context Structures *******************************/ - -typedef struct _SHA256_CTX { - uint32_t state[8]; - uint64_t bitcount; - uint8_t buffer[SHA256_BLOCK_LENGTH]; -} SHA256_CTX; -typedef struct _SHA512_CTX { - uint64_t state[8]; - uint64_t bitcount[2]; - uint8_t buffer[SHA512_BLOCK_LENGTH]; -} SHA512_CTX; - -typedef SHA512_CTX SHA384_CTX; - - -#ifdef RUBY -#define SHA256_Init rb_Digest_SHA256_Init -#define SHA256_Update rb_Digest_SHA256_Update -#define SHA256_Final rb_Digest_SHA256_Final -#define SHA256_End rb_Digest_SHA256_End -#define SHA256_Data rb_Digest_SHA256_Data -#define SHA256_File rb_Digest_SHA256_File -#define SHA256_Equal rb_Digest_SHA256_Equal - -#define SHA384_Init rb_Digest_SHA384_Init -#define SHA384_Update rb_Digest_SHA384_Update -#define SHA384_Final rb_Digest_SHA384_Final -#define SHA384_End rb_Digest_SHA384_End -#define SHA384_Data rb_Digest_SHA384_Data -#define SHA384_File rb_Digest_SHA384_File -#define SHA384_Equal rb_Digest_SHA384_Equal - -#define SHA512_Init rb_Digest_SHA512_Init -#define SHA512_Update rb_Digest_SHA512_Update -#define SHA512_Final rb_Digest_SHA512_Final -#define SHA512_End rb_Digest_SHA512_End -#define SHA512_Data rb_Digest_SHA512_Data -#define SHA512_File rb_Digest_SHA512_File -#define SHA512_Equal rb_Digest_SHA512_Equal -#endif - -/*** SHA-256/384/512 Function Prototypes ******************************/ -void SHA256_Init _((SHA256_CTX *)); -void SHA256_Update _((SHA256_CTX*, const uint8_t*, size_t)); -void SHA256_Final _((uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*)); -char* SHA256_End _((SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH])); -char* SHA256_Data _((const uint8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH])); -char *SHA256_File _((char *, char *)); -int SHA256_Equal _((SHA256_CTX*, SHA256_CTX*)); - -void SHA384_Init _((SHA384_CTX*)); -void SHA384_Update _((SHA384_CTX*, const uint8_t*, size_t)); -void SHA384_Final _((uint8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*)); -char* SHA384_End _((SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH])); -char* SHA384_Data _((const uint8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH])); -char *SHA384_File _((char *, char *)); -int SHA384_Equal _((SHA384_CTX*, SHA384_CTX*)); - -void SHA512_Init _((SHA512_CTX*)); -void SHA512_Update _((SHA512_CTX*, const uint8_t*, size_t)); -void SHA512_Final _((uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*)); -char* SHA512_End _((SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH])); -char* SHA512_Data _((const uint8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH])); -char *SHA512_File _((char *, char *)); -int SHA512_Equal _((SHA512_CTX*, SHA512_CTX*)); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SHA2_H__ */ - diff --git a/ext/digest/sha2/sha2hl.c b/ext/digest/sha2/sha2hl.c deleted file mode 100644 index 03fde538c3..0000000000 --- a/ext/digest/sha2/sha2hl.c +++ /dev/null @@ -1,252 +0,0 @@ -/* $NetBSD: sha2hl.c,v 1.1 2001/03/12 09:08:40 agc Exp $ */ -/* $RoughId: sha2hl.c,v 1.2 2001/07/13 19:49:10 knu Exp $ */ -/* $Id$ */ - -/* - * sha2hl.c - * This code includes some functions taken from sha2.c, hence the - * following licence reproduction. - * - * This code is not a verbatim copy, since some routines have been added, - * and some bugs have been fixed. - * - * Version 1.0.0beta1 - * - * Written by Aaron D. Gifford - * - * Copyright 2000 Aaron D. Gifford. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holder nor the names of contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - */ - -#include "sha2.h" - -#ifndef lint -/* __RCSID("$NetBSD: sha2hl.c,v 1.1 2001/03/12 09:08:40 agc Exp $"); */ -#endif /* not lint */ - -/* #include "namespace.h" */ - -#include -#include -#include -#include -#include -#include -#if defined(HAVE_UNISTD_H) -# include -#endif - -#ifndef _DIAGASSERT -#define _DIAGASSERT(cond) assert(cond) -#endif - -/* - * Constant used by SHA256/384/512_End() functions for converting the - * digest to a readable hexadecimal character string: - */ -static const char sha2_hex_digits[] = "0123456789abcdef"; - -char * -SHA256_File(char *filename, char *buf) -{ - uint8_t buffer[BUFSIZ * 20]; - SHA256_CTX ctx; - int fd, num, oerrno; - - _DIAGASSERT(filename != NULL); - /* XXX: buf may be NULL ? */ - - SHA256_Init(&ctx); - - if ((fd = open(filename, O_RDONLY)) < 0) - return (0); - - while ((num = read(fd, buffer, sizeof(buffer))) > 0) - SHA256_Update(&ctx, buffer, (size_t) num); - - oerrno = errno; - close(fd); - errno = oerrno; - return (num < 0 ? 0 : SHA256_End(&ctx, buf)); -} - - -char * -SHA256_End(SHA256_CTX *ctx, char buffer[]) -{ - uint8_t digest[SHA256_DIGEST_LENGTH], *d = digest; - uint8_t *ret; - int i; - - /* Sanity check: */ - assert(ctx != NULL); - - if ((ret = buffer) != NULL) { - SHA256_Final(digest, ctx); - - for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { - *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; - *buffer++ = sha2_hex_digits[*d & 0x0f]; - d++; - } - *buffer = (char) 0; - } else { - (void) memset(ctx, 0, sizeof(SHA256_CTX)); - } - (void) memset(digest, 0, SHA256_DIGEST_LENGTH); - return ret; -} - -char * -SHA256_Data(const uint8_t * data, size_t len, char *digest) -{ - SHA256_CTX ctx; - - SHA256_Init(&ctx); - SHA256_Update(&ctx, data, len); - return SHA256_End(&ctx, digest); -} - -char * -SHA384_File(char *filename, char *buf) -{ - SHA384_CTX ctx; - uint8_t buffer[BUFSIZ * 20]; - int fd, num, oerrno; - - _DIAGASSERT(filename != NULL); - /* XXX: buf may be NULL ? */ - - SHA384_Init(&ctx); - - if ((fd = open(filename, O_RDONLY)) < 0) - return (0); - - while ((num = read(fd, buffer, sizeof(buffer))) > 0) - SHA384_Update(&ctx, buffer, (size_t) num); - - oerrno = errno; - close(fd); - errno = oerrno; - return (num < 0 ? 0 : SHA384_End(&ctx, buf)); -} - -char * -SHA384_End(SHA384_CTX * ctx, char buffer[]) -{ - uint8_t digest[SHA384_DIGEST_LENGTH], *d = digest; - uint8_t *ret; - int i; - - /* Sanity check: */ - assert(ctx != NULL); - - if ((ret = buffer) != NULL) { - SHA384_Final(digest, ctx); - - for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { - *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; - *buffer++ = sha2_hex_digits[*d & 0x0f]; - d++; - } - *buffer = (char) 0; - } else { - (void) memset(ctx, 0, sizeof(SHA384_CTX)); - } - (void) memset(digest, 0, SHA384_DIGEST_LENGTH); - return ret; -} - -char * -SHA384_Data(const uint8_t * data, size_t len, char *digest) -{ - SHA384_CTX ctx; - - SHA384_Init(&ctx); - SHA384_Update(&ctx, data, len); - return SHA384_End(&ctx, digest); -} - -char * -SHA512_File(char *filename, char *buf) -{ - SHA512_CTX ctx; - uint8_t buffer[BUFSIZ * 20]; - int fd, num, oerrno; - - _DIAGASSERT(filename != NULL); - /* XXX: buf may be NULL ? */ - - SHA512_Init(&ctx); - - if ((fd = open(filename, O_RDONLY)) < 0) - return (0); - - while ((num = read(fd, buffer, sizeof(buffer))) > 0) - SHA512_Update(&ctx, buffer, (size_t) num); - - oerrno = errno; - close(fd); - errno = oerrno; - return (num < 0 ? 0 : SHA512_End(&ctx, buf)); -} - -char * -SHA512_End(SHA512_CTX * ctx, char buffer[]) -{ - uint8_t digest[SHA512_DIGEST_LENGTH], *d = digest; - uint8_t *ret; - int i; - - /* Sanity check: */ - assert(ctx != NULL); - - if ((ret = buffer) != NULL) { - SHA512_Final(digest, ctx); - - for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { - *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; - *buffer++ = sha2_hex_digits[*d & 0x0f]; - d++; - } - *buffer = (char) 0; - } else { - (void) memset(ctx, 0, sizeof(SHA512_CTX)); - } - (void) memset(digest, 0, SHA512_DIGEST_LENGTH); - return ret; -} - -char * -SHA512_Data(const uint8_t * data, size_t len, char *digest) -{ - SHA512_CTX ctx; - - SHA512_Init(&ctx); - SHA512_Update(&ctx, data, len); - return SHA512_End(&ctx, digest); -} diff --git a/ext/digest/sha2/sha2init.c b/ext/digest/sha2/sha2init.c deleted file mode 100644 index 4b14031811..0000000000 --- a/ext/digest/sha2/sha2init.c +++ /dev/null @@ -1,47 +0,0 @@ -/* $RoughId: sha2init.c,v 1.3 2001/07/13 20:00:43 knu Exp $ */ -/* $Id$ */ - -#include "digest.h" -#include "sha2.h" - -#define FOREACH_BITLEN(func) func(256) func(384) func(512) - -#define DEFINE_ALGO_METADATA(bitlen) \ -static algo_t sha##bitlen = { \ - SHA##bitlen##_DIGEST_LENGTH, \ - sizeof(SHA##bitlen##_CTX), \ - (hash_init_func_t)SHA##bitlen##_Init, \ - (hash_update_func_t)SHA##bitlen##_Update, \ - (hash_end_func_t)SHA##bitlen##_End, \ - (hash_final_func_t)SHA##bitlen##_Final, \ - (hash_equal_func_t)SHA##bitlen##_Equal, \ -}; - -FOREACH_BITLEN(DEFINE_ALGO_METADATA) - -void -Init_sha2() -{ - VALUE mDigest, cDigest_Base; - ID id_metadata; - -#define DECLARE_ALGO_CLASS(bitlen) \ - VALUE cDigest_SHA##bitlen; - - FOREACH_BITLEN(DECLARE_ALGO_CLASS) - - rb_require("digest.so"); - - id_metadata = rb_intern("metadata"); - - mDigest = rb_path2class("Digest"); - cDigest_Base = rb_path2class("Digest::Base"); - -#define DEFINE_ALGO_CLASS(bitlen) \ - cDigest_SHA##bitlen = rb_define_class_under(mDigest, "SHA" #bitlen, cDigest_Base); \ -\ - rb_cvar_set(cDigest_SHA##bitlen, id_metadata, \ - Data_Wrap_Struct(rb_cObject, 0, 0, &sha##bitlen), Qtrue); - - FOREACH_BITLEN(DEFINE_ALGO_CLASS) -} diff --git a/ext/digest/test.rb b/ext/digest/test.rb deleted file mode 100644 index 2f29948bb6..0000000000 --- a/ext/digest/test.rb +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env ruby -# -# $RoughId: test.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ -# $Id$ - -require 'runit/testcase' -require 'runit/cui/testrunner' - -require 'digest/md5' -require 'digest/rmd160' -require 'digest/sha1' -require 'digest/sha2' -include Digest - -class TestDigest < RUNIT::TestCase - ALGOS = [ - MD5, - SHA1, - SHA256, - SHA384, - SHA512, - RMD160 - ] - - DATA = { - "abc" => { - MD5 => "900150983cd24fb0d6963f7d28e17f72", - SHA1 => "a9993e364706816aba3e25717850c26c9cd0d89d", - SHA256 => "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", - SHA384 => "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7", - SHA512 => "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", - RMD160 => "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc" - }, - - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" => { - MD5 => "8215ef0796a20bcaaae116d3876c664a", - SHA1 => "84983e441c3bd26ebaae4aa1f95129e5e54670f1", - SHA256 => "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", - SHA384 => "3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b", - SHA512 => "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445", - RMD160 => "12a053384a9c0c88e405a06c27dcf49ada62eb2b" - } - } - - def test_s_hexdigest - ALGOS.each do |algo| - DATA.each do |str, table| - assert_equal(table[algo], algo.hexdigest(str)) - end - end - end - - def test_s_digest - ALGOS.each do |algo| - DATA.each do |str, table| - assert_equal([table[algo]].pack("H*"), algo.digest(str)) - end - end - end - - def test_update - # This test is also for digest() and hexdigest() - - str = "ABC" - - ALGOS.each do |algo| - md = algo.new - md.update str - assert_equal(algo.hexdigest(str), md.hexdigest) - assert_equal(algo.digest(str), md.digest) - end - end - - def test_eq - # This test is also for clone() - - ALGOS.each do |algo| - md1 = algo.new("ABC") - - assert_equal(md1, md1.clone) - - md2 = algo.new - md2 << "A" - - assert(md1 != md2) - - md2 << "BC" - - assert_equal(md1, md2) - end - end -end - -if $0 == __FILE__ - suite = RUNIT::TestSuite.new - - suite.add_test(TestDigest.suite) - - RUNIT::CUI::TestRunner.run(suite) -end diff --git a/ext/digest/test.sh b/ext/digest/test.sh deleted file mode 100644 index 88b34b04c5..0000000000 --- a/ext/digest/test.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh -# -# $RoughId: test.sh,v 1.5 2001/07/13 15:38:27 knu Exp $ -# $Id$ - -RUBY=${RUBY:=ruby} -MAKE=${MAKE:=make} -CFLAGS=${CFLAGS:=-Wall} - -${RUBY} extconf.rb --with-cflags="${CFLAGS}" -${MAKE} clean -${MAKE} - -mkdir -p lib/digest - -for algo in md5 rmd160 sha1 sha2; do - (cd $algo && - ${RUBY} extconf.rb --with-cflags="${CFLAGS}"; - ${MAKE} clean; - ${MAKE}) - ln -sf ../../$algo/$algo.so lib/digest/ -done - -${RUBY} -I. -I./lib test.rb - -rm lib/digest/*.so -rmdir lib/digest diff --git a/ext/etc/.cvsignore b/ext/etc/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/etc/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/etc/MANIFEST b/ext/etc/MANIFEST deleted file mode 100644 index 62cf5be233..0000000000 --- a/ext/etc/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -MANIFEST -etc.c -etc.txt -etc.txt.ja -depend -extconf.rb diff --git a/ext/etc/depend b/ext/etc/depend deleted file mode 100644 index ac706477b0..0000000000 --- a/ext/etc/depend +++ /dev/null @@ -1 +0,0 @@ -etc.o : etc.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/etc/etc.c b/ext/etc/etc.c deleted file mode 100644 index 5c54237b7a..0000000000 --- a/ext/etc/etc.c +++ /dev/null @@ -1,276 +0,0 @@ -/************************************************ - - etc.c - - - $Author$ - $Date$ - created at: Tue Mar 22 18:39:19 JST 1994 - -************************************************/ - -#include "ruby.h" - -#include -#ifdef HAVE_UNISTD_H -#include -#endif - -#ifdef HAVE_GETPWENT -#include -#endif - -#ifdef HAVE_GETGRENT -#include -#endif - -static VALUE sPasswd, sGroup; - -static VALUE -etc_getlogin(obj) - VALUE obj; -{ - char *getenv(); - char *login; - -#ifdef HAVE_GETLOGIN - char *getlogin(); - - login = getlogin(); - if (!login) login = getenv("USER"); -#else - login = getenv("USER"); -#endif - - if (login) - return rb_tainted_str_new2(login); - return Qnil; -} - -#ifdef HAVE_GETPWENT -static VALUE -setup_passwd(pwd) - struct passwd *pwd; -{ - if (pwd == 0) rb_sys_fail("/etc/passwd"); - return rb_struct_new(sPasswd, - rb_tainted_str_new2(pwd->pw_name), - rb_tainted_str_new2(pwd->pw_passwd), - INT2FIX(pwd->pw_uid), - INT2FIX(pwd->pw_gid), -#ifdef PW_GECOS - rb_tainted_str_new2(pwd->pw_gecos), -#endif - rb_tainted_str_new2(pwd->pw_dir), - rb_tainted_str_new2(pwd->pw_shell), -#ifdef PW_CHANGE - INT2FIX(pwd->pw_change), -#endif -#ifdef PW_QUOTA - INT2FIX(pwd->pw_quota), -#endif -#ifdef PW_AGE - INT2FIX(pwd->pw_age), -#endif -#ifdef PW_CLASS - rb_tainted_str_new2(pwd->pw_class), -#endif -#ifdef PW_COMMENT - rb_tainted_str_new2(pwd->pw_comment), -#endif -#ifdef PW_EXPIRE - INT2FIX(pwd->pw_expire), -#endif - 0 /*dummy*/ - ); -} -#endif - -static VALUE -etc_getpwuid(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ -#ifdef HAVE_GETPWENT - VALUE id; - int uid; - struct passwd *pwd; - - if (rb_scan_args(argc, argv, "01", &id) == 1) { - uid = NUM2INT(id); - } - else { - uid = getuid(); - } - pwd = getpwuid(uid); - if (pwd == 0) rb_raise(rb_eArgError, "can't find user for %d", uid); - return setup_passwd(pwd); -#else - return Qnil; -#endif -} - -static VALUE -etc_getpwnam(obj, nam) - VALUE obj, nam; -{ -#ifdef HAVE_GETPWENT - struct passwd *pwd; - - StringValue(nam); - pwd = getpwnam(RSTRING(nam)->ptr); - if (pwd == 0) rb_raise(rb_eArgError, "can't find user for %s", RSTRING(nam)->ptr); - return setup_passwd(pwd); -#else - return Qnil; -#endif -} - -static VALUE -etc_passwd(obj) - VALUE obj; -{ -#ifdef HAVE_GETPWENT - struct passwd *pw; - - if (rb_block_given_p()) { - setpwent(); - while (pw = getpwent()) { - rb_yield(setup_passwd(pw)); - } - endpwent(); - return obj; - } - if (pw = getpwent()) { - return setup_passwd(pw); - } -#endif - return Qnil; -} - -#ifdef HAVE_GETGRENT -static VALUE -setup_group(grp) - struct group *grp; -{ - VALUE mem; - char **tbl; - - mem = rb_ary_new(); - tbl = grp->gr_mem; - while (*tbl) { - rb_ary_push(mem, rb_tainted_str_new2(*tbl)); - tbl++; - } - return rb_struct_new(sGroup, - rb_tainted_str_new2(grp->gr_name), - rb_tainted_str_new2(grp->gr_passwd), - INT2FIX(grp->gr_gid), - mem); -} -#endif - -static VALUE -etc_getgrgid(obj, id) - VALUE obj, id; -{ -#ifdef HAVE_GETGRENT - int gid; - struct group *grp; - - gid = NUM2INT(id); - grp = getgrgid(gid); - if (grp == 0) rb_raise(rb_eArgError, "can't find group for %d", gid); - return setup_group(grp); -#else - return Qnil; -#endif -} - -static VALUE -etc_getgrnam(obj, nam) - VALUE obj, nam; -{ -#ifdef HAVE_GETGRENT - struct group *grp; - - StringValue(nam); - grp = getgrnam(RSTRING(nam)->ptr); - if (grp == 0) rb_raise(rb_eArgError, "can't find group for %s", RSTRING(nam)->ptr); - return setup_group(grp); -#else - return Qnil; -#endif -} - -static VALUE -etc_group(obj) - VALUE obj; -{ -#ifdef HAVE_GETGRENT - struct group *grp; - - if (rb_block_given_p()) { - setgrent(); - while (grp = getgrent()) { - rb_yield(setup_group(grp)); - } - endgrent(); - return obj; - } - if (grp = getgrent()) { - return setup_group(grp); - } -#endif - return Qnil; -} - -static VALUE mEtc; - -void -Init_etc() -{ - mEtc = rb_define_module("Etc"); - - rb_define_module_function(mEtc, "getlogin", etc_getlogin, 0); - - rb_define_module_function(mEtc, "getpwuid", etc_getpwuid, -1); - rb_define_module_function(mEtc, "getpwnam", etc_getpwnam, 1); - rb_define_module_function(mEtc, "passwd", etc_passwd, 0); - - rb_define_module_function(mEtc, "getgrgid", etc_getgrgid, 1); - rb_define_module_function(mEtc, "getgrnam", etc_getgrnam, 1); - rb_define_module_function(mEtc, "group", etc_group, 0); - - sPasswd = rb_struct_define("Passwd", - "name", "passwd", "uid", "gid", -#ifdef PW_GECOS - "gecos", -#endif - "dir", "shell", -#ifdef PW_CHANGE - "change", -#endif -#ifdef PW_QUOTA - "quota", -#endif -#ifdef PW_AGE - "age", -#endif -#ifdef PW_CLASS - "class", -#endif -#ifdef PW_COMMENT - "comment", -#endif -#ifdef PW_EXPIRE - "expire", -#endif - 0); - rb_global_variable(&sPasswd); - -#ifdef HAVE_GETGRENT - sGroup = rb_struct_define("Group", "name", "passwd", "gid", "mem", 0); - rb_global_variable(&sGroup); -#endif -} diff --git a/ext/etc/etc.txt b/ext/etc/etc.txt deleted file mode 100644 index 534790172c..0000000000 --- a/ext/etc/etc.txt +++ /dev/null @@ -1,72 +0,0 @@ -.\" etc.txt - -*- Indented-Text -*- created at: Fri Jul 14 00:47:15 JST 1995 - -** Etc(Module) - -The module to retrieve information under /etc directory. Available -only on UNIX platforms. All operations defined in this module are -module functions, so that you can include Etc module into your class. - -Module Function: - - getlogin - - returns login name of the user. It this fails, try getpwuid(). - - getpwnam(name) - - searches in /etc/passwd file (or equivalent database), and - returns password entry for the user. The return value is an - passwd structure, which has members described below. - - struct passwd - name # user name(string) - passwd # encrypted password(string) - uid # user ID(integer) - gid # group ID(integer) - gecos # gecos field(string) - dir # home directory(string) - shell # login shell(string) - # members below are optional - change # password change time(integer) - quota # quota value(integer) - age # password age(integer) - class # user access class(string) - comment # comment(string) - expire # account expiration time(integer) - end - - See getpwnam(3) for detail. - - getpwuid([uid]) - - returns passwd entry for the specified user id. If uid is - ommitted, use the value from getuid(). See getpwuid(3) for - detail. - - getgrgid(gid) - - searches in /etc/group file (or equivalent database), and - returns group entry for the group id. The return value is an - group structure, which has members described below. - - struct group - name # group name(string) - passwd # group password(string) - gid # group ID(integer) - mem # array of the group member names - end - - See getgrgid(3) for detail. - - getgrnam(name) - - returns the group entry for the specified name. The return - value is the group structure. See getgrnam(3) for detail. - - group - - iterates over all group entries. - - passwd - - iterates over all passwd entries. diff --git a/ext/etc/etc.txt.ja b/ext/etc/etc.txt.ja deleted file mode 100644 index 2dddcfb036..0000000000 --- a/ext/etc/etc.txt.ja +++ /dev/null @@ -1,72 +0,0 @@ -.\" etc.txt.ja - -*- Indented-Text -*- created at: Fri Jul 14 00:47:15 JST 1995 - -** Etc(¥â¥¸¥å¡¼¥ë) - -/etc¥Ç¥£¥ì¥¯¥È¥ê°Ê²¼¤Î¾ðÊó¤òÆÀ¤ë¤¿¤á¤Î¥â¥¸¥å¡¼¥ë¡¥¥¯¥é¥¹¤Ë¥¤¥ó¥¯¥ë¡¼¥É -¤·¤Æ»È¤¦¤³¤È¤â¤Ç¤­¤ë¡¥ - -Module Function: - - getlogin - - ¼«Ê¬¤Îlogin̾¤òÊÖ¤¹¡¥¤³¤ì¤¬¼ºÇÔ¤·¤¿¾ì¹ç¤Ïgetpwuid()¤òÍѤ¤¤ë¤È - Îɤ¤¡¥ - - getpwnam(name) - - /etc/passwd¥Õ¥¡¥¤¥ë(¤¢¤ë¤¤¤ÏDBM¥Õ¥¡¥¤¥ë¤äNIS¥Ç¡¼¥¿¥Ù¡¼¥¹)¤ò¸¡ - º÷¤·¡¤name¤Î̾Á°¤ò»ý¤Äpasswd¥¨¥ó¥È¥ê¤òÊÖ¤¹¡¥Ìá¤êÃͤÏpasswd¹½Â¤ - ÂΤǰʲ¼¤Î¥á¥ó¥Ð¤ò»ý¤Ä¡¥ - - struct passwd - name # ¥æ¡¼¥¶Ì¾(ʸ»úÎó) - passwd # ¥Ñ¥¹¥ï¡¼¥É(ʸ»úÎó) - uid # ¥æ¡¼¥¶ID(À°¿ô) - gid # ¥°¥ë¡¼¥×ID(À°¿ô) - gecos # gecos¥Õ¥£¡¼¥ë¥É(ʸ»úÎó) - dir # ¥Û¡¼¥à¥Ç¥£¥ì¥¯¥È¥ê(ʸ»úÎó) - shell # ¥í¥°¥¤¥ó¥·¥§¥ë(ʸ»úÎó) - # °Ê¹ß¤Î¥á¥ó¥Ð¤Ï¥·¥¹¥Æ¥à¤Ë¤è¤Ã¤Æ¤ÏÄ󶡤µ¤ì¤Ê¤¤¡¥ - change # ¥Ñ¥¹¥ï¡¼¥ÉÊѹ¹»þ´Ö(À°¿ô) - quota # ¥¯¥©¡¼¥¿(À°¿ô) - age # ¥¨¡¼¥¸(À°¿ô) - class # ¥æ¡¼¥¶¥¢¥¯¥»¥¹¥¯¥é¥¹(ʸ»úÎó) - comment # ¥³¥á¥ó¥È(ʸ»úÎó) - expire # ¥¢¥«¥¦¥ó¥ÈÍ­¸ú´ü¸Â(À°¿ô) - end - - ¾ÜºÙ¤Ïgetpwnam(3)¤ò»²¾È¤Î¤³¤È¡¥ - - getpwuid([uid]) - - uid¤ò¥æ¡¼¥¶ID¤È¤¹¤ëpasswd¥¨¥ó¥È¥ê¤òÊÖ¤¹¡¥Ìá¤êÃͤÏgetpwnam()¤È - ƱÍͤǤ¢¤ë¡¥°ú¿ô¤ò¾Êά¤·¤¿¾ì¹ç¤Ë¤Ïgetuid()¤ÎÃͤòÍѤ¤¤ë¡¥¾ÜºÙ¤Ï - getpwuid(3)¤ò»²¾È¤Î¤³¤È¡¥ - - getgrgid(gid) - - /etc/group¥Õ¥¡¥¤¥ë(¤¢¤ë¤¤¤Ï¡Ägetpwnam»²¾È)¤ò¸¡º÷¤·¡¤gid¤ò¥°¥ë¡¼ - ¥×ID¤È¤¹¤ë¥°¥ë¡¼¥×¥¨¥ó¥È¥ê¤òÊÖ¤¹¡¥Ìá¤êÃͤÏgroup¹½Â¤ÂΤǰʲ¼¤Î - ¥á¥ó¥Ð¤ò»ý¤Ä¡¥ - - struct group - name # ¥°¥ë¡¼¥×̾(ʸ»úÎó) - passwd # ¥°¥ë¡¼¥×¤Î¥Ñ¥¹¥ï¡¼¥É(ʸ»úÎó) - gid # ¥°¥ë¡¼¥×ID(À°¿ô) - mem # ¥°¥ë¡¼¥×¥á¥ó¥Ð̾¤ÎÇÛÎó - end - - ¾ÜºÙ¤Ïgetgrgid(3)¤ò»²¾È¤Î¤³¤È¡¥ - - getgrnam(name) - - name¤È¤¤¤¦Ì¾Á°¤Î¥°¥ë¡¼¥×¥¨¥ó¥È¥ê¤òÊÖ¤¹¡¥Ìá¤êÃͤÏgetgrgid()¤ÈƱ - ÍͤǤ¢¤ë¡¥¾ÜºÙ¤Ïgetgrnam(3)¤ò»²¾È¡¥ - - group - - Á´¤Æ¤Î¥°¥ë¡¼¥×¥¨¥ó¥È¥ê¤ò½ç¤Ë¥¢¥¯¥»¥¹¤¹¤ë¤¿¤á¤Î¥¤¥Æ¥ì¡¼¥¿¡¥ - - passwd - - Á´¤Æ¤Îpasswd¥¨¥ó¥È¥ê¤ò½ç¤Ë¥¢¥¯¥»¥¹¤¹¤ë¤¿¤á¤Î¥¤¥Æ¥ì¡¼¥¿¡¥ diff --git a/ext/etc/extconf.rb b/ext/etc/extconf.rb deleted file mode 100644 index b920d91a95..0000000000 --- a/ext/etc/extconf.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'mkmf' - -def etc_grep_header(field) - if egrep_cpp(field, "#include \n") - $defs.push(format("-D%s", field.upcase)) - end -end - -have_library("sun", "getpwnam") # NIS (== YP) interface for IRIX 4 -a = have_func("getlogin") -b = have_func("getpwent") -c = have_func("getgrent") -if a or b or c - etc_grep_header("pw_gecos") - etc_grep_header("pw_change") - etc_grep_header("pw_quota") - etc_grep_header("pw_age") - etc_grep_header("pw_class") - etc_grep_header("pw_comment") unless /cygwin/ === RUBY_PLATFORM - etc_grep_header("pw_expire") - create_makefile("etc") -end diff --git a/ext/extmk.rb.in b/ext/extmk.rb.in deleted file mode 100644 index dd7cabfc98..0000000000 --- a/ext/extmk.rb.in +++ /dev/null @@ -1,780 +0,0 @@ -#! /usr/local/bin/ruby -# -*- ruby -*- - -$".push 'mkmf.rb' # " -ORIG_LIBPATH = ENV['LIB'] - -if ARGV[0] == 'static' - $force_static = true - ARGV.shift -elsif ARGV[0] == 'install' - $install = true - $destdir = ARGV[1] || '' - ARGV.shift -elsif ARGV[0] == 'clean' - $clean = "clean" - ARGV.shift -elsif ARGV[0] == 'distclean' - $clean = "distclean" - ARGV.shift -elsif ARGV[0] == 'realclean' - $clean = "realclean" - ARGV.shift -end - -SRC_EXT = ["c", "cc", "m", "cxx", "cpp", "C"] -$extlist = [] - -$includedir = "@includedir@" -$libdir = "@libdir@" - -$top_srcdir = "@top_srcdir@" -if $top_srcdir !~ "^/" - # get absolute path - $top_srcdir = File.expand_path($top_srcdir) -end -# get absolute path -$topdir = File.expand_path("..") - -$:.replace [$topdir, $top_srcdir, $top_srcdir+"/lib", "."] - -require 'rbconfig.rb' -require 'find' - -def rm_f(*files) - targets = [] - for file in files - targets.concat Dir[file] - end - if not targets.empty? - File::chmod(0777, *targets) - File::unlink(*targets) - end -end - -def older(file1, file2) - if !File.exist?(file1) then - return true - end - if !File.exist?(file2) then - return false - end - if File.mtime(file1) < File.mtime(file2) - return true - end - return false -end - -CFLAGS = "@CFLAGS@" -if RUBY_PLATFORM == "m68k-human" - CFLAGS.gsub!(/-c..-stack=[0-9]+ */, '') -end -if /mswin32/ =~ RUBY_PLATFORM - OUTFLAG = '-Fe' -else - OUTFLAG = '-o ' -end -LINK = "@CC@ #{OUTFLAG}conftest -I#$topdir -I#$top_srcdir #{CFLAGS} -I#$includedir @LDFLAGS@ %s %s %s conftest.c %s %s @LIBS@" -CPP = "@CPP@ @CPPFLAGS@ -I#$topdir -I#$top_srcdir #{CFLAGS} -I#$includedir %s %s %s conftest.c" - -$log = open('extmk.log', 'w') - -$orgerr = $stderr.dup -$orgout = $stdout.dup -def xsystem command - if $DEBUG - puts command - return system(command) - end - $stderr.reopen($log) - $stdout.reopen($log) - puts command - r = system(command) - $stderr.reopen($orgerr) - $stdout.reopen($orgout) - return r -end - -def try_link0(src, opt="") - cfile = open("conftest.c", "w") - cfile.print src - cfile.close - ldflags = $LDFLAGS - if /mswin32/ =~ RUBY_PLATFORM and !$LIBPATH.empty? - ENV['LIB'] = ($LIBPATH + [ORIG_LIBPATH]).compact.join(';') - else - ldflags = ldflags.dup - $LIBPATH.each {|d| ldflags << " -L" + d} - end - begin - xsystem(Config::expand(format(LINK, $CFLAGS, $CPPFLAGS, ldflags, opt, $LOCAL_LIBS))) - ensure - ENV['LIB'] = ORIG_LIBPATH if /mswin32/ =~ RUBY_PLATFORM - end -end - -def try_link(src, opt="") - begin - try_link0(src, opt) - ensure - rm_f "conftest*" - end -end - -def try_cpp(src, opt="") - cfile = open("conftest.c", "w") - cfile.print src - cfile.close - begin - xsystem(Config::expand(format(CPP, $CFLAGS, $CPPFLAGS, opt))) - ensure - rm_f "conftest*" - end -end - -def egrep_cpp(pat, src, opt="") - cfile = open("conftest.c", "w") - cfile.print src - cfile.close - begin - xsystem(Config::expand(format(CPP, $CFLAGS, $CPPFLAGS, opt))+"|egrep #{pat}") - ensure - rm_f "conftest*" - end -end - -def try_run(src, opt="") - begin - if try_link0(src, opt) - if xsystem("./conftest") - true - else - false - end - else - nil - end - ensure - rm_f "conftest*" - end -end - -def install_rb(mfile, srcdir = nil) - libdir = "lib" - libdir = srcdir + "/" + libdir if srcdir - path = [] - dir = [] - if File.directory? libdir - Find.find(libdir) do |f| - next unless /\.rb$/ =~ f - f = f[libdir.length+1..-1] - path.push f - dir |= [File.dirname(f)] - end - end - for f in dir - if f == "." - mfile.print "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(DESTDIR)$(pkglibdir)$(target_prefix)\n" - else - mfile.printf "\t@$(RUBY) -r ftools -e 'File::makedirs(*ARGV)' $(DESTDIR)$(pkglibdir)$(target_prefix)/%s\n", f - end - end - for f in path - mfile.printf "\t@$(RUBY) -r ftools -e 'File::install(ARGV[0], ARGV[1], 0644, true)' $(srcdir)/lib/%s $(DESTDIR)$(pkglibdir)$(target_prefix)/%s\n", f, f - end -end - -def append_library(libs, lib) - if /mswin32/ =~ RUBY_PLATFORM - lib + ".lib " + libs - else - "-l" + lib + " " + libs - end -end - -def have_library(lib, func="main") - if func && func != "" - libs = append_library($libs, lib) - if /mswin32|mingw/ =~ RUBY_PLATFORM - return true if lib == 'm' - r = try_link(<<"SRC", libs) -#include -#include -int main() { return 0; } -int t() { #{func}(); return 0; } -SRC - unless r - r = try_link(<<"SRC", libs) -#include -#include -int main() { return 0; } -int t() { void ((*p)()); p = (void ((*)()))#{func}; return 0; } -SRC - end - else - r = try_link(<<"SRC", libs) -int main() { return 0; } -int t() { #{func}(); return 0; } -SRC - end - unless r - return false - end - else - libs = append_library($libs, lib) - end - - $libs = libs - return true -end - -def find_library(lib, func, *paths) - libpath = $LIBPATH - libs = append_library($libs, lib) - until try_link(<<"SRC", libs) -int main() { return 0; } -int t() { #{func}(); return 0; } -SRC - if paths.size == 0 - $LIBPATH = libpath - return false - end - $LIBPATH = libpath | [paths.shift] - end - $libs = libs - return true -end - -def have_func(func, header=nil) - libs = $libs - src = - if /mswin32|mingw/ =~ RUBY_PLATFORM - r = <<"SRC" -#include -#include -SRC - else - "" - end - unless header.nil? - src << <<"SRC" -#include <#{header}> -SRC - end - r = try_link(src + <<"SRC", libs) -int main() { return 0; } -int t() { #{func}(); return 0; } -SRC - unless r - r = try_link(src + <<"SRC", libs) -int main() { return 0; } -int t() { void ((*p)()); p = (void ((*)()))#{func}; return 0; } -SRC - end - unless r - return false - end - $defs.push(format("-DHAVE_%s", func.upcase)) - return true -end - -def have_header(header) - unless try_cpp(<<"SRC") -#include <#{header}> -SRC - return false - end - $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___"))) - return true -end - -def arg_config(config, default=nil) - unless defined? $configure_args - $configure_args = {} - args = "@configure_args@" - if /mswin32|mingw/ =~ RUBY_PLATFORM and ENV["CONFIGURE_ARGS"] - args << " " << ENV["CONFIGURE_ARGS"] - end - for arg in args.split - next unless /^--/ =~ arg - arg, val = arg.split('=', 2) - $configure_args[arg] = val || true - end - end - $configure_args.fetch(config, default) -end - -def with_config(config, default=nil) - unless /^--with-/ =~ config - config = '--with-' + config - end - arg_config(config, default) -end - -def enable_config(config, default=nil) - if arg_config("--enable-"+config, default) - true - elsif arg_config("--disable-"+config, false) - false - else - default - end -end - -def create_header() - if $defs.length > 0 - hfile = open("extconf.h", "w") - for line in $defs - line =~ /^-D(.*)/ - hfile.printf "#define %s 1\n", $1 - end - hfile.close - end -end - -def dir_config(target, idefault=nil, ldefault=nil) - if dir = with_config(target + "-dir", (idefault unless ldefault)) - idefault = dir + "/include" - ldefault = dir + "/lib" - end - - idir = with_config(target + "-include", idefault) - ldir = with_config(target + "-lib", ldefault) - - if idir - idircflag = "-I" + idir - $CPPFLAGS += " " + idircflag unless $CPPFLAGS.split.include?(idircflag) - end - - if ldir - $LIBPATH << ldir unless $LIBPATH.include?(ldir) - end - - [idir, ldir] -end - -def create_makefile(target) - $target = target - if target.include?('/') - target_prefix, target = File.split(target) - target_prefix[0,0] = '/' - else - target_prefix = "" - end - rm_f "conftest*" - if "@DLEXT@" == $OBJEXT - libs = $libs.split - for lib in libs - lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%) - end - $defs.push(format("-DEXTLIB='%s'", libs.join(","))) - end - - $DLDFLAGS = '@DLDFLAGS@' - - if $configure_args['--enable-shared'] or "@LIBRUBY@" != "@LIBRUBY_A@" - $libs = "@LIBRUBYARG@ " + $libs - $LIBPATH.unshift $topdir - end - - defflag = '' - if RUBY_PLATFORM =~ /cygwin|mingw/ and not $static - if not File.exist? target + '.def' - open(target + '.def', 'wb') do |f| - f.print "EXPORTS\n", "Init_", target, "\n" - end - end - defflag = "--def=" + target + ".def" - end - - if RUBY_PLATFORM =~ /mswin32/ - libpath = $LIBPATH.join(';') - else - $LIBPATH.each {|d| $DLDFLAGS << " -L" << d} - if /netbsdelf/ =~ RUBY_PLATFORM - $LIBPATH.each {|d| $DLDFLAGS << " -Wl,-R" + d unless d == $topdir} - end - end - - $srcdir = $top_srcdir + "/ext/" + $mdir - mfile = open("Makefile", "w") - mfile.binmode if /mingw/ =~ RUBY_PLATFORM - mfile.printf "\ -SHELL = /bin/sh - -#### Start of system configuration section. #### - -srcdir = #{$srcdir} -VPATH = #{$srcdir} - -topdir = #{$topdir} -hdrdir = #{$top_srcdir} - -CC = @CC@ - -CFLAGS = %s #{CFLAGS} #$CFLAGS -CPPFLAGS = -I$(topdir) -I$(hdrdir) -I@includedir@ %s #$CPPFLAGS -DLDFLAGS = #$DLDFLAGS #$LDFLAGS -LDSHARED = @LDSHARED@ #{defflag} -", if $static then "" else "@CCDLFLAGS@" end, $defs.join(" ") - mfile.puts "LIBPATH = #{libpath}" if libpath - - mfile.puts ".SUFFIXES: .@OBJEXT@" unless "@OBJEXT@" == "o" - - mfile.printf "\ - -RUBY_INSTALL_NAME = @RUBY_INSTALL_NAME@ -RUBY_SO_NAME = @RUBY_SO_NAME@ - -prefix = @prefix@ -exec_prefix = @exec_prefix@ -libdir = @libdir@ -#pkglibdir = $(libdir)/$(RUBY_INSTALL_NAME)/@MAJOR@.@MINOR@ -pkglibdir = $(libdir)/ruby/@MAJOR@.@MINOR@ -archdir = $(pkglibdir)/@arch@ -target_prefix = #{target_prefix} -@SET_MAKE@ - -#### End of system configuration section. #### - -" - mfile.printf "LOCAL_LIBS = %s %s\n", $LOCAL_LIBS, $local_flags - mfile.printf "LIBS = %s\n", $libs - mfile.printf "OBJS = " - if !$objs then - $objs = [] - for f in Dir["#{$top_srcdir}/ext/#{$mdir}/*.{#{SRC_EXT.join(%q{,})}}"] - f = File.basename(f) - f.sub!(/(#{SRC_EXT.join(%q{|})})$/, $OBJEXT) - $objs.push f - end - else - for i in $objs - i.sub!(/\.o\z/, ".#{$OBJEXT}") - end - end - mfile.printf $objs.join(" ") - mfile.printf "\n" - - ruby_interpreter = "$(topdir)/miniruby@EXEEXT@" - if /nmake/i =~ $make - ruby_interpreter = '$(topdir:/=\)\miniruby@EXEEXT@' - end - if defined? CROSS_COMPILING - ruby_interpreter = "@MINIRUBY@" - end - - mfile.printf < /dev/null || true -" - end - elsif "@DLEXT@" != $OBJEXT - mfile.print "$(DLLIB): $(OBJS)\n" - if /mswin32/ =~ RUBY_PLATFORM - if /nmake/i =~ $make - mfile.print "\tset LIB=$(LIBPATH:/=\\);$(LIB)\n" - else - mfile.print "\tenv LIB='$(subst /,\\\\,$(LIBPATH));$(LIB)' \\\n" - end - end - mfile.print "\t$(LDSHARED) $(DLDFLAGS) #{OUTFLAG}$(DLLIB) $(OBJS) $(LIBS) $(LOCAL_LIBS)\n" - elsif RUBY_PLATFORM == "m68k-human" - mfile.printf "\ -$(DLLIB): $(OBJS) - ar cru $(DLLIB) $(OBJS) -" - else - mfile.printf "\ -$(DLLIB): $(OBJS) - ld $(DLDFLAGS) -r -o $(DLLIB) $(OBJS) -" - end - - if File.exist?("#{$srcdir}/depend") - dfile = open("#{$srcdir}/depend", "r") - mfile.printf "###\n" - while line = dfile.gets() - line.gsub!(/\.o\b/, ".#{$OBJEXT}") - line.gsub!(/(\s)([^\s\/]+\.[ch])/, '\1$(srcdir)/\2') if /nmake/i =~ $make - mfile.printf "%s", line.gsub('\$\(hdrdir\)/config.h', '$(topdir)/config.h') - end - dfile.close - end - mfile.close -end - -def extmake(target) - if $force_static or $static_ext[target] - $static = target - else - $static = false - end - - unless $install or $clean - return if $nodynamic and not $static - end - - $OBJEXT = "@OBJEXT@" - $LIBEXT = "a" - $objs = nil - $libs = "@DLDLIBS@" - $local_flags = "" - if /mswin32/ =~ RUBY_PLATFORM - $LIBEXT = "lib" - $local_flags = "-link /INCREMENTAL:no /EXPORT:Init_$(TARGET)" - end - $LOCAL_LIBS = "" # to be assigned in extconf.rb - $CFLAGS = "" - $CPPFLAGS = "@CPPFLAGS@" - $LDFLAGS = "" - $LIBPATH = [$libdir] - - dir_config("opt") - - begin - dir = Dir.pwd - Dir.mkdir target unless File.directory?(target) - Dir.chdir target - $target = target - $mdir = target - unless $install or $clean - if $static_ext.size > 0 || - !File.exist?("./Makefile") || - older("./Makefile", "#{$top_srcdir}/ext/@setup@") || - older("./Makefile", "#{$topdir}/ext/extmk.rb") || - older("./Makefile", "#{$top_srcdir}/ext/#{target}/makefile.rb") || - older("./Makefile", "#{$top_srcdir}/ext/#{target}/extconf.rb") - then - $defs = [] - if File.exist?("#{$top_srcdir}/ext/#{target}/makefile.rb") - load "#{$top_srcdir}/ext/#{target}/makefile.rb" - elsif File.exist?("#{$top_srcdir}/ext/#{target}/extconf.rb") - load "#{$top_srcdir}/ext/#{target}/extconf.rb" - else - create_makefile(target) - end - end - end - if File.exist?("./Makefile") - if $static - $extlist.push [$static, File.basename($target)] - end - if $install - system "#{$make} install DESTDIR=#{$destdir}" - elsif $clean - system "#{$make} #{$clean}" - else - unless system "#{$make} all" - if ENV["MAKEFLAGS"] != "k" and ENV["MFLAGS"] != "-k" - exit - end - end - end - end - if $static - $extlibs ||= "" - $extlibs += " " + $LDFLAGS unless $LDFLAGS == "" - $extlibs += " " + $libs unless $libs == "" - $extlibs += " " + $LOCAL_LIBS unless $LOCAL_LIBS == "" - end - ensure - rm_f "conftest*" - Dir.chdir dir - end -end - -$make = ENV["MAKE"] -$make ||= with_config("make-prog", "make") - -# get static-link modules -$static_ext = {} -for setup in ["@setup@", "#{$top_srcdir}/ext/@setup@"] - if File.file? setup - f = open(setup) - while line = f.gets() - line.chomp! - line.sub!(/#.*$/, '') - next if /^\s*$/ =~ line - if /^option +nodynamic/ =~ line - $nodynamic = true - next - end - target = line.split[0] - target = target.downcase if /mswin32/ =~ RUBY_PLATFORM - $static_ext[target] = true - end - f.close - break - end -end - -ext_prefix = "#{$top_srcdir}/ext" -for d in Dir["#{ext_prefix}/**/*"] - File.directory?(d) || next - File.file?(d + "/MANIFEST") || next - - d.slice!(0, ext_prefix.length + 1) - if $install - print "installing ", d, "\n" - elsif $clean - print "cleaning ", d, "\n" - else - print "compiling ", d, "\n" - if RUBY_PLATFORM =~ /-aix/ and older("../ruby.imp", "../miniruby") - load "#{$top_srcdir}/ext/aix_mksym.rb" - end - end - extmake(d) -end - -if $install or $clean - Dir.chdir ".." - exit -end -$extinit = "" unless $extinit - -ruby = "@RUBY_INSTALL_NAME@@EXEEXT@" -miniruby = "miniruby@EXEEXT@" - -$extobjs = "" unless $extobjs -if $extlist.size > 0 - for s,t in $extlist - f = format("%s/%s.%s", s, t, $LIBEXT) - if File.exist?(f) - $extinit += format("\ -\tInit_%s();\n\ -\trb_provide(\"%s\");\n\ -", t, s) - $extobjs += "ext/" - $extobjs += f - $extobjs += " " - else - false - end - end - - if older("extinit.c", "#{$top_srcdir}/ext/@setup@") - f = open("extinit.c", "w") - f.printf "void Init_ext() {\n" - f.printf $extinit - f.printf "}\n" - f.close - end - if older("extinit.#{$OBJEXT}", "extinit.c") - cmd = "@CC@ " + CFLAGS + " -c extinit.c" - print cmd, "\n" - system cmd or exit 1 - end - - Dir.chdir ".." - - if older(ruby, "#{$top_srcdir}/ext/@setup@") or older(ruby, miniruby) - rm_f ruby - end - - $extobjs = "ext/extinit.#{$OBJEXT} " + $extobjs - if RUBY_PLATFORM =~ /m68k-human|beos/ - $extlibs.gsub!("-L/usr/local/lib", "") if $extlibs - end - system format(%[#{$make} #{ruby} EXTOBJS='%s' EXTLIBS='%s'], $extobjs, $extlibs) -else - Dir.chdir ".." - if older(ruby, miniruby) - rm_f ruby - system("#{$make} #{ruby}") - end -end - -#Local variables: -# mode: ruby -#end: diff --git a/ext/fcntl/.cvsignore b/ext/fcntl/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/fcntl/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/fcntl/MANIFEST b/ext/fcntl/MANIFEST deleted file mode 100644 index aef7ad4ca0..0000000000 --- a/ext/fcntl/MANIFEST +++ /dev/null @@ -1,3 +0,0 @@ -MANIFEST -depend -fcntl.c diff --git a/ext/fcntl/depend b/ext/fcntl/depend deleted file mode 100644 index 10eab64a46..0000000000 --- a/ext/fcntl/depend +++ /dev/null @@ -1 +0,0 @@ -fcntl.o: fcntl.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/fcntl/fcntl.c b/ext/fcntl/fcntl.c deleted file mode 100644 index de0b284b36..0000000000 --- a/ext/fcntl/fcntl.c +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************ - - fcntl.c - - - $Author$ - created at: Mon Apr 7 18:53:05 JST 1997 - - Copyright (C) 1997-2001 Yukihiro Matsumoto - -************************************************/ - -/************************************************ -= NAME - -fcntl - load the C fcntl.h defines - -= SYNOPSIS - - require "fcntl" - m = s.fcntl(Fcntl::F_GETFL, 0) - f.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK|m) - -= DESCRIPTION - -This module is just a translation of the C file. - -= NOTE - -Only #define symbols get translated; you must still correctly -pack up your own arguments to pass as args for locking functions, etc. - -************************************************/ - -#include "ruby.h" -#include - -void -Init_fcntl() -{ - VALUE mFcntl = rb_define_module("Fcntl"); -#ifdef F_DUPFD - rb_define_const(mFcntl, "F_DUPFD", INT2NUM(F_DUPFD)); -#endif -#ifdef F_GETFD - rb_define_const(mFcntl, "F_GETFD", INT2NUM(F_GETFD)); -#endif -#ifdef F_GETLK - rb_define_const(mFcntl, "F_GETLK", INT2NUM(F_GETLK)); -#endif -#ifdef F_SETFD - rb_define_const(mFcntl, "F_SETFD", INT2NUM(F_SETFD)); -#endif -#ifdef F_GETFL - rb_define_const(mFcntl, "F_GETFL", INT2NUM(F_GETFL)); -#endif -#ifdef F_SETFL - rb_define_const(mFcntl, "F_SETFL", INT2NUM(F_SETFL)); -#endif -#ifdef F_SETLK - rb_define_const(mFcntl, "F_SETLK", INT2NUM(F_SETLK)); -#endif -#ifdef F_SETLKW - rb_define_const(mFcntl, "F_SETLKW", INT2NUM(F_SETLKW)); -#endif -#ifdef FD_CLOEXEC - rb_define_const(mFcntl, "FD_CLOEXEC", INT2NUM(FD_CLOEXEC)); -#endif -#ifdef F_RDLCK - rb_define_const(mFcntl, "F_RDLCK", INT2NUM(F_RDLCK)); -#endif -#ifdef F_UNLCK - rb_define_const(mFcntl, "F_UNLCK", INT2NUM(F_UNLCK)); -#endif -#ifdef F_WRLCK - rb_define_const(mFcntl, "F_WRLCK", INT2NUM(F_WRLCK)); -#endif -#ifdef O_CREAT - rb_define_const(mFcntl, "O_CREAT", INT2NUM(O_CREAT)); -#endif -#ifdef O_EXCL - rb_define_const(mFcntl, "O_EXCL", INT2NUM(O_EXCL)); -#endif -#ifdef O_NOCTTY - rb_define_const(mFcntl, "O_NOCTTY", INT2NUM(O_NOCTTY)); -#endif -#ifdef O_TRUNC - rb_define_const(mFcntl, "O_TRUNC", INT2NUM(O_TRUNC)); -#endif -#ifdef O_APPEND - rb_define_const(mFcntl, "O_APPEND", INT2NUM(O_APPEND)); -#endif -#ifdef O_NONBLOCK - rb_define_const(mFcntl, "O_NONBLOCK", INT2NUM(O_NONBLOCK)); -#endif -#ifdef O_NDELAY - rb_define_const(mFcntl, "O_NDELAY", INT2NUM(O_NDELAY)); -#endif -#ifdef O_RDONLY - rb_define_const(mFcntl, "O_RDONLY", INT2NUM(O_RDONLY)); -#endif -#ifdef O_RDWR - rb_define_const(mFcntl, "O_RDWR", INT2NUM(O_RDWR)); -#endif -#ifdef O_WRONLY - rb_define_const(mFcntl, "O_WRONLY", INT2NUM(O_WRONLY)); -#endif -} diff --git a/ext/gdbm/.cvsignore b/ext/gdbm/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/gdbm/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/gdbm/MANIFEST b/ext/gdbm/MANIFEST deleted file mode 100644 index 1359b4fdaf..0000000000 --- a/ext/gdbm/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -MANIFEST -README -depend -extconf.rb -gdbm.c -testgdbm.rb diff --git a/ext/gdbm/README b/ext/gdbm/README deleted file mode 100644 index df7a261c68..0000000000 --- a/ext/gdbm/README +++ /dev/null @@ -1 +0,0 @@ -gdbm ext-library for Ruby 1.3 or later diff --git a/ext/gdbm/depend b/ext/gdbm/depend deleted file mode 100644 index c080a81619..0000000000 --- a/ext/gdbm/depend +++ /dev/null @@ -1 +0,0 @@ -gdbm.o: gdbm.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/gdbm/extconf.rb b/ext/gdbm/extconf.rb deleted file mode 100644 index 5a09492e5e..0000000000 --- a/ext/gdbm/extconf.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'mkmf' - -dir_config("gdbm") -if have_library("gdbm", "gdbm_open") and - have_header("gdbm.h") - create_makefile("gdbm") -end diff --git a/ext/gdbm/gdbm.c b/ext/gdbm/gdbm.c deleted file mode 100644 index d30f5dec7a..0000000000 --- a/ext/gdbm/gdbm.c +++ /dev/null @@ -1,994 +0,0 @@ -/************************************************ - - gdbm.c - - - $Author$ - $Date$ - modified at: Mon Jan 24 15:59:52 JST 1994 - -************************************************/ - -#include "ruby.h" - -#include -#include -#include - -static VALUE rb_cGDBM, rb_eGDBMError, rb_eGDBMFatalError; - -#define MY_BLOCK_SIZE (2048) -#define MY_FATAL_FUNC rb_gdbm_fatal -static void -rb_gdbm_fatal(msg) - char *msg; -{ - rb_raise(rb_eGDBMFatalError, msg); -} - -struct dbmdata { - int di_size; - GDBM_FILE di_dbm; -}; - -static void -closed_dbm() -{ - rb_raise(rb_eRuntimeError, "closed GDBM file"); -} - -#define GetDBM(obj, dbmp) {\ - Data_Get_Struct(obj, struct dbmdata, dbmp);\ - if (dbmp == 0) closed_dbm();\ - if (dbmp->di_dbm == 0) closed_dbm();\ -} - -static void -free_dbm(dbmp) - struct dbmdata *dbmp; -{ - if (dbmp) { - if (dbmp->di_dbm) gdbm_close(dbmp->di_dbm); - free(dbmp); - } -} - -static VALUE -fgdbm_close(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - - GetDBM(obj, dbmp); - gdbm_close(dbmp->di_dbm); - dbmp->di_dbm = 0; - - return Qnil; -} - -static VALUE -fgdbm_s_new(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0); - rb_obj_call_init(obj, argc, argv); - return obj; -} - -static VALUE -fgdbm_initialize(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE file, vmode, vflags; - GDBM_FILE dbm; - struct dbmdata *dbmp; - int mode, flags = 0; - - if (rb_scan_args(argc, argv, "12", &file, &vmode, &vflags) == 1) { - mode = 0666; /* default value */ - } - else if (NIL_P(vmode)) { - mode = -1; /* return nil if DB not exist */ - } - else { - mode = NUM2INT(vmode); - } - - if (!NIL_P(vflags)) - flags = NUM2INT(vflags); - - SafeStringValue(file); - - dbm = 0; - if (mode >= 0) - dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE, - GDBM_WRCREAT|flags, mode, MY_FATAL_FUNC); - if (!dbm) - dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE, - GDBM_WRITER|flags, 0, MY_FATAL_FUNC); - if (!dbm) - dbm = gdbm_open(RSTRING(file)->ptr, MY_BLOCK_SIZE, - GDBM_READER|flags, 0, MY_FATAL_FUNC); - - if (!dbm) { - if (mode == -1) return Qnil; - - if (gdbm_errno == GDBM_FILE_OPEN_ERROR || - gdbm_errno == GDBM_CANT_BE_READER || - gdbm_errno == GDBM_CANT_BE_WRITER) - rb_sys_fail(RSTRING(file)->ptr); - else - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - - dbmp = ALLOC(struct dbmdata); - DATA_PTR(obj) = dbmp; - dbmp->di_dbm = dbm; - dbmp->di_size = -1; - - return obj; -} - -static VALUE -fgdbm_s_open(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = Data_Wrap_Struct(klass, 0, free_dbm, 0); - - if (NIL_P(fgdbm_initialize(argc, argv, obj))) { - return Qnil; - } - - if (rb_block_given_p()) { - return rb_ensure(rb_yield, obj, fgdbm_close, obj); - } - - return obj; -} - -static VALUE -rb_gdbm_fetch(dbm, key) - GDBM_FILE dbm; - datum key; -{ - datum val; - VALUE str; - - val = gdbm_fetch(dbm, key); - if (val.dptr == 0) - return Qnil; - - str = rb_obj_alloc(rb_cString); - RSTRING(str)->len = val.dsize; - RSTRING(str)->aux.capa = val.dsize; - RSTRING(str)->ptr = REALLOC_N(val.dptr,char,val.dsize+1); - RSTRING(str)->ptr[val.dsize] = '\0'; - - OBJ_TAINT(str); - return (VALUE)str; -} - -static VALUE -rb_gdbm_fetch2(dbm, keystr) - GDBM_FILE dbm; - VALUE keystr; -{ - datum key; - - StringValue(keystr); - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - return rb_gdbm_fetch(dbm, key); -} - -static VALUE -rb_gdbm_fetch3(obj, keystr) - VALUE obj, keystr; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - return rb_gdbm_fetch2(dbm, keystr); -} - -static VALUE -rb_gdbm_firstkey(dbm) - GDBM_FILE dbm; -{ - datum key; - VALUE str; - - key = gdbm_firstkey(dbm); - if (key.dptr == 0) - return Qnil; - - str = rb_obj_alloc(rb_cString); - RSTRING(str)->len = key.dsize; - RSTRING(str)->aux.capa = key.dsize; - RSTRING(str)->ptr = REALLOC_N(key.dptr,char,key.dsize+1); - RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; - - OBJ_TAINT(str); - return str; -} - -static VALUE -rb_gdbm_nextkey(dbm, keystr) - GDBM_FILE dbm; - VALUE keystr; -{ - datum key, key2; - VALUE str; - - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - key2 = gdbm_nextkey(dbm, key); - if (key2.dptr == 0) - return Qnil; - - str = rb_obj_alloc(rb_cString); - RSTRING(str)->len = key2.dsize; - RSTRING(str)->aux.capa = key2.dsize; - RSTRING(str)->ptr = REALLOC_N(key2.dptr,char,key2.dsize+1); - RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; - - OBJ_TAINT(str); - return str; -} - -static VALUE -fgdbm_fetch(obj, keystr, ifnone) - VALUE obj, keystr, ifnone; -{ - VALUE valstr; - - valstr = rb_gdbm_fetch3(obj, keystr); - if (NIL_P(valstr)) { - if (ifnone == Qnil && rb_block_given_p()) - return rb_yield(keystr); - return ifnone; - } - return valstr; -} - -static VALUE -fgdbm_aref(obj, keystr) - VALUE obj, keystr; -{ - return rb_gdbm_fetch3(obj, keystr); -} - -static VALUE -fgdbm_fetch_m(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE keystr, valstr, ifnone; - - rb_scan_args(argc, argv, "11", &keystr, &ifnone); - valstr = fgdbm_fetch(obj, keystr, ifnone); - if (argc == 1 && !rb_block_given_p() && NIL_P(valstr)) - rb_raise(rb_eIndexError, "key not found"); - - return valstr; -} - -static VALUE -fgdbm_index(obj, valstr) - VALUE obj, valstr; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, valstr2; - - StringValue(valstr); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - valstr2 = rb_gdbm_fetch2(dbm, keystr); - if (!NIL_P(valstr2) && - RSTRING(valstr)->len == RSTRING(valstr2)->len && - memcmp(RSTRING(valstr)->ptr, RSTRING(valstr2)->ptr, - RSTRING(valstr)->len) == 0) { - return keystr; - } - } - return Qnil; -} - -static VALUE -fgdbm_indexes(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE new; - int i; - - new = rb_ary_new2(argc); - for (i=0; i 0) { - rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc); - } - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - VALUE assoc = rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr)); - - if (RTEST(rb_yield(assoc))) - rb_ary_push(new, assoc); - } - } - else { - for (i=0; iptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - if (!gdbm_exists(dbm, key)) { - return Qnil; - } - - if (gdbm_delete(dbm, key)) { - dbmp->di_size = -1; - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - else if (dbmp->di_size >= 0) { - dbmp->di_size--; - } - return obj; -} - -static VALUE -fgdbm_delete(obj, keystr) - VALUE obj, keystr; -{ - VALUE valstr; - - valstr = fgdbm_fetch(obj, keystr, Qnil); - rb_gdbm_delete(obj, keystr); - return valstr; -} - -static VALUE -fgdbm_shift(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, valstr; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - keystr = rb_gdbm_firstkey(dbm); - if (NIL_P(keystr)) return Qnil; - valstr = rb_gdbm_fetch2(dbm, keystr); - rb_gdbm_delete(obj, keystr); - - return rb_assoc_new(keystr, valstr); -} - -static VALUE -fgdbm_delete_if(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, valstr; - VALUE ret, ary = rb_ary_new(); - int i, status = 0, n; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - n = dbmp->di_size; - dbmp->di_size = -1; - - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - valstr = rb_gdbm_fetch2(dbm, keystr); - ret = rb_protect(rb_yield, rb_assoc_new(keystr, valstr), &status); - if (status != 0) break; - if (RTEST(ret)) rb_ary_push(ary, keystr); - } - - for (i = 0; i < RARRAY(ary)->len; i++) - rb_gdbm_delete(obj, RARRAY(ary)->ptr[i]); - if (status) rb_jump_tag(status); - if (n > 0) dbmp->di_size = n - RARRAY(ary)->len; - - return obj; -} - -static VALUE -fgdbm_clear(obj) - VALUE obj; -{ - datum key, nextkey; - struct dbmdata *dbmp; - GDBM_FILE dbm; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - dbmp->di_size = -1; - -#if 0 - while (key = gdbm_firstkey(dbm), key.dptr) { - if (gdbm_delete(dbm, key)) { - free(key.dptr); - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - free(key.dptr); - } -#else - while (key = gdbm_firstkey(dbm), key.dptr) { - for (; key.dptr; key = nextkey) { - nextkey = gdbm_nextkey(dbm, key); - if (gdbm_delete(dbm, key)) { - free(key.dptr); - if (nextkey.dptr) free(nextkey.dptr); - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - free(key.dptr); - } - } -#endif - dbmp->di_size = 0; - - return obj; -} - -static VALUE -fgdbm_invert(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, valstr; - VALUE hash = rb_hash_new(); - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - valstr = rb_gdbm_fetch2(dbm, keystr); - - rb_hash_aset(hash, valstr, keystr); - } - return hash; -} - -static VALUE -each_pair(obj) - VALUE obj; -{ - return rb_funcall(obj, rb_intern("each_pair"), 0, 0); -} - -static VALUE fgdbm_store _((VALUE,VALUE,VALUE)); - -static VALUE -update_i(pair, dbm) - VALUE pair, dbm; -{ - Check_Type(pair, T_ARRAY); - if (RARRAY(pair)->len < 2) { - rb_raise(rb_eArgError, "pair must be [key, value]"); - } - fgdbm_store(dbm, RARRAY(pair)->ptr[0], RARRAY(pair)->ptr[1]); - return Qnil; -} - -static VALUE -fgdbm_update(obj, other) - VALUE obj, other; -{ - rb_iterate(each_pair, other, update_i, obj); - return obj; -} - -static VALUE -fgdbm_replace(obj, other) - VALUE obj, other; -{ - fgdbm_clear(obj); - rb_iterate(each_pair, other, update_i, obj); - return obj; -} - -static VALUE -fgdbm_store(obj, keystr, valstr) - VALUE obj, keystr, valstr; -{ - datum key, val; - struct dbmdata *dbmp; - GDBM_FILE dbm; - - rb_secure(4); - StringValue(keystr); - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - StringValue(valstr); - val.dptr = RSTRING(valstr)->ptr; - val.dsize = RSTRING(valstr)->len; - - GetDBM(obj, dbmp); - dbmp->di_size = -1; - dbm = dbmp->di_dbm; - if (gdbm_store(dbm, key, val, GDBM_REPLACE)) { - if (errno == EPERM) rb_sys_fail(0); - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - - return valstr; -} - -static VALUE -fgdbm_length(obj) - VALUE obj; -{ - datum key, nextkey; - struct dbmdata *dbmp; - GDBM_FILE dbm; - int i = 0; - - GetDBM(obj, dbmp); - if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size); - dbm = dbmp->di_dbm; - - for (key = gdbm_firstkey(dbm); key.dptr; key = nextkey) { - nextkey = gdbm_nextkey(dbm, key); - free(key.dptr); - i++; - } - dbmp->di_size = i; - - return INT2FIX(i); -} - -static VALUE -fgdbm_empty_p(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - GDBM_FILE dbm; - - GetDBM(obj, dbmp); - if (dbmp->di_size < 0) { - dbm = dbmp->di_dbm; - - key = gdbm_firstkey(dbm); - if (key.dptr) { - free(key.dptr); - return Qfalse; - } - return Qtrue; - } - - if (dbmp->di_size == 0) return Qtrue; - return Qfalse; -} - -static VALUE -fgdbm_each_value(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - rb_yield(rb_gdbm_fetch2(dbm, keystr)); - } - return obj; -} - -static VALUE -fgdbm_each_key(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - rb_yield(keystr); - } - return obj; -} - -static VALUE -fgdbm_each_pair(obj) - VALUE obj; -{ - GDBM_FILE dbm; - struct dbmdata *dbmp; - VALUE keystr; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - rb_yield(rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr))); - } - - return obj; -} - -static VALUE -fgdbm_keys(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - rb_ary_push(ary, keystr); - } - - return ary; -} - -static VALUE -fgdbm_values(obj) - VALUE obj; -{ - datum key, nextkey; - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE valstr, ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (key = gdbm_firstkey(dbm); key.dptr; key = nextkey) { - nextkey = gdbm_nextkey(dbm, key); - valstr = rb_gdbm_fetch(dbm, key); - free(key.dptr); - rb_ary_push(ary, valstr); - } - - return ary; -} - -static VALUE -fgdbm_has_key(obj, keystr) - VALUE obj, keystr; -{ - datum key; - struct dbmdata *dbmp; - GDBM_FILE dbm; - - StringValue(keystr); - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - if (gdbm_exists(dbm, key)) - return Qtrue; - return Qfalse; -} - -static VALUE -fgdbm_has_value(obj, valstr) - VALUE obj, valstr; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, valstr2; - - StringValue(valstr); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - valstr2 = rb_gdbm_fetch2(dbm, keystr); - - if (!NIL_P(valstr2) && - RSTRING(valstr)->len == RSTRING(valstr2)->len && - memcmp(RSTRING(valstr)->ptr, RSTRING(valstr2)->ptr, - RSTRING(valstr)->len) == 0) { - return Qtrue; - } - } - return Qfalse; -} - -static VALUE -fgdbm_to_a(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - rb_ary_push(ary, rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr))); - } - - return ary; -} - -static VALUE -fgdbm_reorganize(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - gdbm_reorganize(dbm); - return obj; -} - -static VALUE -fgdbm_sync(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - gdbm_sync(dbm); - return obj; -} - -static VALUE -fgdbm_set_cachesize(obj, val) - VALUE obj, val; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - int optval; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - optval = FIX2INT(val); - if (gdbm_setopt(dbm, GDBM_CACHESIZE, &optval, sizeof(optval)) == -1) { - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - return val; -} - -static VALUE -fgdbm_set_fastmode(obj, val) - VALUE obj, val; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - int optval; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - optval = 0; - if (RTEST(val)) - optval = 1; - - if (gdbm_setopt(dbm, GDBM_FASTMODE, &optval, sizeof(optval)) == -1) { - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - return val; -} - -static VALUE -fgdbm_set_syncmode(obj, val) - VALUE obj, val; -{ -#if !defined(GDBM_SYNCMODE) - fgdbm_set_fastmode(obj, RTEST(val) ? Qfalse : Qtrue); - return val; -#else - struct dbmdata *dbmp; - GDBM_FILE dbm; - int optval; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - optval = 0; - if (RTEST(val)) - optval = 1; - - if (gdbm_setopt(dbm, GDBM_FASTMODE, &optval, sizeof(optval)) == -1) { - rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno)); - } - return val; -#endif -} - -static VALUE -fgdbm_to_hash(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - GDBM_FILE dbm; - VALUE keystr, hash; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - hash = rb_hash_new(); - for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr); - keystr = rb_gdbm_nextkey(dbm, keystr)) { - - rb_hash_aset(hash, keystr, rb_gdbm_fetch2(dbm, keystr)); - } - - return hash; -} - -static VALUE -fgdbm_reject(obj) - VALUE obj; -{ - return rb_hash_delete_if(fgdbm_to_hash(obj)); -} - -void -Init_gdbm() -{ - rb_cGDBM = rb_define_class("GDBM", rb_cObject); - rb_eGDBMError = rb_define_class("GDBMError", rb_eStandardError); - rb_eGDBMFatalError = rb_define_class("GDBMFatalError", rb_eException); - rb_include_module(rb_cGDBM, rb_mEnumerable); - - rb_define_singleton_method(rb_cGDBM, "new", fgdbm_s_new, -1); - rb_define_singleton_method(rb_cGDBM, "open", fgdbm_s_open, -1); - - rb_define_method(rb_cGDBM, "initialize", fgdbm_initialize, -1); - rb_define_method(rb_cGDBM, "close", fgdbm_close, 0); - rb_define_method(rb_cGDBM, "[]", fgdbm_aref, 1); - rb_define_method(rb_cGDBM, "fetch", fgdbm_fetch_m, -1); - rb_define_method(rb_cGDBM, "[]=", fgdbm_store, 2); - rb_define_method(rb_cGDBM, "store", fgdbm_store, 2); - rb_define_method(rb_cGDBM, "index", fgdbm_index, 1); - rb_define_method(rb_cGDBM, "indexes", fgdbm_indexes, -1); - rb_define_method(rb_cGDBM, "indices", fgdbm_indexes, -1); - rb_define_method(rb_cGDBM, "select", fgdbm_select, -1); - rb_define_method(rb_cGDBM, "length", fgdbm_length, 0); - rb_define_method(rb_cGDBM, "size", fgdbm_length, 0); - rb_define_method(rb_cGDBM, "empty?", fgdbm_empty_p, 0); - rb_define_method(rb_cGDBM, "each", fgdbm_each_pair, 0); - rb_define_method(rb_cGDBM, "each_value", fgdbm_each_value, 0); - rb_define_method(rb_cGDBM, "each_key", fgdbm_each_key, 0); - rb_define_method(rb_cGDBM, "each_pair", fgdbm_each_pair, 0); - rb_define_method(rb_cGDBM, "keys", fgdbm_keys, 0); - rb_define_method(rb_cGDBM, "values", fgdbm_values, 0); - rb_define_method(rb_cGDBM, "shift", fgdbm_shift, 0); - rb_define_method(rb_cGDBM, "delete", fgdbm_delete, 1); - rb_define_method(rb_cGDBM, "delete_if", fgdbm_delete_if, 0); - rb_define_method(rb_cGDBM, "reject!", fgdbm_delete_if, 0); - rb_define_method(rb_cGDBM, "reject", fgdbm_reject, 0); - rb_define_method(rb_cGDBM, "clear", fgdbm_clear, 0); - rb_define_method(rb_cGDBM,"invert", fgdbm_invert, 0); - rb_define_method(rb_cGDBM,"update", fgdbm_update, 1); - rb_define_method(rb_cGDBM,"replace", fgdbm_replace, 1); - rb_define_method(rb_cGDBM,"reorganize", fgdbm_reorganize, 0); - rb_define_method(rb_cGDBM,"sync", fgdbm_sync, 0); - /* rb_define_method(rb_cGDBM,"setopt", fgdbm_setopt, 2); */ - rb_define_method(rb_cGDBM,"cachesize=", fgdbm_set_cachesize, 1); - rb_define_method(rb_cGDBM,"fastmode=", fgdbm_set_fastmode, 1); - rb_define_method(rb_cGDBM,"syncmode=", fgdbm_set_syncmode, 1); - - rb_define_method(rb_cGDBM, "include?", fgdbm_has_key, 1); - rb_define_method(rb_cGDBM, "has_key?", fgdbm_has_key, 1); - rb_define_method(rb_cGDBM, "member?", fgdbm_has_key, 1); - rb_define_method(rb_cGDBM, "has_value?", fgdbm_has_value, 1); - rb_define_method(rb_cGDBM, "key?", fgdbm_has_key, 1); - rb_define_method(rb_cGDBM, "value?", fgdbm_has_value, 1); - - rb_define_method(rb_cGDBM, "to_a", fgdbm_to_a, 0); - rb_define_method(rb_cGDBM, "to_hash", fgdbm_to_hash, 0); - - /* flags for gdbm_opn() */ - /* - rb_define_const(rb_cGDBM, "READER", INT2FIX(GDBM_READER)); - rb_define_const(rb_cGDBM, "WRITER", INT2FIX(GDBM_WRITER)); - rb_define_const(rb_cGDBM, "WRCREAT", INT2FIX(GDBM_WRCREAT)); - rb_define_const(rb_cGDBM, "NEWDB", INT2FIX(GDBM_NEWDB)); - */ - rb_define_const(rb_cGDBM, "FAST", INT2FIX(GDBM_FAST)); - /* this flag is obsolete in gdbm 1.8. - On gdbm 1.8, fast mode is default behavior. */ - - /* gdbm version 1.8 specific */ -#if defined(GDBM_SYNC) - rb_define_const(rb_cGDBM, "SYNC", INT2FIX(GDBM_SYNC)); -#endif -#if defined(GDBM_NOLOCK) - rb_define_const(rb_cGDBM, "NOLOCK", INT2FIX(GDBM_NOLOCK)); -#endif - rb_define_const(rb_cGDBM, "VERSION", rb_str_new2(gdbm_version)); -} diff --git a/ext/gdbm/testgdbm.rb b/ext/gdbm/testgdbm.rb deleted file mode 100644 index 524d3f8ca3..0000000000 --- a/ext/gdbm/testgdbm.rb +++ /dev/null @@ -1,663 +0,0 @@ -require 'runit/testcase' -require 'runit/cui/testrunner' - -if $".grep(/\bgdbm.so\b/).empty? - begin - require './gdbm' - rescue LoadError - require 'gdbm' - end -end - -def uname_s - require 'rbconfig' - case Config::CONFIG['host_os'] - when 'cygwin' - require 'Win32API' - uname = Win32API.new 'cygwin1', 'uname', 'P', 'I' - utsname = ' ' * 100 - raise 'cannot get system name' if uname.call(utsname) == -1 - - utsname.unpack('A20' * 5)[0] - else - Config::CONFIG['host_os'] - end -end - -SYSTEM = uname_s - -class TestGDBM < RUNIT::TestCase - def setup - @path = "tmptest_gdbm_" - assert_instance_of(GDBM, @gdbm = GDBM.new(@path)) - - # prepare to make readonly GDBM file - GDBM.open("tmptest_gdbm_rdonly", 0400) {|gdbm| - gdbm['foo'] = 'FOO' - } - assert_instance_of(GDBM, @gdbm_rdonly = GDBM.new("tmptest_gdbm_rdonly", nil)) - end - def teardown - assert_nil(@gdbm.close) - assert_nil(@gdbm_rdonly.close) - GC.start - File.delete *Dir.glob("tmptest_gdbm*").to_a - p Dir.glob("tmptest_gdbm*") if $DEBUG - end - - def check_size(expect, gdbm=@gdbm) - assert_equals(expect, gdbm.size) - n = 0 - gdbm.each { n+=1 } - assert_equals(expect, n) - if expect == 0 - assert_equals(true, gdbm.empty?) - else - assert_equals(false, gdbm.empty?) - end - end - - def test_version - STDERR.print GDBM::VERSION - end - - def test_s_new_has_no_block - # GDBM.new ignore the block - foo = true - assert_instance_of(GDBM, gdbm = GDBM.new("tmptest_gdbm") { foo = false }) - assert_equals(foo, true) - assert_nil(gdbm.close) - end - def test_s_open_create_new - return if /^CYGWIN_9/ =~ SYSTEM - - save_mask = File.umask(0) - begin - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm")) - gdbm.close - assert_equals(File.stat("tmptest_gdbm").mode & 0777, 0666) - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm2", 0644)) - gdbm.close - assert_equals(File.stat("tmptest_gdbm2").mode & 0777, 0644) - ensure - File.umask save_mask - end - end - def test_s_open_no_create - # this test is failed on libgdbm 1.8.0 - assert_nil(gdbm = GDBM.open("tmptest_gdbm", nil)) - ensure - gdbm.close if gdbm - end - def test_s_open_3rd_arg - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644, - GDBM::FAST)) - gdbm.close - - # gdbm 1.8.0 specific - if defined? GDBM::SYNC - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644, - GDBM::SYNC)) - gdbm.close - end - # gdbm 1.8.0 specific - if defined? GDBM::NOLOCK - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644, - GDBM::NOLOCK)) - gdbm.close - end - end - def test_s_open_with_block - assert_equals(GDBM.open("tmptest_gdbm") { :foo }, :foo) - end - def test_s_open_lock - fork() { - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644)) - sleep 2 - } - begin - sleep 1 - assert_exception(Errno::EWOULDBLOCK) { - begin - assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644)) - rescue Errno::EAGAIN, Errno::EACCES - raise Errno::EWOULDBLOCK - end - } - ensure - Process.wait - end - end - -=begin - # Is it guaranteed on many OS? - def test_s_open_lock_one_process - # locking on one process - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644)) - assert_exception(Errno::EWOULDBLOCK) { - begin - GDBM.open("tmptest_gdbm", 0644) - rescue Errno::EAGAIN - raise Errno::EWOULDBLOCK - end - } - end -=end - - def test_s_open_nolock - # gdbm 1.8.0 specific - if not defined? GDBM::NOLOCK - return - end - - fork() { - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644, - GDBM::NOLOCK)) - sleep 2 - } - sleep 1 - begin - gdbm2 = nil - assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { - assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644)) - } - ensure - Process.wait - gdbm2.close if gdbm2 - end - - p Dir.glob("tmptest_gdbm*") if $DEBUG - - fork() { - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644)) - sleep 2 - } - begin - sleep 1 - gdbm2 = nil - assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { - # this test is failed on Cygwin98 (???) - assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644, - GDBM::NOLOCK)) - } - ensure - Process.wait - gdbm2.close if gdbm2 - end - end - - def test_s_open_error - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0)) - assert_exception(Errno::EACCES) { - GDBM.open("tmptest_gdbm", 0) - } - gdbm.close - end - - def test_close - assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm")) - assert_nil(gdbm.close) - - # closed GDBM file - assert_exception(RuntimeError) { gdbm.close } - end - - def test_aref - assert_equals('bar', @gdbm['foo'] = 'bar') - assert_equals('bar', @gdbm['foo']) - - assert_nil(@gdbm['bar']) - end - - def test_fetch - assert_equals('bar', @gdbm['foo']='bar') - assert_equals('bar', @gdbm.fetch('foo')) - - # key not found - assert_exception(IndexError) { - @gdbm.fetch('bar') - } - - # test for `ifnone' arg - assert_equals('baz', @gdbm.fetch('bar', 'baz')) - - # test for `ifnone' block - assert_equals('foobar', @gdbm.fetch('bar') {|key| 'foo' + key }) - end - - def test_aset - num = 0 - 2.times {|i| - assert_equals('foo', @gdbm['foo'] = 'foo') - assert_equals('foo', @gdbm['foo']) - assert_equals('bar', @gdbm['foo'] = 'bar') - assert_equals('bar', @gdbm['foo']) - - num += 1 if i == 0 - assert_equals(num, @gdbm.size) - - # assign nil - assert_equals('', @gdbm['bar'] = '') - assert_equals('', @gdbm['bar']) - - num += 1 if i == 0 - assert_equals(num, @gdbm.size) - - # empty string - assert_equals('', @gdbm[''] = '') - assert_equals('', @gdbm['']) - - num += 1 if i == 0 - assert_equals(num, @gdbm.size) - - # Fixnum - assert_equals('200', @gdbm['100'] = '200') - assert_equals('200', @gdbm['100']) - - num += 1 if i == 0 - assert_equals(num, @gdbm.size) - - # Big key and value - assert_equals('y' * 100, @gdbm['x' * 100] = 'y' * 100) - assert_equals('y' * 100, @gdbm['x' * 100]) - - num += 1 if i == 0 - assert_equals(num, @gdbm.size) - } - end - - def test_index - assert_equals('bar', @gdbm['foo'] = 'bar') - assert_equals('foo', @gdbm.index('bar')) - assert_nil(@gdbm['bar']) - end - - def test_indexes - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - assert_equals(values.reverse, @gdbm.indexes(*keys.reverse)) - end - - def test_select - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - assert_equals(values.reverse, @gdbm.select(*keys.reverse)) - end - - def test_select_with_block - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - ret = @gdbm.select {|k,v| - assert_equals(k.upcase, v) - k != "bar" - } - assert_equals([['baz', 'BAZ'], ['foo', 'FOO']], - ret.sort) - end - - def test_length - num = 10 - assert_equals(0, @gdbm.size) - num.times {|i| - i = i.to_s - @gdbm[i] = i - } - assert_equals(num, @gdbm.size) - - @gdbm.shift - - assert_equals(num - 1, @gdbm.size) - end - - def test_empty? - assert_equals(true, @gdbm.empty?) - @gdbm['foo'] = 'FOO' - assert_equals(false, @gdbm.empty?) - end - - def test_each_pair - n = 0 - @gdbm.each_pair { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - - n = 0 - ret = @gdbm.each_pair {|key, val| - assert_not_nil(i = keys.index(key)) - assert_equals(val, values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@gdbm, ret) - end - - def test_each_value - n = 0 - @gdbm.each_value { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - - n = 0 - ret = @gdbm.each_value {|val| - assert_not_nil(key = @gdbm.index(val)) - assert_not_nil(i = keys.index(key)) - assert_equals(val, values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@gdbm, ret) - end - - def test_each_key - n = 0 - @gdbm.each_key { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - - n = 0 - ret = @gdbm.each_key {|key| - assert_not_nil(i = keys.index(key)) - assert_equals(@gdbm[key], values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@gdbm, ret) - end - - def test_keys - assert_equals([], @gdbm.keys) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - - assert_equals(keys.sort, @gdbm.keys.sort) - assert_equals(values.sort, @gdbm.values.sort) - end - - def test_values - test_keys - end - - def test_shift - assert_nil(@gdbm.shift) - assert_equals(0, @gdbm.size) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - - ret_keys = [] - ret_values = [] - while ret = @gdbm.shift - ret_keys.push ret[0] - ret_values.push ret[1] - - assert_equals(keys.size - ret_keys.size, @gdbm.size) - end - - assert_equals(keys.sort, ret_keys.sort) - assert_equals(values.sort, ret_values.sort) - end - - def test_delete - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - key = keys[1] - - assert_nil(@gdbm.delete(key)) - assert_equals(0, @gdbm.size) - - @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values - - assert_equals('BAR', @gdbm.delete(key)) - assert_nil(@gdbm[key]) - assert_equals(2, @gdbm.size) - - assert_nil(@gdbm.delete(key)) - - if /^CYGWIN_9/ !~ SYSTEM - assert_exception(GDBMError) { - @gdbm_rdonly.delete("foo") - } - - assert_nil(@gdbm_rdonly.delete("bar")) - end - end - def test_delete_with_block - key = 'no called block' - @gdbm[key] = 'foo' - assert_equals('foo', @gdbm.delete(key) {|k| k.replace 'called block'}) - assert_equals('no called block', key) - assert_equals(0, @gdbm.size) - - key = 'no called block' - assert_equals(:blockval, - @gdbm.delete(key) {|k| k.replace 'called block'; :blockval}) - assert_equals('called block', key) - assert_equals(0, @gdbm.size) - end - - def test_delete_if - v = "0" - 100.times {@gdbm[v] = v; v = v.next} - - ret = @gdbm.delete_if {|key, val| key.to_i < 50} - assert_equals(@gdbm, ret) - check_size(50, @gdbm) - - ret = @gdbm.delete_if {|key, val| key.to_i >= 50} - assert_equals(@gdbm, ret) - check_size(0, @gdbm) - - # break - v = "0" - 100.times {@gdbm[v] = v; v = v.next} - check_size(100, @gdbm) - n = 0; - @gdbm.delete_if {|key, val| - break if n > 50 - n+=1 - true - } - assert_equals(51, n) - check_size(49, @gdbm) - - @gdbm.clear - - # raise - v = "0" - 100.times {@gdbm[v] = v; v = v.next} - check_size(100, @gdbm) - n = 0; - begin - @gdbm.delete_if {|key, val| - raise "runtime error" if n > 50 - n+=1 - true - } - rescue - end - assert_equals(51, n) - check_size(49, @gdbm) - end - - def test_reject - v = "0" - 100.times {@gdbm[v] = v; v = v.next} - - hash = @gdbm.reject {|key, val| key.to_i < 50} - assert_instance_of(Hash, hash) - assert_equals(100, @gdbm.size) - - assert_equals(50, hash.size) - hash.each_pair {|key,val| - assert_equals(false, key.to_i < 50) - assert_equals(key, val) - } - - hash = @gdbm.reject {|key, val| key.to_i < 100} - assert_instance_of(Hash, hash) - assert_equals(true, hash.empty?) - end - - def test_clear - v = "1" - 100.times {v = v.next; @gdbm[v] = v} - - assert_equals(@gdbm, @gdbm.clear) - - # validate GDBM#size - i = 0 - @gdbm.each { i += 1 } - assert_equals(@gdbm.size, i) - assert_equals(0, i) - end - - def test_invert - v = "0" - 100.times {@gdbm[v] = v; v = v.next} - - hash = @gdbm.invert - assert_instance_of(Hash, hash) - assert_equals(100, hash.size) - hash.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_update - hash = {} - v = "0" - 100.times {v = v.next; hash[v] = v} - - @gdbm["101"] = "101" - @gdbm.update hash - assert_equals(101, @gdbm.size) - @gdbm.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_replace - hash = {} - v = "0" - 100.times {v = v.next; hash[v] = v} - - @gdbm["101"] = "101" - @gdbm.replace hash - assert_equals(100, @gdbm.size) - @gdbm.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_reorganize - size1 = File.size(@path) - i = "1" - 1000.times {i = i.next; @gdbm[i] = i} - @gdbm.clear - @gdbm.sync - - size2 = File.size(@path) - @gdbm.reorganize - size3 = File.size(@path) - - # p [size1, size2, size3] - assert_equals(true, size1 < size2) - # this test is failed on Cygwin98. `GDBM version 1.8.0, as of May 19, 1999' - assert_equals(true, size3 < size2) - assert_equals(size1, size3) - end - - def test_sync - assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666, GDBM::FAST)) - assert_equals(gdbm.sync, gdbm) - gdbm.close - assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666)) - assert_equals(gdbm.sync, gdbm) - gdbm.close - end - - def test_cachesize= - assert_equals(@gdbm.cachesize = 1024, 1024) - end - - def test_fastmode= - assert_equals(@gdbm.fastmode = true, true) - end - - def test_syncmode= - assert_equals(@gdbm.syncmode = true, true) - end - - def test_haskey? - assert_equals('bar', @gdbm['foo']='bar') - assert_equals(true, @gdbm.has_key?('foo')) - assert_equals(false, @gdbm.has_key?('bar')) - end - - def test_has_value? - assert_equals('bar', @gdbm['foo']='bar') - assert_equals(true, @gdbm.has_value?('bar')) - assert_equals(false, @gdbm.has_value?('foo')) - end - - def test_to_a - v = "0" - 100.times {v = v.next; @gdbm[v] = v} - - ary = @gdbm.to_a - assert_instance_of(Array, ary) - assert_equals(100, ary.size) - ary.each {|key,val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_to_hash - v = "0" - 100.times {v = v.next; @gdbm[v] = v} - - hash = @gdbm.to_hash - assert_instance_of(Hash, hash) - assert_equals(100, hash.size) - hash.each {|key,val| - assert_equals(key.to_i, val.to_i) - } - end -end - -if $0 == __FILE__ - if ARGV.size == 0 - suite = RUNIT::TestSuite.new - suite.add_test(TestGDBM.suite) - else - suite = RUNIT::TestSuite.new - ARGV.each do |testmethod| - suite.add_test(TestGDBM.new(testmethod)) - end - end - - RUNIT::CUI::TestRunner.run(suite) -end diff --git a/ext/iconv/MANIFEST b/ext/iconv/MANIFEST deleted file mode 100644 index 643f3b7f4d..0000000000 --- a/ext/iconv/MANIFEST +++ /dev/null @@ -1,4 +0,0 @@ -MANIFEST -extconf.rb -iconv.c -depend diff --git a/ext/iconv/depend b/ext/iconv/depend deleted file mode 100644 index 688ddd97b7..0000000000 --- a/ext/iconv/depend +++ /dev/null @@ -1,2 +0,0 @@ -iconv.o: iconv.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h \ - $(hdrdir)/intern.h diff --git a/ext/iconv/extconf.rb b/ext/iconv/extconf.rb deleted file mode 100644 index 55d9c5da5f..0000000000 --- a/ext/iconv/extconf.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'mkmf' - -dir_config("iconv") - -if have_header("iconv.h") - have_library("iconv") - create_makefile("iconv") -end diff --git a/ext/iconv/iconv.c b/ext/iconv/iconv.c deleted file mode 100644 index bf1528d21a..0000000000 --- a/ext/iconv/iconv.c +++ /dev/null @@ -1,735 +0,0 @@ -/* -*- mode:c; c-file-style:"ruby" -*- */ -/********************************************************************** - - iconv.c - - - $Author$ - $Date$ - created at: Wed Dec 1 20:28:09 JST 1999 - - All the files in this distribution are covered under the Ruby's - license (see the file COPYING). - -**********************************************************************/ - -/* -=begin -= Summary -Ruby extension for codeset conversion. - -= Abstract -Iconv is a wrapper class for UNIX 95 (({iconv()})) function family, which -translates string between various coding systems. - -See (())'s on-line documents for more details. -* (()) -* (()) -* (()) -* (()) - -Which coding systems are available, it depends on the platform. - -=end -*/ - -#include -#include -#include -#include "ruby.h" -#include "intern.h" - -/* Invalid value for iconv_t is -1 but 0 for VALUE, I hope VALUE is - big enough to keep iconv_t */ -#define VALUE2ICONV(v) ((iconv_t)((VALUE)(v) ^ -1)) -#define ICONV2VALUE(c) ((VALUE)(c) ^ -1) - -struct iconv_env_t -{ - iconv_t cd; - int argc; - VALUE *argv; - VALUE ret; -}; - -static VALUE rb_eIconvFailure; -static VALUE rb_eIconvIllegalSeq; -static VALUE rb_eIconvInvalidChar; -static VALUE rb_eIconvOutOfRange; -static ID rb_inserter; - -static ID rb_success, rb_failed, rb_mesg; -static VALUE iconv_failure_initialize _((VALUE error, VALUE success, VALUE failed, struct iconv_env_t* env)); -static VALUE iconv_failure_success _((VALUE self)); -static VALUE iconv_failure_failed _((VALUE self)); - -static iconv_t iconv_create _((VALUE to, VALUE from)); -static VALUE iconv_free _((VALUE cd)); -static VALUE iconv_try _((iconv_t cd, const char **inptr, size_t *inlen, char **outptr, size_t *outlen)); -static VALUE rb_str_derive _((VALUE str, const char* ptr, int len)); -static VALUE iconv_convert _((iconv_t cd, VALUE str, int start, int length, struct iconv_env_t* env)); -static VALUE iconv_s_allocate _((VALUE klass)); -static VALUE iconv_initialize _((VALUE self, VALUE to, VALUE from)); -static VALUE iconv_s_open _((VALUE self, VALUE to, VALUE from)); -static VALUE iconv_s_convert _((struct iconv_env_t* env)); -static VALUE iconv_s_iconv _((int argc, VALUE *argv, VALUE self)); -static VALUE iconv_init_state _((VALUE cd)); -static VALUE iconv_finish _((VALUE self)); -static VALUE iconv_iconv _((int argc, VALUE *argv, VALUE self)); - - -/* -=begin -= Classes & Modules -=end -*/ - -/* -=begin -== Iconv -=end -*/ -static iconv_t -iconv_create -#ifdef HAVE_PROTOTYPES -(VALUE to, VALUE from) -#else /* HAVE_PROTOTYPES */ - (to, from) - VALUE to; - VALUE from; -#endif /* HAVE_PROTOTYPES */ -{ - const char* tocode = StringValuePtr(to); - const char* fromcode = StringValuePtr(from); - - iconv_t cd = iconv_open(tocode, fromcode); - - if (cd == (iconv_t)-1) { - switch (errno) { - case EMFILE: - case ENFILE: - case ENOMEM: - rb_gc(); - cd = iconv_open(tocode, fromcode); - } - if (cd == (iconv_t)-1) { - volatile VALUE msg = rb_str_new2("iconv(\""); - rb_str_buf_cat2(rb_str_buf_append(msg, to), "\", \""); - rb_str_buf_cat2(rb_str_buf_append(msg, from), "\")"); - rb_sys_fail(StringValuePtr(msg)); - } - } - - return cd; -} - -static VALUE -iconv_free -#ifdef HAVE_PROTOTYPES -(VALUE cd) -#else /* HAVE_PROTOTYPES */ - (cd) - VALUE cd; -#endif /* HAVE_PROTOTYPES */ -{ - if (cd && iconv_close(VALUE2ICONV(cd)) == -1) - rb_sys_fail("iconv_close"); - return Qnil; -} - -#define ICONV_FREE (RUBY_DATA_FUNC)iconv_free - -static VALUE -iconv_try -#ifdef HAVE_PROTOTYPES -(iconv_t cd, const char **inptr, size_t *inlen, char **outptr, size_t *outlen) -#else /* HAVE_PROTOTYPES */ - (cd, inptr, inlen, outptr, outlen) - iconv_t cd; - const char **inptr; - size_t *inlen; - char **outptr; - size_t *outlen; -#endif /* HAVE_PROTOTYPES */ -{ - if (iconv(cd, (char **)inptr, inlen, outptr, outlen) == (size_t)-1) { - if (!*inlen) - return Qfalse; - switch (errno) { - case E2BIG: - /* try the left in next loop */ - break; - case EILSEQ: - return rb_obj_alloc(rb_eIconvIllegalSeq); - case EINVAL: - return rb_obj_alloc(rb_eIconvInvalidChar); - default: - rb_sys_fail("iconv"); - } - } - else if (*inlen > 0) { - /* something goes wrong */ - return rb_obj_alloc(rb_eIconvIllegalSeq); - } - return Qfalse; -} - -#define iconv_fail(error, success, failed, env) \ - rb_exc_raise(iconv_failure_initialize(error, success, failed, env)) - -static VALUE -iconv_failure_initialize -#ifdef HAVE_PROTOTYPES -(VALUE error, VALUE success, VALUE failed, struct iconv_env_t* env) -#else /* HAVE_PROTOTYPES */ - (error, success, failed, env) - VALUE error; - VALUE success; - VALUE failed; - struct iconv_env_t *env; -#endif /* HAVE_PROTOTYPES */ -{ - if (NIL_P(rb_ivar_get(error, rb_mesg))) - rb_ivar_set(error, rb_mesg, rb_inspect(failed)); - if (env) { - success = rb_funcall3(env->ret, rb_inserter, 1, &success); - if (env->argc > 0) { - *(env->argv) = failed; - failed = rb_ary_new4(env->argc, env->argv); - } - } - rb_ivar_set(error, rb_success, success); - rb_ivar_set(error, rb_failed, failed); - return error; -} - -static VALUE -rb_str_derive -#ifdef HAVE_PROTOTYPES -(VALUE str, const char* ptr, int len) -#else /* HAVE_PROTOTYPES */ - (str, ptr, len) - VALUE str; - const char *ptr; - int len; -#endif /* HAVE_PROTOTYPES */ -{ - VALUE ret; - - if (NIL_P(str)) - return rb_str_new(ptr, len); - if (RSTRING(str)->ptr == ptr && RSTRING(str)->len == len) - return str; - ret = rb_str_new(ptr, len); - OBJ_INFECT(ret, str); - return ret; -} - -static VALUE -iconv_convert -#ifdef HAVE_PROTOTYPES -(iconv_t cd, VALUE str, int start, int length, struct iconv_env_t* env) -#else /* HAVE_PROTOTYPES */ - (cd, str, start, length, env) - iconv_t cd; - VALUE str; - int start; - int length; - struct iconv_env_t *env; -#endif /* HAVE_PROTOTYPES */ -{ - VALUE ret = Qfalse; - VALUE error = Qfalse; - const char *inptr, *instart; - size_t inlen; - /* I believe ONE CHARACTER never exceed this. */ - char buffer[BUFSIZ]; - char *outptr; - size_t outlen; - - if (cd == (iconv_t)-1) - rb_raise(rb_eArgError, "closed iconv"); - - if (NIL_P(str)) { - /* Reset output pointer or something. */ - inptr = ""; - inlen = 0; - outptr = buffer; - outlen = sizeof(buffer); - error = iconv_try(cd, &inptr, &inlen, &outptr, &outlen); - if (error) - iconv_fail(error, Qnil, Qnil, env); - - inptr = NULL; - length = 0; - } - else { - int slen; - - Check_Type(str, T_STRING); - slen = RSTRING(str)->len; - inptr = RSTRING(str)->ptr; - - if (start < 0 ? (start += slen) < 0 : start >= slen) - length = 0; - else if (length < 0 && (length += slen + 1) < 0) - length = 0; - else if ((length -= start) < 0) - length = 0; - else - inptr += start; - } - instart = inptr; - inlen = length; - - do { - const char *tmpstart = inptr; - outptr = buffer; - outlen = sizeof(buffer); - - error = iconv_try(cd, &inptr, &inlen, &outptr, &outlen); - - if (0 <= outlen && outlen <= sizeof(buffer)) { - outlen = sizeof(buffer) - outlen; - if (outlen > inptr - tmpstart || /* input can't contain output */ - (outlen < inptr - tmpstart && inlen > 0) || /* something skipped */ - memcmp(buffer, tmpstart, outlen)) /* something differs */ - { - if (NIL_P(str)) { - ret = rb_str_new(buffer, outlen); - } - else { - if (ret) { - ret = rb_str_buf_cat(ret, instart, tmpstart - instart); - } - else { - ret = rb_str_new(instart, tmpstart - instart); - OBJ_INFECT(ret, str); - } - ret = rb_str_buf_cat(ret, buffer, outlen); - instart = inptr; - } - } - else if (!inlen) { - inptr = tmpstart + outlen; - } - } - else { - /* Some iconv() have a bug, return *outlen out of range */ - char errmsg[50]; - sprintf(errmsg, "bug?(output length = %d)", sizeof(buffer) - outlen); - error = rb_exc_new2(rb_eIconvOutOfRange, errmsg); - } - - if (error) { - if (!ret) - ret = rb_str_derive(str, instart, inptr - instart); - str = rb_str_derive(str, inptr, inlen); - iconv_fail(error, ret, str, env); - } - } while (inlen > 0); - - if (!ret) - ret = rb_str_derive(str, instart, inptr - instart); - return ret; -} - - -/* -=begin -=== Class methods -=end -*/ -/* -=begin ---- Iconv.new(to, from) - Creates new code converter from a coding-system designated with ((|from|)) - to another one designated with ((|to|)). - :Parameters - :((|to|)) - coding-system name for destination. - :((|from|)) - coding-system name for source. - :Exceptions - :(({TypeError})) - if ((|to|)) or ((|from|)) aren't String - :(({ArgumentError})) - if designated converter couldn't find out. - :(({SystemCallError})) - when (({iconv_open(3)})) failed. - ---- Iconv.open(to, from) - Equivalents to (()) except with in the case of called - with a block, yields with the new instance and closes it, and - returns the result which returned from the block. -=end -*/ -static VALUE -iconv_s_allocate -#ifdef HAVE_PROTOTYPES -(VALUE klass) -#else /* HAVE_PROTOTYPES */ - (klass) - VALUE klass; -#endif /* HAVE_PROTOTYPES */ -{ - return Data_Wrap_Struct(klass, 0, ICONV_FREE, 0); -} - -static VALUE -iconv_initialize -#ifdef HAVE_PROTOTYPES -(VALUE self, VALUE to, VALUE from) -#else /* HAVE_PROTOTYPES */ - (self, to, from) - VALUE self; - VALUE to; - VALUE from; -#endif /* HAVE_PROTOTYPES */ -{ - iconv_free((VALUE)(DATA_PTR(self))); - DATA_PTR(self) = NULL; - DATA_PTR(self) = (void *)ICONV2VALUE(iconv_create(to, from)); - return self; -} - -static VALUE -iconv_s_open -#ifdef HAVE_PROTOTYPES -(VALUE self, VALUE to, VALUE from) -#else /* HAVE_PROTOTYPES */ - (self, to, from) - VALUE self; - VALUE to; - VALUE from; -#endif /* HAVE_PROTOTYPES */ -{ - VALUE cd = ICONV2VALUE(iconv_create(to, from)); - - if (rb_block_given_p()) { - self = Data_Wrap_Struct(self, NULL, NULL, (void *)cd); - return rb_ensure(rb_yield, self, (VALUE(*)())iconv_finish, self); - } - else { - return Data_Wrap_Struct(self, NULL, ICONV_FREE, (void *)cd); - } -} - -/* -=begin ---- Iconv.iconv(to, from, *strs) - Shorthand for - Iconv.open(to, from) {|cd| (strs + nil).collect {|s| cd.iconv(s)}} - :Parameters - :((|to|)), ((|from|)) - see (()). - :((|strs|)) - strings to be converted. - :Exceptions - exceptions thrown by (()), (()) and - (()). -=end -*/ - -static VALUE -iconv_s_convert -#ifdef HAVE_PROTOTYPES -(struct iconv_env_t* env) -#else /* HAVE_PROTOTYPES */ - (env) - struct iconv_env_t *env; -#endif /* HAVE_PROTOTYPES */ -{ - VALUE last = 0; - - for (; env->argc > 0; --env->argc, ++env->argv) { - VALUE s = iconv_convert(env->cd, last = *(env->argv), 0, -1, env); - rb_funcall3(env->ret, rb_inserter, 1, &s); - } - - if (!NIL_P(last)) { - VALUE s = iconv_convert(env->cd, Qnil, 0, 0, env); - if (RSTRING(s)->len) - rb_funcall3(env->ret, rb_inserter, 1, &s); - } - - return env->ret; -} - -static VALUE -iconv_s_iconv -#ifdef HAVE_PROTOTYPES -(int argc, VALUE *argv, VALUE self) -#else /* HAVE_PROTOTYPES */ - (argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -#endif /* HAVE_PROTOTYPES */ -{ - struct iconv_env_t arg; - - if (argc < 2) /* needs `to' and `from' arguments at least */ - rb_raise(rb_eArgError, "wrong # of arguments (%d for %d)", argc, 2); - - arg.argc = argc -= 2; - arg.argv = argv + 2; - arg.ret = rb_ary_new2(argc); - arg.cd = iconv_create(argv[0], argv[1]); - return rb_ensure(iconv_s_convert, (VALUE)&arg, iconv_free, ICONV2VALUE(arg.cd)); -} - - -/* -=begin -=== Instance methods -=end -*/ -/* -=begin ---- Iconv#close - Finishes conversion. - * After calling this, invoking method (()) will cause - exception, but multiple calls of (({close})) are guaranteed to - end successfully. - * Returns a string contains the byte sequence to change the - output buffer to its initial shift state. -=end -*/ -static VALUE -iconv_init_state -#ifdef HAVE_PROTOTYPES -(VALUE cd) -#else /* HAVE_PROTOTYPES */ - (cd) - VALUE cd; -#endif /* HAVE_PROTOTYPES */ -{ - return iconv_convert(VALUE2ICONV(cd), Qnil, 0, 0, NULL); -} - -static VALUE -iconv_finish -#ifdef HAVE_PROTOTYPES -(VALUE self) -#else /* HAVE_PROTOTYPES */ - (self) - VALUE self; -#endif /* HAVE_PROTOTYPES */ -{ - VALUE cd; - - Check_Type(self, T_DATA); - - cd = (VALUE)DATA_PTR(self); - if (!cd) return Qnil; - DATA_PTR(self) = NULL; - - return rb_ensure(iconv_init_state, cd, iconv_free, cd); -} - -/* -=begin ---- Iconv#iconv(str, [ start = 0, [ length = -1 ] ]) - Converts string and returns converted one. - * In the case of ((|str|)) is (({String})), converts (({str[start, length]})). - Returns converted string. - * In the case of ((|str|)) is (({nil})), places ((|converter|)) - itself into initial shift state and just returns a string contains - the byte sequence to change the output buffer to its initial shift - state. - * Otherwise, causes exception. - :Parameters - :((|str|)) - string to be converted or (({nil})). - :((|start|)) - starting offset. - :((|length|)) - conversion length, - (({nil})) or (({-1})) means whole string from (({start})). - :Exceptions - * (()) - * (()) - * (()) -=end -*/ -static VALUE -iconv_iconv -#ifdef HAVE_PROTOTYPES -(int argc, VALUE *argv, VALUE self) -#else /* HAVE_PROTOTYPES */ - (argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -#endif /* HAVE_PROTOTYPES */ -{ - VALUE str, n1, n2; - - Check_Type(self, T_DATA); - - n1 = n2 = Qnil; - rb_scan_args(argc, argv, "12", &str, &n1, &n2); - - return iconv_convert(VALUE2ICONV(DATA_PTR(self)), str, - NIL_P(n1) ? 0 : NUM2INT(n1), - NIL_P(n2) ? -1 : NUM2INT(n1), - NULL); -} - - -/* -=begin -= Exceptions -=end -*/ -/* -=begin -== Iconv::Failure -Base exceptional attributes from (()). - -=== Instance methods -=end -*/ -/* -=begin ---- Iconv::Failure#success - Returns string(s) translated successfully until the exception occurred. - * In the case of failure occurred within (()), returned - value is an array of strings translated successfully preceding - failure and the last element is string on the way. -=end -*/ -static VALUE -iconv_failure_success -#ifdef HAVE_PROTOTYPES -(VALUE self) -#else /* HAVE_PROTOTYPES */ - (self) - VALUE self; -#endif /* HAVE_PROTOTYPES */ -{ - return rb_ivar_get(self, rb_success); -} - -/* -=begin ---- Iconv::Failure#failed - Returns substring of the original string passed to (()) that - starts at the character caused the exception. -=end -*/ -static VALUE -iconv_failure_failed -#ifdef HAVE_PROTOTYPES -(VALUE self) -#else /* HAVE_PROTOTYPES */ - (self) - VALUE self; -#endif /* HAVE_PROTOTYPES */ -{ - return rb_ivar_get(self, rb_failed); -} - -/* -=begin ---- Iconv::Failure#inspect - Returns inspected string like as: #<(({type})): "(({success}))", "(({failed}))"> -=end -*/ -static VALUE -iconv_failure_inspect -#ifdef HAVE_PROTOTYPES -(VALUE self) -#else /* HAVE_PROTOTYPES */ - (self) - VALUE self; -#endif /* HAVE_PROTOTYPES */ -{ - char *cname = rb_class2name(CLASS_OF(self)); - VALUE success = iconv_failure_success(self); - VALUE failed = iconv_failure_failed(self); - VALUE str = rb_str_buf_cat2(rb_str_new2("#<"), cname); - str = rb_str_buf_cat(str, ": ", 2); - str = rb_str_buf_append(str, rb_inspect(success)); - str = rb_str_buf_cat(str, ", ", 2); - str = rb_str_buf_append(str, rb_inspect(failed)); - return rb_str_buf_cat(str, ">", 1); -} - -/* - Hmmm, I don't like to write RD inside of function :-<. - -=begin -== Iconv::IllegalSequence -Exception in the case of any illegal sequence detected. -=== Superclass -(({ArgumentError})) -=== Included Modules -(()) - -== Iconv::InvalidCharacter -Exception in the case of output coding system can't express the character. -=== Superclass -(({ArgumentError})) -=== Included Modules -(()) - -== Iconv::OutOfRange -Iconv library internal error. Must not occur. -=== Superclass -(({RuntimeError})) -=== Included Modules -(()) -=end -*/ - -void -Init_iconv _((void)) -{ - VALUE rb_cIconv = rb_define_class("Iconv", rb_cData); - rb_define_singleton_method(rb_cIconv, "allocate", iconv_s_allocate, 0); - rb_define_singleton_method(rb_cIconv, "open", iconv_s_open, 2); - rb_define_singleton_method(rb_cIconv, "iconv", iconv_s_iconv, -1); - rb_define_method(rb_cIconv, "initialize", iconv_initialize, 2); - rb_define_method(rb_cIconv, "close", iconv_finish, 0); - rb_define_method(rb_cIconv, "iconv", iconv_iconv, -1); - - rb_eIconvFailure = rb_define_module_under(rb_cIconv, "Failure"); - rb_define_method(rb_eIconvFailure, "success", iconv_failure_success, 0); - rb_define_method(rb_eIconvFailure, "failed", iconv_failure_failed, 0); - rb_define_method(rb_eIconvFailure, "inspect", iconv_failure_inspect, 0); - - rb_eIconvIllegalSeq = rb_define_class_under(rb_cIconv, "IllegalSequence", rb_eArgError); - rb_eIconvInvalidChar = rb_define_class_under(rb_cIconv, "InvalidCharacter", rb_eArgError); - rb_eIconvOutOfRange = rb_define_class_under(rb_cIconv, "OutOfRange", rb_eRuntimeError); - rb_include_module(rb_eIconvIllegalSeq, rb_eIconvFailure); - rb_include_module(rb_eIconvInvalidChar, rb_eIconvFailure); - rb_include_module(rb_eIconvOutOfRange, rb_eIconvFailure); - - rb_inserter = rb_intern("<<"); - rb_success = rb_intern("success"); - rb_failed = rb_intern("failed"); - rb_mesg = rb_intern("mesg"); -} - - -/* -=begin -== Example -(1) Instantiate a new (()), use method (()). - cd = Iconv.new(to, from) - begin - input.each {|s| output << cd.iconv(s)} - output << cd.iconv(nil) # don't forget this - ensure - cd.close - end -(2) Invoke (()) with a block. - Iconv.open(to, from) do |cd| - input.each {|s| output << cd.iconv(s)} - output << cd.iconv(nil) - end -(3) Shorthand for (2). - Iconv.iconv(to, from, *input.to_a) -=end -*/ diff --git a/ext/nkf/.cvsignore b/ext/nkf/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/nkf/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/nkf/MANIFEST b/ext/nkf/MANIFEST deleted file mode 100644 index 5114a3762a..0000000000 --- a/ext/nkf/MANIFEST +++ /dev/null @@ -1,7 +0,0 @@ -MANIFEST -depend -extconf.rb -lib/kconv.rb -nkf.c -nkf1.7/nkf.c -test.rb diff --git a/ext/nkf/depend b/ext/nkf/depend deleted file mode 100644 index 13e32e6074..0000000000 --- a/ext/nkf/depend +++ /dev/null @@ -1 +0,0 @@ -nkf.o : nkf.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h $(srcdir)/nkf1.7/nkf.c diff --git a/ext/nkf/extconf.rb b/ext/nkf/extconf.rb deleted file mode 100644 index 710662f19c..0000000000 --- a/ext/nkf/extconf.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'mkmf' -create_makefile('nkf') diff --git a/ext/nkf/lib/kconv.rb b/ext/nkf/lib/kconv.rb deleted file mode 100644 index af6d82275f..0000000000 --- a/ext/nkf/lib/kconv.rb +++ /dev/null @@ -1,73 +0,0 @@ -require 'nkf' - -module Kconv - AUTO = NKF::AUTO - JIS = NKF::JIS - EUC = NKF::EUC - SJIS = NKF::SJIS - BINARY = NKF::BINARY - NOCONV = NKF::NOCONV - UNKNOWN = NKF::UNKNOWN - def kconv(str, out_code, in_code = AUTO) - opt = '-' - case in_code - when NKF::JIS - opt << 'J' - when NKF::EUC - opt << 'E' - when NKF::SJIS - opt << 'S' - end - - case out_code - when NKF::JIS - opt << 'j' - when NKF::EUC - opt << 'e' - when NKF::SJIS - opt << 's' - when NKF::NOCONV - return str - end - - opt = '' if opt == '-' - - NKF::nkf(opt, str) - end - module_function :kconv - - def tojis(str) - NKF::nkf('-j', str) - end - module_function :tojis - - def toeuc(str) - NKF::nkf('-e', str) - end - module_function :toeuc - - def tosjis(str) - NKF::nkf('-s', str) - end - module_function :tosjis - - def guess(str) - NKF::guess(str) - end - module_function :guess -end - -class String - def kconv(out_code, in_code=Kconv::AUTO) - Kconv::kconv(self, out_code, in_code) - end - def tojis - NKF::nkf('-j', self) - end - def toeuc - NKF::nkf('-e', self) - end - def tosjis - NKF::nkf('-s', self) - end -end diff --git a/ext/nkf/nkf.c b/ext/nkf/nkf.c deleted file mode 100644 index 50723467cd..0000000000 --- a/ext/nkf/nkf.c +++ /dev/null @@ -1,197 +0,0 @@ -#include "ruby.h" - -#define _AUTO 0 -#define _JIS 1 -#define _EUC 2 -#define _SJIS 3 -#define _BINARY 4 -#define _NOCONV 4 -#define _UNKNOWN _AUTO - -#undef getc -#undef ungetc -#define getc(f) (input_ctr= o_len) { - o_len += incsize; - rb_str_cat(dst, 0, incsize); - output = RSTRING(dst)->ptr; - incsize *= 2; - } - output[output_ctr++] = c; - - return c; -} - -#define PERL_XS 1 -#include "nkf1.7/nkf.c" - -static VALUE -rb_nkf_kconv(obj, opt, src) - VALUE obj, opt, src; -{ - char *opt_ptr, *opt_end; - volatile VALUE v; - - reinit(); - StringValue(opt); - opt_ptr = RSTRING(opt)->ptr; - opt_end = opt_ptr + RSTRING(opt)->len; - for (; opt_ptr < opt_end; opt_ptr++) { - if (*opt_ptr != '-') { - continue; - } - arguments(opt_ptr); - } - - incsize = INCSIZE; - - input_ctr = 0; - StringValue(src); - input = RSTRING(src)->ptr; - i_len = RSTRING(src)->len; - dst = rb_str_new(0, i_len*3 + 10); - v = dst; - - output_ctr = 0; - output = RSTRING(dst)->ptr; - o_len = RSTRING(dst)->len; - *output = '\0'; - - if(iso8859_f && (oconv != j_oconv || !x0201_f )) { - iso8859_f = FALSE; - } - - kanji_convert(NULL); - RSTRING(dst)->ptr[output_ctr] = '\0'; - RSTRING(dst)->len = output_ctr; - OBJ_INFECT(dst, src); - - return dst; -} - -/* - * Character code detection - Algorithm described in: - * Ken Lunde. `Understanding Japanese Information Processing' - * Sebastopol, CA: O'Reilly & Associates. - */ - -static VALUE -rb_nkf_guess(obj, src) - VALUE obj, src; -{ - unsigned char *p; - unsigned char *pend; - int sequence_counter = 0; - - StringValue(src); - p = RSTRING(src)->ptr; - pend = p + RSTRING(src)->len; - -#define INCR do {\ - p++;\ - if (p==pend) return INT2FIX(_UNKNOWN);\ - sequence_counter++;\ - if (sequence_counter % 2 == 1 && *p != 0xa4)\ - sequence_counter = 0;\ - if (6 <= sequence_counter) {\ - sequence_counter = 0;\ - return INT2FIX(_EUC);\ - }\ -} while (0) - - if (*p == 0xa4) - sequence_counter = 1; - - while (p= 0x40) { - if (*p >= 0x81) { - if (*p <= 0x8d || (0x8f <= *p && *p <= 0x9f)) { - return INT2FIX(_SJIS); - } - else if (0xfd <= *p && *p <= 0xfe) { - return INT2FIX(_EUC); - } - } - INCR; - } - } - else if (*p <= 0x9f) { - return INT2FIX(_SJIS); - } - } - else if (0xf0 <= *p && *p <= 0xfe) { - return INT2FIX(_EUC); - } - else if (0xe0 <= *p && *p <= 0xef) { - INCR; - if ((0x40 <= *p && *p <= 0x7e) || - (0x80 <= *p && *p <= 0xa0)) { - return INT2FIX(_SJIS); - } - if (0xfd <= *p && *p <= 0xfe) { - return INT2FIX(_EUC); - } - } - INCR; - } - return INT2FIX(_UNKNOWN); -} - -void -Init_nkf() -{ - VALUE mKconv = rb_define_module("NKF"); - - rb_define_module_function(mKconv, "nkf", rb_nkf_kconv, 2); - rb_define_module_function(mKconv, "guess", rb_nkf_guess, 1); - - rb_define_const(mKconv, "AUTO", INT2FIX(_AUTO)); - rb_define_const(mKconv, "JIS", INT2FIX(_JIS)); - rb_define_const(mKconv, "EUC", INT2FIX(_EUC)); - rb_define_const(mKconv, "SJIS", INT2FIX(_SJIS)); - rb_define_const(mKconv, "BINARY", INT2FIX(_BINARY)); - rb_define_const(mKconv, "NOCONV", INT2FIX(_NOCONV)); - rb_define_const(mKconv, "UNKNOWN", INT2FIX(_UNKNOWN)); -} diff --git a/ext/nkf/nkf1.7/nkf.c b/ext/nkf/nkf1.7/nkf.c deleted file mode 100644 index 09419f40a7..0000000000 --- a/ext/nkf/nkf1.7/nkf.c +++ /dev/null @@ -1,1900 +0,0 @@ -/** Network Kanji Filter. (PDS Version) -************************************************************************ -** Copyright (C) 1987, Fujitsu LTD. (Itaru ICHIKAWA) -** $BO"Mm@h!'(B $B!J3t!KIY;NDL8&5f=j!!%=%U%H#38&!!;T@n!!;j(B -** $B!J(BE-Mail Address: ichikawa@flab.fujitsu.co.jp$B!K(B -** Copyright (C) 1996,1998 -** $BO"Mm@h!'(B $BN05eBg3X>pJs9)3X2J(B $B2OLn(B $B??<#(B mine/X0208 support -** $B!J(BE-Mail Address: kono@ie.u-ryukyu.ac.jp$B!K(B -** $BO"Mm@h!'(B COW for DOS & Win16 & Win32 & OS/2 -** $B!J(BE-Mail Address: GHG00637@niftyserve.or.p$B!K(B -** $B$3$N%=!<%9$N$$$+$J$kJ#Z$b$7$J$$!"0-$7$+$i$:!#(B -** Everyone is permitted to do anything on this program -** including copying, modifying, improving. -** as long as you don't try to pretend that you wrote it. -** i.e., the above copyright notice has to appear in all copies. -** You don't have to ask before copying or publishing. -** THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE. -***********************************************************************/ - -static char *CopyRight = - "Copyright (C) 1987, FUJITSU LTD. (I.Ichikawa),1998 S. Kono, COW"; -static char *Version = - "1.7"; -static char *Patchlevel = - "0/9711/Shinji Kono"; - -/* -** -** -** -** USAGE: nkf [flags] [file] -** -** Flags: -** b Output is bufferred (DEFAULT) -** u Output is unbufferred -** -** t no operation -** -** j Outout code is JIS 7 bit (DEFAULT SELECT) -** s Output code is MS Kanji (DEFAULT SELECT) -** e Output code is AT&T JIS (DEFAULT SELECT) -** l Output code is JIS 7bit and ISO8859-1 Latin-1 -** -** m MIME conversion for ISO-2022-JP -** i_ Output sequence to designate JIS-kanji (DEFAULT_J) -** o_ Output sequence to designate single-byte roman characters (DEFAULT_R) -** -** r {de/en}crypt ROT13/47 -** -** v display Version -** -** T Text mode output (for MS-DOS) -** -** x Do not convert X0201 kana into X0208 -** Z Convert X0208 alphabet to ASCII -** -** f60 fold option -** -** m MIME decode -** B try to fix broken JIS, missing Escape -** B[1-9] broken level -** -** O Output to 'nkf.out' file -** d Delete \r in line feed -** c Add \r in line feed -**/ -/******************************/ -/* $B%G%U%)%k%H$N=PNO%3!<%IA*Br(B */ -/* Select DEFAULT_CODE */ -#define DEFAULT_CODE_JIS -/* #define DEFAULT_CODE_SJIS */ -/* #define DEFAULT_CODE_EUC */ -/******************************/ - -#if (defined(__TURBOC__) || defined(LSI_C)) && !defined(MSDOS) -#define MSDOS -#endif - -#ifndef PERL_XS -#include -#endif - -#if defined(MSDOS) || defined(__OS2__) -#include -#include -#include -#endif - -#ifdef MSDOS -#ifdef LSI_C -#define setbinmode(fp) fsetbin(fp) -#else /* Microsoft C, Turbo C */ -#define setbinmode(fp) setmode(fileno(fp), O_BINARY) -#endif -#else /* UNIX,OS/2 */ -#define setbinmode(fp) -#endif - -#ifdef _IOFBF /* SysV and MSDOS */ -#define setvbuffer(fp, buf, size) setvbuf(fp, buf, _IOFBF, size) -#else /* BSD */ -#define setvbuffer(fp, buf, size) setbuffer(fp, buf, size) -#endif - -/*Borland C++ 4.5 EasyWin*/ -#if defined(__TURBOC__) && defined(_Windows) && !defined(__WIN32__) /*Easy Win */ -#define EASYWIN -#include -#endif - -#define FALSE 0 -#define TRUE 1 - -/* state of output_mode and input_mode */ - -#define ASCII 0 -#define X0208 1 -#define X0201 2 -#define NO_X0201 3 -#define JIS_INPUT 4 -#define SJIS_INPUT 5 -#define LATIN1_INPUT 6 -#define FIXED_MIME 7 -#define DOUBLE_SPACE -2 - -#define NL 0x0a -#define ESC 0x1b -#define SPACE 0x20 -#define AT 0x40 -#define SSP 0xa0 -#define DEL 0x7f -#define SI 0x0f -#define SO 0x0e -#define SSO 0x8e - -#define HOLD_SIZE 32 -#define IOBUF_SIZE 16384 - -#define DEFAULT_J 'B' -#define DEFAULT_R 'B' - -#define SJ0162 0x00e1 /* 01 - 62 ku offset */ -#define SJ6394 0x0161 /* 63 - 94 ku offset */ - - -/* MIME preprocessor */ - -#undef STRICT_MIME /* do stupid strict mime integrity check */ -#define GETC(p) ((!mime_mode)?getc(p):mime_getc(p)) -#define UNGETC(c,p) ((!mime_mode)?ungetc(c,p):mime_ungetc(c)) - - -#ifdef EASYWIN /*Easy Win */ -extern POINT _BufferSize; -#endif - -/* function prototype */ - -#ifndef _ -# ifdef __STDC__ -# define _(args) args -# else -# define _(args) () -# endif -#endif - -#ifndef PERL_XS -static void noconvert _((FILE *f)); -static int mime_integrity _((FILE *f,unsigned char *p)); -static int usage _((void)); -static char stdibuf[IOBUF_SIZE]; -static char stdobuf[IOBUF_SIZE]; -static unsigned int mime_input = 0; /* undecoded */ -static int end_check; -#endif - -static void kanji_convert _((FILE *f)); -static void h_conv _((FILE *f,int c2,int c1)); -static int push_hold_buf _((int c2,int c1)); -static void s_iconv _((int c2,int c1)); -static void e_oconv _((int c2,int c1)); -static void s_oconv _((int c2,int c1)); -static void j_oconv _((int c2,int c1)); -static int line_fold _((int c2,int c1)); -static int pre_convert _((int c1,int c2)); -static int mime_begin _((FILE *f)); -static int mime_getc _((FILE *f)); -static int mime_ungetc _((unsigned int c)); -static int base64decode _((int c)); -static void arguments _((char *c)); -static void reinit _((void)); - -/* buffers */ - -static unsigned char hold_buf[HOLD_SIZE*2]; -static int hold_count; - -/* MIME preprocessor fifo */ - -#define MIME_BUF_SIZE (1024) /* 2^n ring buffer */ -#define MIME_BUF_MASK (MIME_BUF_SIZE-1) -#define Fifo(n) mime_buf[(n)&MIME_BUF_MASK] -static unsigned char mime_buf[MIME_BUF_SIZE]; -static unsigned int mime_top = 0; -static unsigned int mime_last = 0; /* decoded */ - -/* flags */ -static int unbuf_f = FALSE; -static int estab_f = FALSE; -static int nop_f = FALSE; -static int binmode_f = TRUE; /* binary mode */ -static int rot_f = FALSE; /* rot14/43 mode */ -static int input_f = FALSE; /* non fixed input code */ -static int alpha_f = FALSE; /* convert JIx0208 alphbet to ASCII */ -static int mime_f = TRUE; /* convert MIME B base64 or Q */ -static int mimebuf_f = FALSE; /* MIME buffered input */ -static int broken_f = FALSE; /* convert ESC-less broken JIS */ -static int iso8859_f = FALSE; /* ISO8859 through */ -#if defined(MSDOS) || defined(__OS2__) -static int x0201_f = TRUE; /* Assume JISX0201 kana */ -#else -static int x0201_f = NO_X0201; /* Assume NO JISX0201 */ -#endif - -/* X0208 -> ASCII converter */ - -static int c1_return; - -/* fold parameter */ -static int line = 0; /* chars in line */ -static int prev = 0; -static int fold_f = FALSE; -static int fold_len = 0; - -/* options */ -static char kanji_intro = DEFAULT_J, - ascii_intro = DEFAULT_R; - -/* Folding */ - -int line_fold(); -#define FOLD_MARGIN 10 -#define DEFAULT_FOLD 60 - -/* converters */ - -#ifdef DEFAULT_CODE_JIS -# define DEFAULT_CONV j_oconv -#endif -#ifdef DEFAULT_CODE_SJIS -# define DEFAULT_CONV s_oconv -#endif -#ifdef DEFAULT_CODE_EUC -# define DEFAULT_CONV e_oconv -#endif - -static void (*iconv) _((int c2,int c1)); - /* s_iconv or oconv */ -static void (*oconv) _((int c2,int c1)) = DEFAULT_CONV; - /* [ejs]_oconv */ - -/* Global states */ -static int output_mode = ASCII, /* output kanji mode */ - input_mode = ASCII, /* input kanji mode */ - shift_mode = FALSE; /* TRUE shift out, or X0201 */ -static int mime_mode = FALSE; /* MIME mode B base64, Q hex */ - -/* X0201 / X0208 conversion tables */ - -/* X0201 kana conversion table */ -/* 90-9F A0-DF */ -unsigned char cv[]= { -0x21,0x21,0x21,0x23,0x21,0x56,0x21,0x57, -0x21,0x22,0x21,0x26,0x25,0x72,0x25,0x21, -0x25,0x23,0x25,0x25,0x25,0x27,0x25,0x29, -0x25,0x63,0x25,0x65,0x25,0x67,0x25,0x43, -0x21,0x3c,0x25,0x22,0x25,0x24,0x25,0x26, -0x25,0x28,0x25,0x2a,0x25,0x2b,0x25,0x2d, -0x25,0x2f,0x25,0x31,0x25,0x33,0x25,0x35, -0x25,0x37,0x25,0x39,0x25,0x3b,0x25,0x3d, -0x25,0x3f,0x25,0x41,0x25,0x44,0x25,0x46, -0x25,0x48,0x25,0x4a,0x25,0x4b,0x25,0x4c, -0x25,0x4d,0x25,0x4e,0x25,0x4f,0x25,0x52, -0x25,0x55,0x25,0x58,0x25,0x5b,0x25,0x5e, -0x25,0x5f,0x25,0x60,0x25,0x61,0x25,0x62, -0x25,0x64,0x25,0x66,0x25,0x68,0x25,0x69, -0x25,0x6a,0x25,0x6b,0x25,0x6c,0x25,0x6d, -0x25,0x6f,0x25,0x73,0x21,0x2b,0x21,0x2c, -0x00,0x00}; - - -/* X0201 kana conversion table for daguten */ -/* 90-9F A0-DF */ -unsigned char dv[]= { -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x25,0x2c,0x25,0x2e, -0x25,0x30,0x25,0x32,0x25,0x34,0x25,0x36, -0x25,0x38,0x25,0x3a,0x25,0x3c,0x25,0x3e, -0x25,0x40,0x25,0x42,0x25,0x45,0x25,0x47, -0x25,0x49,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x25,0x50,0x25,0x53, -0x25,0x56,0x25,0x59,0x25,0x5c,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00}; - -/* X0201 kana conversion table for han-daguten */ -/* 90-9F A0-DF */ -unsigned char ev[]= { -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x25,0x51,0x25,0x54, -0x25,0x57,0x25,0x5a,0x25,0x5d,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00}; - - -/* X0208 kigou conversion table */ -/* 0x8140 - 0x819e */ -unsigned char fv[] = { - -0x00,0x00,0x00,0x00,0x2c,0x2e,0x00,0x3a, -0x3b,0x3f,0x21,0x00,0x00,0x27,0x60,0x00, -0x5e,0x00,0x5f,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x2d,0x00,0x2f, -0x5c,0x00,0x00,0x7c,0x00,0x00,0x60,0x27, -0x22,0x22,0x28,0x29,0x00,0x00,0x5b,0x5d, -0x7b,0x7d,0x3c,0x3e,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x2b,0x2d,0x00,0x00, -0x00,0x3d,0x00,0x3c,0x3e,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x24,0x00,0x00,0x25,0x23,0x26,0x2a,0x40, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 -} ; - - -static int file_out = FALSE; -static int add_cr = FALSE; -static int del_cr = FALSE; - -#ifndef PERL_XS -int -main(argc, argv) - int argc; - char **argv; -{ - FILE *fin; - char *cp; - -#ifdef EASYWIN /*Easy Win */ - _BufferSize.y = 400;/*Set Scroll Buffer Size*/ -#endif - - for (argc--,argv++; (argc > 0) && **argv == '-'; argc--, argv++) { - cp = *argv; - arguments(cp); - } - - if(iso8859_f && (oconv != j_oconv || !x0201_f )) { - fprintf(stderr,"Mixed ISO8859/JISX0201/SJIS/EUC output is not allowed.\n"); - exit(1); - } - - if(binmode_f == TRUE) -#ifdef __OS2__ - if(freopen("","wb",stdout) == NULL) - return (-1); -#else - setbinmode(stdout); -#endif - - if(unbuf_f) - setbuf(stdout, (char *) NULL); - else - setvbuffer(stdout, stdobuf, IOBUF_SIZE); - - if(argc == 0) { - if(binmode_f == TRUE) -#ifdef __OS2__ - if(freopen("","rb",stdin) == NULL) return (-1); -#else - setbinmode(stdin); -#endif - setvbuffer(stdin, stdibuf, IOBUF_SIZE); - if(nop_f) - noconvert(stdin); - else - kanji_convert(stdin); - } else { - while (argc--) { - if((fin = fopen(*argv++, "r")) == NULL) { - perror(*--argv); - return(-1); - } else { -/* reopen file for stdout */ - if(file_out == TRUE){ - if(argc == 1 ) { - if(freopen(*argv++, "w", stdout) == NULL) { - perror(*--argv); - return (-1); - } - argc--; - } else { - if(freopen("nkf.out", "w", stdout) == NULL) { - perror(*--argv); - return (-1); - } - } - if(binmode_f == TRUE) { -#ifdef __OS2__ - if(freopen("","wb",stdout) == NULL) - return (-1); -#else - setbinmode(stdout); -#endif - } - } - if(binmode_f == TRUE) -#ifdef __OS2__ - if(freopen("","rb",fin) == NULL) - return (-1); -#else - setbinmode(fin); -#endif - setvbuffer(fin, stdibuf, IOBUF_SIZE); - if(nop_f) - noconvert(fin); - else - kanji_convert(fin); - fclose(fin); - } - } - } -#ifdef EASYWIN /*Easy Win */ - if(file_out == FALSE) - scanf("%d",&end_check); - else - fclose(stdout); -#else /* for Other OS */ - if(file_out == TRUE) - fclose(stdout); -#endif - return (0); -} -#endif - -static void -arguments(cp) - char *cp; -{ - while (*cp) { - switch (*cp++) { - case 'b': /* buffered mode */ - unbuf_f = FALSE; - continue; - case 'u': /* non bufferd mode */ - unbuf_f = TRUE; - continue; - case 't': /* transparent mode */ - nop_f = TRUE; - continue; - case 'j': /* JIS output */ - case 'n': - oconv = j_oconv; - continue; - case 'e': /* AT&T EUC output */ - oconv = e_oconv; - continue; - case 's': /* SJIS output */ - oconv = s_oconv; - continue; - case 'l': /* ISO8859 Latin-1 support, no conversion */ - iso8859_f = TRUE; /* Only compatible with ISO-2022-JP */ - input_f = LATIN1_INPUT; - continue; - case 'i': /* Kanji IN ESC-$-@/B */ - if(*cp=='@'||*cp=='B') - kanji_intro = *cp++; - continue; - case 'o': /* ASCII IN ESC-(-J/B */ - if(*cp=='J'||*cp=='B'||*cp=='H') - ascii_intro = *cp++; - continue; - case 'r': - rot_f = TRUE; - continue; -#if defined(MSDOS) || defined(__OS2__) - case 'T': - binmode_f = FALSE; - continue; -#endif -#ifndef PERL_XS - case 'v': - usage(); - exit(1); - break; -#endif - /* Input code assumption */ - case 'J': /* JIS input */ - case 'E': /* AT&T EUC input */ - input_f = JIS_INPUT; - continue; - case 'S': /* MS Kanji input */ - input_f = SJIS_INPUT; - if(x0201_f==NO_X0201) x0201_f=TRUE; - continue; - case 'Z': /* Convert X0208 alphabet to asii */ - /* bit:0 Convert X0208 - bit:1 Convert Kankaku to one space - bit:2 Convert Kankaku to two spaces - */ - if('9'>= *cp && *cp>='0') - alpha_f |= 1<<(*cp++ -'0'); - else - alpha_f |= TRUE; - continue; - case 'x': /* Convert X0201 kana to X0208 or X0201 Conversion */ - x0201_f = FALSE; /* No X0201->X0208 conversion */ - /* accept X0201 - ESC-(-I in JIS, EUC, MS Kanji - SI/SO in JIS, EUC, MS Kanji - SSO in EUC, JIS, not in MS Kanji - MS Kanji (0xa0-0xdf) - output X0201 - ESC-(-I in JIS (0x20-0x5f) - SSO in EUC (0xa0-0xdf) - 0xa0-0xd in MS Kanji (0xa0-0xdf) - */ - continue; - case 'X': /* Assume X0201 kana */ - /* Default value is NO_X0201 for EUC/MS-Kanji mix */ - x0201_f = TRUE; - continue; - case 'f': /* folding -f60 or -f */ - fold_f = TRUE; - fold_len = atoi(cp); - if(!(0= *cp && *cp>='0') - broken_f |= 1<<(*cp++ -'0'); - else - broken_f |= TRUE; - continue; -#ifndef PERL_XS - case 'O':/* for Output file */ - file_out = TRUE; - continue; -#endif - case 'c':/* add cr code */ - add_cr = TRUE; - continue; - case 'd':/* delete cr code */ - del_cr = TRUE; - continue; - default: - /* bogus option but ignored */ - continue; - } - } -} - -#ifndef PERL_XS -static void -noconvert(f) - FILE *f; -{ - int c; - - while ((c = getc(f)) != EOF) - putchar(c); -} -#endif - - -static void -kanji_convert(f) - FILE *f; -{ - int c1, c2; - - c2 = 0; - - if(input_f == JIS_INPUT || input_f == LATIN1_INPUT) { - estab_f = TRUE; iconv = oconv; - } else if(input_f == SJIS_INPUT) { - estab_f = TRUE; iconv = s_iconv; - } else { - estab_f = FALSE; iconv = oconv; - } - input_mode = ASCII; - output_mode = ASCII; - shift_mode = FALSE; - -#define NEXT continue /* no output, get next */ -#define SEND ; /* output c1 and c2, get next */ -#define LAST break /* end of loop, go closing */ - - while ((c1 = GETC(f)) != EOF) { - if(c2) { - /* second byte */ - if(c2 > DEL) { - /* in case of 8th bit is on */ - if(!estab_f) { - /* in case of not established yet */ - if(c1 > SSP) { - /* It is still ambiguious */ - h_conv(f, c2, c1); - c2 = 0; - NEXT; - } else if(c1 < AT) { - /* ignore bogus code */ - c2 = 0; - NEXT; - } else { - /* established */ - /* it seems to be MS Kanji */ - estab_f = TRUE; - iconv = s_iconv; - SEND; - } - } else - /* in case of already established */ - if(c1 < AT) { - /* ignore bogus code */ - c2 = 0; - NEXT; - } else - SEND; - } else - /* 7 bit code */ - /* it might be kanji shitfted */ - if((c1 == DEL) || (c1 <= SPACE)) { - /* ignore bogus first code */ - c2 = 0; - NEXT; - } else - SEND; - } else { - /* first byte */ - if(c1 > DEL) { - /* 8 bit code */ - if(!estab_f && !iso8859_f) { - /* not established yet */ - if(c1 < SSP) { - /* it seems to be MS Kanji */ - estab_f = TRUE; - iconv = s_iconv; - } else if(c1 < 0xe0) { - /* it seems to be EUC */ - estab_f = TRUE; - iconv = oconv; - } else { - /* still ambiguious */ - } - c2 = c1; - NEXT; - } else { /* estab_f==TRUE */ - if(iso8859_f) { - SEND; - } else if(SSP<=c1 && c1<0xe0 && iconv == s_iconv) { - /* SJIS X0201 Case... */ - /* This is too arrogant, but ... */ - if(x0201_f==NO_X0201) { - iconv = oconv; - c2 = c1; - NEXT; - } else - if(x0201_f) { - if(dv[(c1-SSP)*2]||ev[(c1-SSP)*2]) { - /* look ahead for X0201/X0208conversion */ - if((c2 = GETC(f)) == EOF) { - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - LAST; - } else if(c2==(0xde)) { /* $BByE@(B */ - (*oconv)(dv[(c1-SSP)*2],dv[(c1-SSP)*2+1]); - c2=0; - NEXT; - } else if(c2==(0xdf)&&ev[(c1-SSP)*2]) { - /* $BH>ByE@(B */ - (*oconv)(ev[(c1-SSP)*2],ev[(c1-SSP)*2+1]); - c2=0; - NEXT; - } - UNGETC(c2,f); c2 = 0; - } - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - NEXT; - } else - SEND; - } else if(c1==SSO && iconv != s_iconv) { - /* EUC X0201 Case */ - /* This is too arrogant - if(x0201_f == NO_X0201) { - estab_f = FALSE; - c2 = 0; - NEXT; - } */ - c1 = GETC(f); /* skip SSO */ - euc_1byte_check: - if(x0201_f && SSP<=c1 && c1<0xe0) { - if(dv[(c1-SSP)*2]||ev[(c1-SSP)*2]) { - if((c2 = GETC(f)) == EOF) { - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - LAST; - } - /* forward lookup $BByE@(B/$BH>ByE@(B */ - if(c2 != SSO) { - UNGETC(c2,f); c2 = 0; - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - NEXT; - } else if((c2 = GETC(f)) == EOF) { - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - (*oconv)(0,SSO); - LAST; - } else if(c2==(0xde)) { /* $BByE@(B */ - (*oconv)(dv[(c1-SSP)*2],dv[(c1-SSP)*2+1]); - c2=0; - NEXT; - } else if(c2==(0xdf)&&ev[(c1-SSP)*2]) { - /* $BH>ByE@(B */ - (*oconv)(ev[(c1-SSP)*2],ev[(c1-SSP)*2+1]); - c2=0; - NEXT; - } else { - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - /* we have to check this c2 */ - /* and no way to push back SSO */ - c1 = c2; c2 = 0; - goto euc_1byte_check; - } - } - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - NEXT; - } else - SEND; - } else if(c1 < SSP && iconv != s_iconv) { - /* strange code in EUC */ - iconv = s_iconv; /* try SJIS */ - c2 = c1; - NEXT; - } else { - /* already established */ - c2 = c1; - NEXT; - } - } - } else if((c1 > SPACE) && (c1 != DEL)) { - /* in case of Roman characters */ - if(shift_mode) { - c1 |= 0x80; - /* output 1 shifted byte */ - if(x0201_f && (!iso8859_f||input_mode==X0201) && - SSP<=c1 && c1<0xe0 ) { - if(dv[(c1-SSP)*2]||ev[(c1-SSP)*2]) { - if((c2 = GETC(f)) == EOF) { - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - LAST; - } else if(c2==(0xde&0x7f)) { /* $BByE@(B */ - (*oconv)(dv[(c1-SSP)*2],dv[(c1-SSP)*2+1]); - c2=0; - NEXT; - } else if(c2==(0xdf&0x7f)&&ev[(c1-SSP)*2]) { - /* $BH>ByE@(B */ - (*oconv)(ev[(c1-SSP)*2],ev[(c1-SSP)*2+1]); - c2=0; - NEXT; - } - UNGETC(c2,f); c2 = 0; - } - (*oconv)(cv[(c1-SSP)*2],cv[(c1-SSP)*2+1]); - NEXT; - } else - SEND; - } else if(c1 == '(' && broken_f && input_mode == X0208 - && !mime_mode ) { - /* Try to recover missing escape */ - if((c1 = GETC(f)) == EOF) { - (*oconv)(0, '('); - LAST; - } else { - if(c1 == 'B' || c1 == 'J' || c1 == 'H') { - input_mode = ASCII; shift_mode = FALSE; - NEXT; - } else { - (*oconv)(0, '('); - /* do not modify various input_mode */ - /* It can be vt100 sequence */ - SEND; - } - } - } else if(input_mode == X0208) { - /* in case of Kanji shifted */ - c2 = c1; - NEXT; - /* goto next_byte */ - } else if(c1 == '=' && mime_f && !mime_mode ) { - if((c1 = getc(f)) == EOF) { - (*oconv)(0, '='); - LAST; - } else if(c1 == '?') { - /* =? is mime conversiooon start sequence */ - if(mime_begin(f) == EOF) /* check in detail */ - LAST; - else - NEXT; - } else { - (*oconv)(0, '='); - ungetc(c1,f); - NEXT; - } - } else if(c1 == '$' && broken_f && !mime_mode) { - /* try to recover missing escape */ - if((c1 = GETC(f)) == EOF) { - (*oconv)(0, '$'); - LAST; - } else if(c1 == '@'|| c1 == 'B') { - /* in case of Kanji in ESC sequence */ - input_mode = X0208; - shift_mode = FALSE; - NEXT; - } else { - /* sorry */ - (*oconv)(0, '$'); - (*oconv)(0, c1); - NEXT; - } - } else - SEND; - } else if(c1 == SI) { - shift_mode = FALSE; - NEXT; - } else if(c1 == SO) { - shift_mode = TRUE; - NEXT; - } else if(c1 == ESC) { - if((c1 = GETC(f)) == EOF) { - (*oconv)(0, ESC); - LAST; - } else if(c1 == '$') { - if((c1 = GETC(f)) == EOF) { - (*oconv)(0, ESC); - (*oconv)(0, '$'); - LAST; - } else if(c1 == '@'|| c1 == 'B') { - /* This is kanji introduction */ - input_mode = X0208; - shift_mode = FALSE; - NEXT; - } else if(c1 == '(') { - if((c1 = GETC(f)) == EOF) { - (*oconv)(0, ESC); - (*oconv)(0, '$'); - (*oconv)(0, '('); - LAST; - } else if(c1 == '@'|| c1 == 'B') { - /* This is kanji introduction */ - input_mode = X0208; - shift_mode = FALSE; - NEXT; - } else { - (*oconv)(0, ESC); - (*oconv)(0, '$'); - (*oconv)(0, '('); - (*oconv)(0, c1); - NEXT; - } - } else if(broken_f&0x2) { - input_mode = X0208; - shift_mode = FALSE; - NEXT; - } else { - (*oconv)(0, ESC); - (*oconv)(0, '$'); - (*oconv)(0, c1); - NEXT; - } - } else if(c1 == '(') { - if((c1 = GETC(f)) == EOF) { - (*oconv)(0, ESC); - (*oconv)(0, '('); - LAST; - } else { - if(c1 == 'I') { - /* This is X0201 kana introduction */ - input_mode = X0201; shift_mode = X0201; - NEXT; - } else if(c1 == 'B' || c1 == 'J' || c1 == 'H') { - /* This is X0208 kanji introduction */ - input_mode = ASCII; shift_mode = FALSE; - NEXT; - } else if(broken_f&0x2) { - input_mode = ASCII; shift_mode = FALSE; - NEXT; - } else { - (*oconv)(0, ESC); - (*oconv)(0, '('); - /* maintain various input_mode here */ - SEND; - } - } - } else { - /* lonely ESC */ - (*oconv)(0, ESC); - SEND; - } - } else if(c1 == NL && broken_f&4) { - input_mode = ASCII; - SEND; - } else - SEND; - } - /* send: */ - if(input_mode == X0208) - (*oconv)(c2, c1); /* this is JIS, not SJIS/EUC case */ - else - (*iconv)(c2, c1); /* can be EUC/SJIS */ - c2 = 0; - continue; - /* goto next_word */ - } - - /* epilogue */ - (*iconv)(EOF, 0); -} - - - - -static void -h_conv(f, c2, c1) - FILE *f; - int c1, c2; -{ - int wc; - - - /** it must NOT be in the kanji shifte sequence */ - /** it must NOT be written in JIS7 */ - /** and it must be after 2 byte 8bit code */ - - hold_count = 0; - push_hold_buf(c2, c1); - c2 = 0; - - while ((c1 = GETC(f)) != EOF) { - if(c2) { - /* second byte */ - if(!estab_f) { - /* not established */ - if(c1 > SSP) { - /* it is still ambiguious yet */ - SEND; - } else if(c1 < AT) { - /* ignore bogus first byte */ - c2 = 0; - SEND; - } else { - /* now established */ - /* it seems to be MS Kanji */ - estab_f = TRUE; - iconv = s_iconv; - SEND; - } - } else - SEND; - } else { - /* First byte */ - if(c1 > DEL) { - /* 8th bit is on */ - if(c1 < SSP) { - /* it seems to be MS Kanji */ - estab_f = TRUE; - iconv = s_iconv; - } else if(c1 < 0xe0) { - /* it seems to be EUC */ - estab_f = TRUE; - iconv = oconv; - } else { - /* still ambiguious */ - } - c2 = c1; - NEXT; - } else - /* 7 bit code , then send without any process */ - SEND; - } - /* send: */ - if((push_hold_buf(c2, c1) == EOF) || estab_f) - break; - c2 = 0; - continue; - } - - /** now, - ** 1) EOF is detected, or - ** 2) Code is established, or - ** 3) Buffer is FULL (but last word is pushed) - ** - ** in 1) and 3) cases, we continue to use - ** Kanji codes by oconv and leave estab_f unchanged. - **/ - - for (wc = 0; wc < hold_count; wc += 2) { - c2 = hold_buf[wc]; - c1 = hold_buf[wc+1]; - (*iconv)(c2, c1); - } - return; -} - - - -static int -push_hold_buf(c2, c1) - int c2, c1; -{ - if(hold_count >= HOLD_SIZE*2) - return (EOF); - hold_buf[hold_count++] = c2; - hold_buf[hold_count++] = c1; - return ((hold_count >= HOLD_SIZE*2) ? EOF : hold_count); -} - - -static void -s_iconv(c2, c1) - int c2, - c1; -{ - if((c2 == EOF) || (c2 == 0)) { - /* NOP */ - } else { - c2 = c2 + c2 - ((c2 <= 0x9f) ? SJ0162 : SJ6394); - if(c1 < 0x9f) - c1 = c1 - ((c1 > DEL) ? SPACE : 0x1f); - else { - c1 = c1 - 0x7e; - c2++; - } - } - (*oconv)(c2, c1); -} - - -static void -e_oconv(c2, c1) - int c2, c1; -{ - c2 = pre_convert(c1,c2); c1 = c1_return; - if(fold_f) { - switch(line_fold(c2,c1)) { - case '\n': - if(add_cr == TRUE) { - putchar('\r'); - c1 = '\n'; - } - putchar('\n'); - break; - case 0: return; - case '\r': - c1 = '\n'; c2 = 0; - break; - case '\t': - case ' ': - c1 = ' '; c2 = 0; - break; - } - } - if(c2==DOUBLE_SPACE) { - putchar(' '); putchar(' '); - return; - } - if(c2 == EOF) - return; - else if(c2 == 0 && (c1&0x80)) { - putchar(SSO); putchar(c1); - } else if(c2 == 0) { - if(c1 == '\n' && add_cr == TRUE) - putchar('\r'); - if(c1 != '\r') - putchar(c1); - else if(del_cr == FALSE) - putchar(c1); - } else { - if((c1<0x20 || 0x7e> 1) + ((c2 <= 0x5e) ? 0x71 : 0xb1))); - putchar((c1 + ((c2 & 1) ? ((c1 < 0x60) ? 0x1f : 0x20) : 0x7e))); - } - return; -} - - -static void -j_oconv(c2, c1) - int c2, c1; -{ - c2 = pre_convert(c1,c2); c1 = c1_return; - if(fold_f) { - switch(line_fold(c2,c1)) { - case '\n': - if(output_mode) { - putchar(ESC); - putchar('('); - putchar(ascii_intro); - } - if(add_cr == TRUE) { - putchar('\r'); - c1 = '\n'; - } - putchar('\n'); - output_mode = ASCII; - break; - case '\r': - c1 = '\n'; c2 = 0; - break; - case '\t': - case ' ': - c1 = ' '; c2 = 0; - break; - case 0: return; - } - } - if(c2 == EOF) { - if(output_mode) { - putchar(ESC); - putchar('('); - putchar(ascii_intro); - } - } else if(c2 == 0 && (c1 & 0x80)) { - if(input_mode==X0201 || !iso8859_f) { - if(output_mode!=X0201) { - putchar(ESC); - putchar('('); - putchar('I'); - output_mode = X0201; - } - c1 &= 0x7f; - } else { - /* iso8859 introduction, or 8th bit on */ - /* Can we convert in 7bit form using ESC-'-'-A ? - Is this popular? */ - } - putchar(c1); - } else if(c2 == 0) { - if(output_mode) { - putchar(ESC); - putchar('('); - putchar(ascii_intro); - output_mode = ASCII; - } - if(c1 == '\n' && add_cr == TRUE) - putchar('\r'); - if(c1 != '\r') - putchar(c1); - else if(del_cr == FALSE) - putchar(c1); - } else if(c2 == DOUBLE_SPACE) { - if(output_mode) { - putchar(ESC); - putchar('('); - putchar(ascii_intro); - output_mode = ASCII; - } - putchar(' '); - if(c1 == '\n' && add_cr == TRUE) - putchar('\r'); - if(c1 != '\r') - putchar(c1); - else if(del_cr == FALSE) - putchar(c1); - } else { - if(output_mode != X0208) { - putchar(ESC); - putchar('$'); - putchar(kanji_intro); - output_mode = X0208; - } - if(c1<0x20 || 0x7e0x80 Japanese (X0208/X0201) - <0x80 ASCII - \n new line - ' ' space - - This fold algorthm does not preserve heading space in a line. - This is the main difference from fmt. -*/ - -static int -line_fold(c2,c1) -int c2,c1; -{ - int prev0; - if(c1=='\r') - return 0; /* ignore cr */ - if(c1== 8) { - if(line>0) line--; - return 1; - } - if(c2==EOF && line != 0) /* close open last line */ - return '\n'; - /* new line */ - if(c1=='\n') { - if(prev == c1) { /* duplicate newline */ - if(line) { - line = 0; - return '\n'; /* output two newline */ - } else { - line = 0; - return 1; - } - } else { - if(prev&0x80) { /* Japanese? */ - prev = c1; - return 0; /* ignore given single newline */ - } else if(prev==' ') { - return 0; - } else { - prev = c1; - if(++line<=fold_len) - return ' '; - else { - line = 0; - return '\r'; /* fold and output nothing */ - } - } - } - } - if(c1=='\f') { - prev = '\n'; - if(line==0) - return 1; - line = 0; - return '\n'; /* output newline and clear */ - } - /* X0208 kankaku or ascii space */ - if( (c2==0&&c1==' ')|| - (c2==0&&c1=='\t')|| - (c2==DOUBLE_SPACE)|| - (c2=='!'&& c1=='!')) { - if(prev == ' ') { - return 0; /* remove duplicate spaces */ - } - prev = ' '; - if(++line<=fold_len) - return ' '; /* output ASCII space only */ - else { - prev = ' '; line = 0; - return '\r'; /* fold and output nothing */ - } - } - prev0 = prev; /* we still need this one... , but almost done */ - prev = c1; - if(c2 || (SSP<=c1 && c1<=0xdf)) - prev |= 0x80; /* this is Japanese */ - line += (c2==0)?1:2; - if(line<=fold_len) { /* normal case */ - return 1; - } - if(line>=fold_len+FOLD_MARGIN) { /* too many kinsou suspension */ - line = (c2==0)?1:2; - return '\n'; /* We can't wait, do fold now */ - } - /* simple kinsoku rules return 1 means no folding */ - if(c2==0) { - if(c1==0xde) return 1; /* $B!+(B*/ - if(c1==0xdf) return 1; /* $B!,(B*/ - if(c1==0xa4) return 1; /* $B!#(B*/ - if(c1==0xa3) return 1; /* $B!$(B*/ - if(c1==0xa1) return 1; /* $B!W(B*/ - if(c1==0xb0) return 1; /* - */ - if(SSP<=c1 && c1<=0xdf) { /* X0201 */ - line = 1; - return '\n';/* add one new line before this character */ - } - /* fold point in ASCII { [ ( */ - if(( c1!=')'&& - c1!=']'&& - c1!='}'&& - c1!='.'&& - c1!=','&& - c1!='!'&& - c1!='?'&& - c1!='/'&& - c1!=':'&& - c1!=';')&& - ((prev0=='\n')|| (prev0==' ')|| /* ignored new line */ - (prev0&0x80)) /* X0208 - ASCII */ - ) { - line = 1; - return '\n';/* add one new line before this character */ - } - return 1; /* default no fold in ASCII */ - } else { - if(c2=='!') { - if(c1=='"') return 1; /* $B!"(B */ - if(c1=='#') return 1; /* $B!#(B */ - if(c1=='$') return 1; /* $B!$(B */ - if(c1=='%') return 1; /* $B!%(B */ - if(c1=='\'') return 1; /* $B!\(B */ - if(c1=='(') return 1; /* $B!((B */ - if(c1==')') return 1; /* $B!)(B */ - if(c1=='*') return 1; /* $B!*(B */ - if(c1=='+') return 1; /* $B!+(B */ - if(c1==',') return 1; /* $B!,(B */ - } - line = 2; - return '\n'; /* add one new line before this character */ - } -} - -static int -pre_convert(c1,c2) - int c1,c2; -{ - if(c2) c1 &= 0x7f; - c1_return = c1; - if(c2==EOF) return c2; - c2 &= 0x7f; - if(rot_f) { - if(c2) { - c1 = rot47(c1); - c2 = rot47(c2); - } else { - if(!(c1 & 0x80)) - c1 = rot13(c1); - } - c1_return = c1; - } - /* JISX0208 Alphabet */ - if(alpha_f && c2 == 0x23 ) return 0; - /* JISX0208 Kigou */ - if(alpha_f && c2 == 0x21 ) { - if(0x21==c1) { - if(alpha_f&0x2) { - c1_return = ' '; - return 0; - } else if(alpha_f&0x4) { - c1_return = ' '; - return DOUBLE_SPACE; - } else { - return c2; - } - } else if(0x20' ';i++) { /* start at =? */ - if( ((((r[i] = c1 = getc(f))==EOF) || nkf_toupper(c1) != p[i] ) { - /* pattern fails, try next one */ - q = p; - while (p = mime_pattern[++j]) { - for(k=2;k i */ - if(p[k]!=q[k]) break; - if(k==i && nkf_toupper(c1)==p[k]) break; - } - if(p) continue; /* found next one, continue */ - /* all fails, output from recovery buffer */ - ungetc(c1,f); - for(j=0;j> 4) & 0x03); - if(c2 != '=') { - Fifo(mime_last++) = cc; - cc = ((t2 << 4) & 0x0f0) | ((t3 >> 2) & 0x0f); - if(c3 != '=') { - Fifo(mime_last++) = cc; - cc = ((t3 << 6) & 0x0c0) | (t4 & 0x3f); - if(c4 != '=') - Fifo(mime_last++) = cc; - } - } else { - return c1; - } - return Fifo(mime_top++); -} - -static int -mime_ungetc(c) - unsigned int c; -{ - Fifo(mime_last++) = c; - return c; -} - -#ifdef STRICT_MIME -int -mime_integrity(f,p) - FILE *f; - unsigned char *p; -{ - int c,d; - unsigned int q; - /* In buffered mode, read until =? or NL or buffer fffull - */ - mime_input = mime_top; - mime_last = mime_top; - while(*p) Fifo(mime_input++) = *p++; - d = 0; - q = mime_input; - while((c=getc(f))!=EOF) { - if(((mime_input-mime_top)&MIME_BUF_MASK)==0) break; - if(c=='=' && d=='?') { - /* checked. skip header, start decode */ - Fifo(mime_input++) = c; - mime_input = q; - return 1; - } - if(!( (c=='+'||c=='/'|| c=='=' || c=='?' || - ('a'<=c && c<='z')||('A'<= c && c<='Z')||('0'<=c && c<='9')))) - break; - /* Should we check length mod 4? */ - Fifo(mime_input++) = c; - d=c; - } - /* In case of Incomplete MIME, no MIME decode */ - Fifo(mime_input++) = c; - mime_last = mime_input; /* point undecoded buffer */ - mime_mode = 1; /* no decode on Fifo last in mime_getc */ - return 1; -} -#endif - -static int -base64decode(c) - int c; -{ - int i; - if(c > '@') - if(c < '[') - i = c - 'A'; /* A..Z 0-25 */ - else - i = c - 'G' /* - 'a' + 26 */ ; /* a..z 26-51 */ - else if(c > '/') - i = c - '0' + '4' /* - '0' + 52 */ ; /* 0..9 52-61 */ - else if(c == '+') - i = '>' /* 62 */ ; /* + 62 */ - else - i = '?' /* 63 */ ; /* / 63 */ - return (i); -} - -static void -reinit() -{ - unbuf_f = FALSE; - estab_f = FALSE; - nop_f = FALSE; - binmode_f = TRUE; - rot_f = FALSE; - input_f = FALSE; - alpha_f = FALSE; - mime_f = TRUE; - mimebuf_f = FALSE; - broken_f = FALSE; - iso8859_f = FALSE; - x0201_f = TRUE; - x0201_f = NO_X0201; - fold_f = FALSE; - kanji_intro = DEFAULT_J; - ascii_intro = DEFAULT_R; - oconv = DEFAULT_CONV; - output_mode = ASCII; - input_mode = ASCII; - shift_mode = FALSE; - mime_mode = FALSE; - file_out = FALSE; - add_cr = FALSE; - del_cr = FALSE; - line = 0; -} - -#ifndef PERL_XS -int -usage() -{ - fprintf(stderr,"USAGE: nkf(nkf32,wnkf,nkf2) -[flags] [in file] .. [out file for -O flag]\n"); - fprintf(stderr,"Flags:\n"); - fprintf(stderr,"b,u Output is bufferred (DEFAULT),Output is unbufferred\n"); -#ifdef DEFAULT_CODE_SJIS - fprintf(stderr,"j,s,e Outout code is JIS 7 bit, Shift JIS (DEFAULT), AT&T JIS (EUC)\n"); -#endif -#ifdef DEFAULT_CODE_JIS - fprintf(stderr,"j,s,e Outout code is JIS 7 bit (DEFAULT), Shift JIS, AT&T JIS (EUC)\n"); -#endif -#ifdef DEFAULT_CODE_EUC - fprintf(stderr,"j,s,e Outout code is JIS 7 bit, Shift JIS, AT&T JIS (EUC) (DEFAULT)\n"); -#endif - fprintf(stderr,"J,S,E Input assumption is JIS 7 bit , Shift JIS, AT&T JIS (EUC)\n"); - fprintf(stderr,"t no conversion\n"); - fprintf(stderr,"i_ Output sequence to designate JIS-kanji (DEFAULT B)\n"); - fprintf(stderr,"o_ Output sequence to designate ASCII (DEFAULT B)\n"); - fprintf(stderr,"r {de/en}crypt ROT13/47\n"); - fprintf(stderr,"v Show this usage\n"); - fprintf(stderr,"m[BQ0] MIME decode [B:base64,Q:quoted,0:no decode]\n"); - fprintf(stderr,"l ISO8859-1 (Latin-1) support\n"); - fprintf(stderr,"f Folding: -f60 or -f\n"); - fprintf(stderr,"Z[0-2] Convert X0208 alphabet to ASCII 1: Kankaku to space,2: 2 spaces\n"); - fprintf(stderr,"X,x Assume X0201 kana in MS-Kanji, -x preserves X0201\n"); - fprintf(stderr,"B[0-2] Broken input 0: missing ESC,1: any X on ESC-[($]-X,2: ASCII on NL\n"); -#ifdef MSDOS - fprintf(stderr,"T Text mode output\n"); -#endif - fprintf(stderr,"O Output to File (DEFAULT 'nkf.out')\n"); - fprintf(stderr,"d,c Delete \\r in line feed, Add \\r in line feed\n"); - fprintf(stderr,"Network Kanji Filter Version %s (%s) " -#if defined(MSDOS) && !defined(_Windows) - "for DOS" -#endif -#if !defined(__WIN32__) && defined(_Windows) - "for Win16" -#endif -#if defined(__WIN32__) && defined(_Windows) - "for Win32" -#endif -#ifdef __OS2__ - "for OS/2" -#endif - ,Version,Patchlevel); - fprintf(stderr,"\n%s\n",CopyRight); - return 0; -} -#endif - -/** - ** $B%Q%C%A@):n - ** ohta@src.ricoh.co.jp (Junn Ohta) - ** inouet@strl.nhk.or.jp (Tomoyuki Inoue) - ** kiri@pulser.win.or.jp (Tetsuaki Kiriyama) - ** Kimihiko Sato - ** a_kuroe@kuroe.aoba.yokohama.jp (Akihiko Kuroe) - ** kono@ie.u-ryukyu.ac.jp (Shinji Kono) - ** GHG00637@nifty-serve.or.jp (COW) - ** - ** $B:G=*99?7F|(B - ** 1998.11.7 - **/ - -/* end */ diff --git a/ext/nkf/test.rb b/ext/nkf/test.rb deleted file mode 100644 index 4519f8ba7e..0000000000 --- a/ext/nkf/test.rb +++ /dev/null @@ -1,318 +0,0 @@ -$counter = 0 -def result(result, message = nil) - $counter += 1 - printf("%s %d%s\n", - result ? 'ok' : 'no', - $counter, - message ? ' ... ' + message : '') -end - -begin - require 'nkf' - include NKF -rescue LoadError - result(false) -end -result(true) - -if nkf('-me', '1') - result(true); -else - result(false); -end - -output = nkf('-e', "\033\$@#1#3#2%B") -if output - # print output, "\n" - result(true, output) -else - result(false) -end - -output = nkf('-Zj', "\033\$@#1#3#2%B") -if output - # print output, "\n" - result(true, output) -else - result(false) -end - -output = "\244\306 " * 1024 -old = output.length -output = nkf("-j", output) -if output - # print output, "\n" - result(true, "#{old} #{output.length}") -else - result(false) -end - - -$detail = false -def test(opt, input, expect) - print "\nINPUT:\n", input if $detail - print "\nEXPECT:\n", expect if $detail - result = nkf(opt, input) - print "\nGOT:\n", result if $detail - - print result == expect ? "Ok\n" : "Fail\n" - return result -end - -# Basic Conversion -print "\nBasic Conversion test\n\n" - -example = {} -example['jis'] = <<'eofeof'.unpack('u')[0] -M1FERED"6GIAR(%-E8V]N9"!3=&%G92"8I9=Y($AI -M#28./ ->@Y*#DR!+:6=O=2"!18&'@D^"8(._@]:$081@A+X* -eofeof -#' - -example['euc'] = <<'eofeof'.unpack('u')[0] -M1FERI?*E\R!+:6=O=2"AIJ'GH["CP:;!IMBGHJ?!J,`* -eofeof -#' - -example['amb'] = <<'eofeof'.unpack('u')[0] -MI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&E -MPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*P -ML:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&E -MPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7" -ML+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"Q -MI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7" -ML+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(* -eofeof - -example['amb.euc'] = <<'eofeof'.unpack('u')[0] -M&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25" -M,#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P,25" -M,#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(; -M*$(*&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P -M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P -M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q -M)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q ->)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(* -eofeof - -example['amb.sjis'] = <<'eofeof'.unpack('u')[0] -M&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25" -M,#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P,25" -M,#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(; -M*$(*&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P -M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P -M,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q -M)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q ->)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(* -eofeof - -example['x0201.sjis'] = <<'eofeof'.unpack('u')[0] -MD5.*<(-*@TR#3H-0@U*#2X--@T^#48-3"I%3B7""8()A@F*"8X)D@F6"9H*! -M@H*"@X*$@H6"AH*'"I%3BTR-AH%)@9>!E(&0@9.!3X&5@9:!:8%J@7R!>X&! -M@6V!;H%O@7"!CPJ4O(IPMK>X/;FZMMZWWKC>N=ZZWH+&"I2\BG#*W\O?S-_- -MW\[?M]^QW@K*W\O?S`IH86YK86MU(,K?R]_,I`K*W\O?S-VA"I2\BG""S(SC -!"@!" -eofeof -#' - -example['x0201.euc'] = <<'eofeof'.unpack('u')[0] -MP;2ST:6KI:VEKZ6QI;.EK*6NI;"ELJ6T"L&TL=&CP:/"H\.CQ*/%H\:CQZ/A -MH^*CXZ/DH^6CYJ/G"L&TM:VYYJ&JH?>A]*'PH?.AL*'UH?:ARJ'+H=VAW*'A -MHCK>.WHZXCMZ.N8[>CKJ. -MWJ3("LB^L]&.RH[?CLN.WX[,CM^.S8[?CLZ.WXZWCM^.L8[>"H[*CM^.RX[? -MCLP*:&%N:V%K=2".RH[?CLN.WX[,CJ0*CLJ.WX[+CM^.S([=CJ$*R+ZST:3. -#N.4* -eofeof -#' - -example['x0201.jis'] = <<'eofeof'.unpack('u')[0] -M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA""ALD0D$T,5$C02-"(T,C -M1"-%(T8C1R-A(V(C8R-D(V4C9B-G&RA""ALD0D$T-2TY9B$J(7.5XZ7ALD0B1(&RA""ALD0D@^,U$;*$E*7TM?3%]-7TY? -M-U\Q7ALH0@H;*$E*7TM?3!LH0@IH86YK86MU(!LH24I?2U],)!LH0@H;*$E* -97TM?3%TA&RA""ALD0D@^,U$D3CAE&RA""@`` -eofeof -#` - -example['x0201.sosi'] = <<'eofeof'.unpack('u')[0] -M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA*"ALD0D$T,5$C02-"(T,C -M1"-%(T8C1R-A(V(C8R-D(V4C9B-G&RA*"ALD0D$T-2TY9B$J(7.5XZ7@\;)$(D2!LH2@H;)$)(/C-1&RA*#DI?2U],7TU? -M3E\W7S%>#PH.2E]+7TP/&RA*"FAA;FMA:W4@#DI?2U],)`\;*$H*#DI?2U], -672$/&RA*"ALD0D@^,U$D3CAE&RA""@`` -eofeof -#" - -example['x0201.x0208'] = <<'eofeof'.unpack('u')[0] -M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA""ALD0D$T,5$;*$)!0D-$ -M149'86)C9&5F9PH;)$)!-#4M.68;*$(A0",D)5XF*B@I+2L]6UU[?1LD0B%O -M&RA""ALD0D@^,U$E*R4M)2\;*$(]&R1")3$E,R4L)2XE,"4R)30D2!LH0@H; -M)$)(/C-1)5$E5"57)5HE724M(2PE(B$K&RA""ALD0B51)50E51LH0@IH86YK -M86MU(!LD0B51)50E52$B&RA""ALD0B51)50E525S(2,;*$(*&R1"2#XS421. -&.&4;*$(* -eofeof -#` - -example['mime.iso2022'] = <<'eofeof'.unpack('u')[0] -M/3])4T\M,C`R,BU*4#]"/T=Y4D%.144W96E23TI566Q/4U9)1WEH2S\]"CT_ -M:7-O+3(P,C(M2E`_0C]'>5)!3D5%-V5I4D]*55EL3U-624=Y:$L_/0H]/VES -M;RTR,#(R+4I0/U$_/3%")$(D1B11/3%"*$)?96YD/ST*&R1`)#TD)B0K)$H; -M*$H@/3])4T\M,C`R,BU*4#]"/T=Y4D%.144W96E23U!Y:S=D:'-O4V<]/3\] -M(&5N9"!O9B!L:6YE"CT_25-/+3(P,C(M2E`_0C]'>5)!3D5%-V5I4D]0>6LW -M9&AS;U-G/3T_/2`]/TE33RTR,#(R+4I0/T(_1WE204Y%13=E:5)/4'EK-V1H -M5)!3D5%-V5I -44D]*55EL3QM;2U-624=Y:$L_/0H_ -eofeof -#' - -example['mime.ans.strict'] = <<'eofeof'.unpack('u')[0] -M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11 -M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F -M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A5)!3D5%-V5I4D]*55EL3QM;2U-624=Y:$L_/0H_ -eofeof -#' - -example['mime.unbuf.strict'] = <<'eofeof'.unpack('u')[0] -M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11 -M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F -M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-AB1./RD;*$)H5)! -M3D5%-V5I4D]0>6LW9&AS;U-G/3T_/0H;)$(T03MZ)$XE1ALH0EM+4U9)1WEH -$2S\]"F5I -eofeof - -example['mime.ans'] = <<'eofeof'.unpack('u')[0] -M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11 -M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F -M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-AB1./RD;*$)HB1./RD[=ALH0@H;)$(T -603MZ)$XE1ALH0EM+4U9)1WEH2S\]"@`* -eofeof -#" - -example['mime.unbuf'] = <<'eofeof'.unpack('u')[0] -M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11 -M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F -M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-AB1./RD;*$)HB1./RD[=ALH0@H;)$(T -603MZ)$XE1ALH0EM+4U9)1WEH2S\]"@`* -eofeof -#" - -example['mime.base64'] = <<'eofeof'.unpack('u')[0] -M9W-M5"])3&YG$I+-&=Q=4,S24LS9W%Q0E%:3TUI-39,,S0Q-&=S5T)1 -M43!+9VUA1%9O3T@*9S)+1%1O3'=K8C)1;$E+;V=Q2T-X24MG9W5M0W%*3EEG -<$E+9V=U;4,X64Q&9W)70S592VMG<6U""F=Q -eofeof -#" - -example['mime.base64.ans'] = <<'eofeof'.unpack('u')[0] -M&R1")$M&?B1I)#LD1D0Z)"TD7B0Y)"PA(D5L-7XV83E9)$2P@1$5.34%22R`@7"`B36EN(&OF<&AEX0208 conversion -# X0208 aphabet -> ASCII -# X0201 Áê¸ßÊÑ´¹ - -print "\nX0201 test\n\n" - -# -X is necessary to allow X0201 in SJIS -# -Z convert X0208 alphabet to ASCII -print 'X0201 conversion: SJIS ' -test('-XZ', example['x0201.sjis'], example['x0201.x0208']) -print 'X0201 conversion: JIS ' -test('-Z', example['x0201.jis'], example['x0201.x0208']) -print 'X0201 conversion:SI/SO ' -test('-Z', example['x0201.sosi'], example['x0201.x0208']) -print 'X0201 conversion: EUC ' -test('-Z', example['x0201.euc'], example['x0201.x0208']) -# -x means X0201 output -print 'X0201 output: SJIS ' -test('-xs', example['x0201.euc'], example['x0201.sjis']) -print 'X0201 output: JIS ' -test('-xj', example['x0201.sjis'], example['x0201.jis']) -print 'X0201 output: EUC ' -test('-xe', example['x0201.jis'], example['x0201.euc']) - -# MIME decode - -print "\nMIME test\n\n" - -# MIME ISO-2022-JP - -print "Next test is expeced to Fail.\n" - -print 'MIME decode (strict) ' -tmp = test('-m', example['mime.iso2022'], example['mime.ans.strict']) -print 'MIME decode (nonstrict)' -tmp = test('-m', example['mime.iso2022'], example['mime.ans']) -# open(OUT,'>tmp1');print OUT pack('u',$tmp);close(OUT); -# unbuf mode implies more pessimistic decode -print 'MIME decode (unbuf) ' -test('-mu', example['mime.iso2022'], example['mime.unbuf']) -print 'MIME decode (base64) ' -t = test('-mB', example['mime.base64'], example['mime.base64.ans']) - -# MIME ISO-8859-1 - -# Without -l, ISO-8859-1 was handled as X0201. - -print 'MIME ISO-8859-1 (Q) ' -test('-ml', example['mime.is8859'], example['mime.is8859.ans']) diff --git a/ext/pty/.cvsignore b/ext/pty/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/pty/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/pty/MANIFEST b/ext/pty/MANIFEST deleted file mode 100644 index 0535a5b7ef..0000000000 --- a/ext/pty/MANIFEST +++ /dev/null @@ -1,12 +0,0 @@ -MANIFEST -README -README.expect -README.expect.ja -README.ja -depend -expect_sample.rb -extconf.rb -lib/expect.rb -pty.c -script.rb -shl.rb diff --git a/ext/pty/README b/ext/pty/README deleted file mode 100644 index a09469d39c..0000000000 --- a/ext/pty/README +++ /dev/null @@ -1,93 +0,0 @@ -pty extension version 0.3 by A.ito - -1. Introduction - -This extension module adds ruby a functionality to execute an -arbitrary command through pseudo tty (pty). - -2. Install - -Follow the instruction below. - -(1) Execute - - ruby extconf.rb - - then Makefile is generated. - -(3) Do make; make install. - -3. What you can do - -This extension module defines a module named PTY, which contains -following module fungtions: - - getpty(command) - spawn(command) - - This function reserves a pty, executes command over the pty - and returns an array. The return value is an array with three - elements. The first element in the array is for reading and the - second for writing. The third element is the process ID of the - child process. If this function is called with an iterator block, - the array is passed to the block as block parameters, and the - function itself returns nil. - - While the process spawned by this function is active, SIGCHLD - is captured to handle the change of the child process. When the - child process is suspended or finished, an exception is raised. - As all SIGCHLD signal is captured and processed by PTY module, - you can't use other function or method which spawns subprosesses - (including signal() and IO.popen()) while the PTY subprocesses - are active. Otherwise, unexpected exception will occur. To avoid - this problem, see protect_signal() below. - - If this function is called with an iterator block, SIGCHLD signal - is captured only within the block. Therefore, it is risky to use - File objects for PTY subprocess outside the iterator block. - - - protect_signal - - This function takes an iterator block. Within the iterator block, - no exception is raised even if any subprocess is terminated. - This function is used to enable functions like system() or IO.popen() - while PTY subprocess is active. For example, - - PTY.spawn("command_foo") do |r,w| - ... - ... - PTY.protect_signal do - system "some other commands" - end - ... - end - - disables to send exception when "some other commands" is - terminated. - - reset_signal - - Disables to handle SIGCHLD while PTY subprocess is active. - - -4. License - -(C) Copyright 1998 by Akinori Ito. - -This software may be redistributed freely for this purpose, in full -or in part, provided that this entire copyright notice is included -on any copies of this software and applications and derivations thereof. - -This software is provided on an "as is" basis, without warranty of any -kind, either expressed or implied, as to any matter including, but not -limited to warranty of fitness of purpose, or merchantability, or -results obtained from use of this software. - -5. Bug report - -Please feel free to send E-mail to - - aito@ei5sun.yz.yamagata-u.ac.jp - -for any bug report, opinion, contribution, etc. diff --git a/ext/pty/README.expect b/ext/pty/README.expect deleted file mode 100644 index fddbb6fdad..0000000000 --- a/ext/pty/README.expect +++ /dev/null @@ -1,22 +0,0 @@ - README for expect - by A. Ito, 28 October, 1998 - - Expect library adds IO class a method called expect(), which -does similar act to tcl's expect extension. - -The usage of the method is: - - IO#expect(pattern,timeout=9999999) - -where `pattern' is an instance of String or Regexp and `timeout' -is Fixnum, which can be omitted. - When the method is called without block, it waits until the -input which matches the pattern is obtained from the IO or the time -specified as the timeout passes. When the pattern is obtained from the -IO, the method returns an array. The first element of the array is the -entire string obtained from the IO until the pattern matches. The -following elements indicates the specific pattern which matched to the -anchor in the regular expression. If the method ends because of -timeout, it returns nil. - When the method is called with block, the array is passed as -the block parameter. diff --git a/ext/pty/README.expect.ja b/ext/pty/README.expect.ja deleted file mode 100644 index db84695ee5..0000000000 --- a/ext/pty/README.expect.ja +++ /dev/null @@ -1,21 +0,0 @@ - README for expect - by A. Ito, 28 October, 1998 - - Expect¥é¥¤¥Ö¥é¥ê¤Ï¡¤tcl ¤Î expect ¥Ñ¥Ã¥±¡¼¥¸¤È»÷¤¿¤è¤¦¤Êµ¡Ç½¤ò -IO¥¯¥é¥¹¤ËÄɲä·¤Þ¤¹¡¥ - - Äɲ䵤ì¤ë¥á¥½¥Ã¥É¤Î»È¤¤Êý¤Ï¼¡¤ÎÄ̤ê¤Ç¤¹¡¥ - - IO#expect(pattern,timeout=9999999) - -pattern ¤Ï String ¤« Regexp ¤Î¥¤¥ó¥¹¥¿¥ó¥¹¡¤timeout ¤Ï Fixnum -¤Î¥¤¥ó¥¹¥¿¥ó¥¹¤Ç¤¹¡¥timeout ¤Ï¾Êά¤Ç¤­¤Þ¤¹¡¥ - ¤³¤Î¥á¥½¥Ã¥É¤¬¥Ö¥í¥Ã¥¯¤Ê¤·¤Ç¸Æ¤Ð¤ì¤¿¾ì¹ç¡¤¤Þ¤º¥ì¥·¡¼¥Ð¤Ç¤¢¤ë -IO¥ª¥Ö¥¸¥§¥¯¥È¤«¤é pattern ¤Ë¥Þ¥Ã¥Á¤¹¤ë¥Ñ¥¿¡¼¥ó¤¬Æɤߤ³¤Þ¤ì¤ë -¤Þ¤ÇÂÔ¤Á¤Þ¤¹¡¥¥Ñ¥¿¡¼¥ó¤¬ÆÀ¤é¤ì¤¿¤é¡¤¤½¤Î¥Ñ¥¿¡¼¥ó¤Ë´Ø¤¹¤ëÇÛÎó¤ò -ÊÖ¤·¤Þ¤¹¡¥ÇÛÎó¤ÎºÇ½é¤ÎÍ×ÁǤϡ¤pattern ¤Ë¥Þ¥Ã¥Á¤¹¤ë¤Þ¤Ç¤ËÆɤߤ³ -¤Þ¤ì¤¿ÆâÍƤÎʸ»úÎó¤Ç¤¹¡¥2ÈÖÌܰʹߤÎÍ×ÁǤϡ¤pattern ¤ÎÀµµ¬É½¸½ -¤ÎÃæ¤Ë¥¢¥ó¥«¡¼¤¬¤¢¤Ã¤¿¾ì¹ç¤Ë¡¤¤½¤Î¥¢¥ó¥«¡¼¤Ë¥Þ¥Ã¥Á¤¹¤ëÉôʬ¤Ç¤¹¡¥ -¤â¤·¥¿¥¤¥à¥¢¥¦¥È¤¬µ¯¤­¤¿¾ì¹ç¤Ï¡¤¤³¤Î¥á¥½¥Ã¥É¤Ïnil¤òÊÖ¤·¤Þ¤¹¡¥ - ¤³¤Î¥á¥½¥Ã¥É¤¬¥Ö¥í¥Ã¥¯ÉÕ¤­¤Ç¸Æ¤Ð¤ì¤¿¾ì¹ç¤Ë¤Ï¡¤¥Þ¥Ã¥Á¤·¤¿Í×ÁǤΠ-ÇÛÎ󤬥֥í¥Ã¥¯°ú¿ô¤È¤·¤ÆÅϤµ¤ì¡¤¥Ö¥í¥Ã¥¯¤¬É¾²Á¤µ¤ì¤Þ¤¹¡¥ diff --git a/ext/pty/README.ja b/ext/pty/README.ja deleted file mode 100644 index 5ae4fb06a0..0000000000 --- a/ext/pty/README.ja +++ /dev/null @@ -1,89 +0,0 @@ -pty ³ÈÄ¥¥â¥¸¥å¡¼¥ë version 0.3 by A.ito - -1. ¤Ï¤¸¤á¤Ë - -¤³¤Î³ÈÄ¥¥â¥¸¥å¡¼¥ë¤Ï¡¤²¾ÁÛtty (pty) ¤òÄ̤·¤ÆŬÅö¤Ê¥³¥Þ¥ó¥É¤ò -¼Â¹Ô¤¹¤ëµ¡Ç½¤ò ruby ¤ËÄ󶡤·¤Þ¤¹¡¥ - -2. ¥¤¥ó¥¹¥È¡¼¥ë - -¼¡¤Î¤è¤¦¤Ë¤·¤Æ¥¤¥ó¥¹¥È¡¼¥ë¤·¤Æ¤¯¤À¤µ¤¤¡¥ - -(1) ruby extconf.rb - - ¤ò¼Â¹Ô¤¹¤ë¤È Makefile ¤¬À¸À®¤µ¤ì¤Þ¤¹¡¥ - -(2) make; make install ¤ò¼Â¹Ô¤·¤Æ¤¯¤À¤µ¤¤¡¥ - -3. ²¿¤¬¤Ç¤­¤ë¤« - -¤³¤Î³ÈÄ¥¥â¥¸¥å¡¼¥ë¤Ï¡¤PTY ¤È¤¤¤¦¥â¥¸¥å¡¼¥ë¤òÄêµÁ¤·¤Þ¤¹¡¥¤½¤ÎÃæ -¤Ë¤Ï¡¤¼¡¤Î¤è¤¦¤Ê¥â¥¸¥å¡¼¥ë´Ø¿ô¤¬´Þ¤Þ¤ì¤Æ¤¤¤Þ¤¹¡¥ - - getpty(command) - spawn(command) - - ¤³¤Î´Ø¿ô¤Ï¡¤²¾ÁÛtty¤ò³ÎÊݤ·¡¤»ØÄꤵ¤ì¤¿¥³¥Þ¥ó¥É¤ò¤½¤Î²¾ÁÛtty - ¤Î¸þ¤³¤¦¤Ç¼Â¹Ô¤·¡¤ÇÛÎó¤òÊÖ¤·¤Þ¤¹¡¥Ìá¤êÃͤÏ3¤Ä¤ÎÍ×ÁǤ«¤é¤Ê¤ë - ÇÛÎó¤Ç¤¹¡¥ºÇ½é¤ÎÍ×ÁǤϲ¾ÁÛtty¤«¤éÆɤ߽Ф¹¤¿¤á¤ÎIO¥ª¥Ö¥¸¥§¥¯¥È¡¤ - 2ÈÖÌܤϽñ¤­¤³¤à¤¿¤á¤ÎIO¥ª¥Ö¥¸¥§¥¯¥È¡¤3ÈÖÌÜ¤Ï»Ò¥×¥í¥»¥¹¤Î¥×¥í - ¥»¥¹ID¤Ç¤¹¡¥¤³¤Î´Ø¿ô¤¬¥¤¥Æ¥ì¡¼¥¿¤È¤·¤Æ¸Æ¤Ð¤ì¤¿¾ì¹ç¡¤¤³¤ì¤é¤Î - Í×ÁǤϥ֥í¥Ã¥¯¥Ñ¥é¥á¡¼¥¿¤È¤·¤ÆÅϤµ¤ì¡¤´Ø¿ô¼«ÂΤÏnil¤òÊÖ¤·¤Þ¤¹¡¥ - - ¤³¤Î´Ø¿ô¤Ë¤è¤Ã¤Æºî¤é¤ì¤¿¥µ¥Ö¥×¥í¥»¥¹¤¬Æ°¤¤¤Æ¤¤¤ë´Ö¡¤»Ò¥×¥í¥»¥¹ - ¤Î¾õÂÖ¤ò´Æ»ë¤¹¤ë¤¿¤á¤Ë SIGCHLD ¥·¥°¥Ê¥ë¤òÊ᪤·¤Þ¤¹¡¥»Ò¥×¥í¥»¥¹ - ¤¬½ªÎ»¤·¤¿¤êÄä»ß¤·¤¿¾ì¹ç¤Ë¤Ï¡¤Îã³°¤¬È¯À¸¤·¤Þ¤¹¡¥¤³¤Î´Ö¡¤¤¹¤Ù¤Æ¤Î - SIGCHLD ¤¬ PTY ¥â¥¸¥å¡¼¥ë¤Î¥·¥°¥Ê¥ë¥Ï¥ó¥É¥é¤ËÊ᪤µ¤ì¤ë¤Î¤Ç¡¤ - ¥µ¥Ö¥×¥í¥»¥¹¤òÀ¸À®¤¹¤ë¾¤Î´Ø¿ô(system() ¤È¤« IO.popen()¤Ê¤É)¤ò - »È¤¦¤È¡¤Í½´ü¤·¤Ê¤¤Îã³°¤¬È¯À¸¤¹¤ë¤³¤È¤¬¤¢¤ê¤Þ¤¹¡¥¤³¤ì¤òËɤ°¤¿¤á - ¤Ë¤Ï¡¤²¼µ­¤Îprotect_signal()¤ò»²¾È¤·¤Æ¤¯¤À¤µ¤¤¡¥ - - ¤³¤Î´Ø¿ô¤¬¥Ö¥í¥Ã¥¯¥Ñ¥é¥á¡¼¥¿ÉÕ¤­¤Ç¸Æ¤Ð¤ì¤¿¾ì¹ç¤Ë¤Ï¡¤¤½¤Î¥Ö¥í¥Ã¥¯ - ¤ÎÃæ¤Ç¤Î¤ß SIGCHLD ¤¬Ê᪤µ¤ì¤Þ¤¹¡¥¤·¤¿¤¬¤Ã¤Æ¡¤¥Ö¥í¥Ã¥¯¥Ñ¥é¥á¡¼¥¿ - ¤È¤·¤ÆÅϤµ¤ì¤¿IO¥ª¥Ö¥¸¥§¥¯¥È¤ò¡¤¥Ö¥í¥Ã¥¯¤Î³°¤Ë»ý¤Á½Ð¤·¤Æ»È¤¦¤Î - ¤Ï´«¤á¤é¤ì¤Þ¤»¤ó¡¥ - - - protect_signal - - ¤³¤Î´Ø¿ô¤Ï¥¤¥Æ¥ì¡¼¥¿¤Ç¤¹¡¥¤³¤³¤Ç»ØÄꤵ¤ì¤¿¥Ö¥í¥Ã¥¯¤ÎÃæ¤Ç¤Ï¡¤ - »Ò¥×¥í¥»¥¹¤¬½ªÎ»¤·¤Æ¤âÎã³°¤òȯÀ¸¤·¤Þ¤»¤ó¡¥¤³¤Î´Ø¿ô¤ò»È¤¦¤³¤È¤Ç¡¤ - PTY¤Î»Ò¥×¥í¥»¥¹¤¬Æ°¤¤¤Æ¤¤¤ë´Ö¤Ç¤â¡¤system()¤ä IO.popen()¤Ê¤É¤Î - ´Ø¿ô¤ò°ÂÁ´¤Ë»È¤¦¤³¤È¤¬¤Ç¤­¤Þ¤¹¡¥Î㤨¤Ð¡¤ - - PTY.spawn("command_foo") do |r,w| - ... - ... - PTY.protect_signal do - system "some other commands" - end - ... - end - - ¤³¤Î¤è¤¦¤Êµ­½Ò¤Ë¤è¤ê¡¤"some other commands" ¤¬½ªÎ»¤·¤¿¤È¤­¤Ë - Îã³°¤¬È¯À¸¤¹¤ë¤Î¤òËɤ²¤Þ¤¹¡¥ - - reset_signal - - PTY ¤Î»Ò¥×¥í¥»¥¹¤¬Æ°¤¤¤Æ¤¤¤Æ¤â¡¤¤½¤Î¥×¥í¥»¥¹¤Î½ªÎ»»þ¤ËÎã³°¤¬È¯À¸ - ¤·¤Ê¤¤¤è¤¦¤Ë¤·¤Þ¤¹¡¥ - -4. ÍøÍѤˤĤ¤¤Æ - -°ËÆ£¾´Â§¤¬Ãøºî¸¢¤òÊÝÍ­¤·¤Þ¤¹¡¥ - -¥½¡¼¥¹¥×¥í¥°¥é¥à¤Þ¤¿¤Ï¥É¥­¥å¥á¥ó¥È¤Ë¸µ¤ÎÃøºî¸¢É½¼¨¤¬²þÊѤµ¤ì¤º¤Ë -ɽ¼¨¤µ¤ì¤Æ¤¤¤ë¾ì¹ç¤Ë¸Â¤ê¡¤Ã¯¤Ç¤â¡¤¤³¤Î¥½¥Õ¥È¥¦¥§¥¢¤ò̵½þ¤«¤ÄÃøºî -¸¢¼Ô¤Ë̵ÃǤÇÍøÍÑ¡¦ÇÛÉÛ¡¦²þÊѤǤ­¤Þ¤¹¡¥ÍøÍÑÌÜŪ¤Ï¸ÂÄꤵ¤ì¤Æ¤¤¤Þ¤» -¤ó¡¥ - -¤³¤Î¥×¥í¥°¥é¥à¤ÎÍøÍÑ¡¦ÇÛÉÛ¤½¤Î¾¤³¤Î¥×¥í¥°¥é¥à¤Ë´Ø·¸¤¹¤ë¹Ô°Ù¤Ë¤è -¤Ã¤ÆÀ¸¤¸¤¿¤¤¤«¤Ê¤ë»³²¤ËÂФ·¤Æ¤â¡¤ºî¼Ô¤Ï°ìÀÚÀÕǤ¤òÉ餤¤Þ¤»¤ó¡¥ - -5. ¥Ð¥°Êó¹ðÅù - -¥Ð¥°¥ì¥Ý¡¼¥È¤Ï´¿·Þ¤·¤Þ¤¹¡¥ - - aito@ei5sun.yz.yamagata-u.ac.jp - -¤Þ¤ÇÅŻҥ᡼¥ë¤Ç¥Ð¥°¥ì¥Ý¡¼¥È¤ò¤ªÁ÷¤ê¤¯¤À¤µ¤¤¡¥ diff --git a/ext/pty/depend b/ext/pty/depend deleted file mode 100644 index 888be6c301..0000000000 --- a/ext/pty/depend +++ /dev/null @@ -1 +0,0 @@ -pty.o: pty.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/pty/expect_sample.rb b/ext/pty/expect_sample.rb deleted file mode 100644 index 1311476c5d..0000000000 --- a/ext/pty/expect_sample.rb +++ /dev/null @@ -1,56 +0,0 @@ -# -# sample program of expect.rb -# -# by A. Ito -# -# This program reports the latest version of ruby interpreter -# by connecting to ftp server at netlab.co.jp. -# -require 'pty' -require 'expect' - -fnames = [] -PTY.spawn("ftp ftp.netlab.co.jp") do - |r_f,w_f,pid| - w_f.sync = true - - $expect_verbose = true - - r_f.expect(/^Name.*: /) do - w_f.print "ftp\n" - end - - if !ENV['USER'].nil? - username = ENV['USER'] - elsif !ENV['LOGNAME'].nil? - username = ENV['LOGNAME'] - else - username = 'guest' - end - - r_f.expect('word:') do - w_f.print username+"@\n" - end - r_f.expect("ftp> ") do - w_f.print "cd pub/lang/ruby\n" - end - r_f.expect("ftp> ") do - w_f.print "dir\n" - end - - r_f.expect("ftp> ") do |output| - for x in output[0].split("\n") - if x =~ /(ruby.*\.tar\.gz)/ then - fnames.push $1 - end - end - end - begin - w_f.print "quit\n" - rescue - end -end - -print "The latest ruby interpreter is " -print fnames.sort.pop -print "\n" diff --git a/ext/pty/extconf.rb b/ext/pty/extconf.rb deleted file mode 100644 index ec35879a33..0000000000 --- a/ext/pty/extconf.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'mkmf' - -if /mswin32|mingw/ !~ RUBY_PLATFORM - have_header("sys/stropts.h") - have_func("setresuid") - have_header("libutil.h") - have_header("pty.h") - have_library("util", "openpty") - if have_func("openpty") or - have_func("_getpty") or - have_func("ptsname") or - have_func("ioctl") - create_makefile('pty') - end -end diff --git a/ext/pty/lib/expect.rb b/ext/pty/lib/expect.rb deleted file mode 100644 index 5b5619e6b2..0000000000 --- a/ext/pty/lib/expect.rb +++ /dev/null @@ -1,36 +0,0 @@ -$expect_verbose = false - -class IO - def expect(pat,timeout=9999999) - buf = '' - case pat - when String - e_pat = Regexp.new(Regexp.quote(pat)) - when Regexp - e_pat = pat - end - while true - if IO.select([self],nil,nil,timeout).nil? then - result = nil - break - end - c = getc.chr - buf << c - if $expect_verbose - STDOUT.print c - STDOUT.flush - end - if buf =~ e_pat then - result = [buf,$1,$2,$3,$4,$5,$6,$7,$8,$9] - break - end - end - if block_given? then - yield result - else - return result - end - nil - end -end - diff --git a/ext/pty/pty.c b/ext/pty/pty.c deleted file mode 100644 index b7c69fe400..0000000000 --- a/ext/pty/pty.c +++ /dev/null @@ -1,488 +0,0 @@ -#include "config.h" -#include -#include -#include -#include -#include -#include -#include -#if !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) -#include -#endif -#ifdef HAVE_LIBUTIL_H -#include -#endif -#ifdef HAVE_PTY_H -#include -#endif -#ifdef HAVE_SYS_WAIT_H -#include -#else -#define WIFSTOPPED(status) (((status) & 0xff) == 0x7f) -#endif -#include - -#include "ruby.h" -#include "rubyio.h" - -#include -#ifdef HAVE_SYS_STROPTS_H -#include -#endif - -#ifdef HAVE_UNISTD_H -#include -#endif - -#define DEVICELEN 16 - -#if !defined(HAVE_OPENPTY) -#ifdef __hpux -static -char *MasterDevice = "/dev/ptym/pty%s", - *SlaveDevice = "/dev/pty/tty%s", - *deviceNo[] = { - "p0","p1","p2","p3","p4","p5","p6","p7", - "p8","p9","pa","pb","pc","pd","pe","pf", - "q0","q1","q2","q3","q4","q5","q6","q7", - "q8","q9","qa","qb","qc","qd","qe","qf", - "r0","r1","r2","r3","r4","r5","r6","r7", - "r8","r9","ra","rb","rc","rd","re","rf", - "s0","s1","s2","s3","s4","s5","s6","s7", - "s8","s9","sa","sb","sc","sd","se","sf", - "t0","t1","t2","t3","t4","t5","t6","t7", - "t8","t9","ta","tb","tc","td","te","tf", - "u0","u1","u2","u3","u4","u5","u6","u7", - "u8","u9","ua","ub","uc","ud","ue","uf", - "v0","v1","v2","v3","v4","v5","v6","v7", - "v8","v9","va","vb","vc","vd","ve","vf", - "w0","w1","w2","w3","w4","w5","w6","w7", - "w8","w9","wa","wb","wc","wd","we","wf", - 0, - }; -#else /* NOT HPUX */ -#ifdef _IBMESA /* AIX/ESA */ -static -char *MasterDevice = "/dev/ptyp%s", - *SlaveDevice = "/dev/ttyp%s", - *deviceNo[] = { -"00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f", -"10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f", -"20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f", -"30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f", -"40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f", -"50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f", -"60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f", -"70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f", -"80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f", -"90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f", -"a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af", -"b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf", -"c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf", -"d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df", -"e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef", -"f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff", - }; -#else -static -char *MasterDevice = "/dev/pty%s", - *SlaveDevice = "/dev/tty%s", - *deviceNo[] = { - "p0","p1","p2","p3","p4","p5","p6","p7", - "p8","p9","pa","pb","pc","pd","pe","pf", - "q0","q1","q2","q3","q4","q5","q6","q7", - "q8","q9","qa","qb","qc","qd","qe","qf", - "r0","r1","r2","r3","r4","r5","r6","r7", - "r8","r9","ra","rb","rc","rd","re","rf", - "s0","s1","s2","s3","s4","s5","s6","s7", - "s8","s9","sa","sb","sc","sd","se","sf", - 0, - }; -#endif /* _IBMESA */ -#endif /* HPUX */ -#endif /* !defined(HAVE_OPENPTY) */ - -static char SlaveName[DEVICELEN]; - -extern int errno; - -#ifndef HAVE_SETEUID -# ifdef HAVE_SETREUID -# define seteuid(e) setreuid(-1, (e)) -# else /* NOT HAVE_SETREUID */ -# ifdef HAVE_SETRESUID -# define seteuid(e) setresuid(-1, (e), -1) -# else /* NOT HAVE_SETRESUID */ - /* I can't set euid. (;_;) */ -# endif /* HAVE_SETRESUID */ -# endif /* HAVE_SETREUID */ -#endif /* NO_SETEUID */ - -static VALUE eChildExited; - -static VALUE -echild_status(self) - VALUE self; -{ - return rb_ivar_get(self, rb_intern("status")); -} - -struct pty_info { - int fd; - pid_t child_pid; - VALUE thread; -}; - -static VALUE -pty_syswait(info) - struct pty_info *info; -{ - extern VALUE rb_last_status; - int cpid, status; - char buf[1024]; - VALUE exc, st; - char *state = "changed"; - - cpid = rb_waitpid(info->child_pid, &status, WUNTRACED); - st = rb_last_status; - - if (cpid == 0 || cpid == -1) - return Qnil; - -#ifdef IF_STOPPED - if (IF_STOPPED(status)) { /* suspend */ - state = "stopped"; - } -#else -#ifdef WIFSTOPPED - if (WIFSTOPPED(status)) { /* suspend */ - state = "stopped"; - } -#else ----->> Either IF_STOPPED or WIFSTOPPED is needed <<---- -#endif /* WIFSTOPPED */ -#endif /* IF_STOPPED */ - if (WIFEXITED(status)) { - state = "exit"; - } - - snprintf(buf, sizeof(buf), "pty - %s: %d", state, cpid); - exc = rb_exc_new2(eChildExited, buf); - rb_iv_set(exc, "status", st); - rb_funcall(info->thread, rb_intern("raise"), 1, exc); - return Qnil; -} - -static void getDevice _((int*, int*)); - -struct exec_info { - int argc; - VALUE *argv; -}; - -static VALUE -pty_exec(arg) - struct exec_info *arg; -{ - return rb_f_exec(arg->argc, arg->argv); -} - -static void -establishShell(argc, argv, info) - int argc; - VALUE *argv; - struct pty_info *info; -{ - static int i,master,slave,currentPid; - char *p,*getenv(); - struct passwd *pwent; - VALUE v; - struct exec_info arg; - int status; - - if (argc == 0) { - char *shellname; - - if ((p = getenv("SHELL")) != NULL) { - shellname = p; - } - else { - pwent = getpwuid(getuid()); - if (pwent && pwent->pw_shell) - shellname = pwent->pw_shell; - else - shellname = "/bin/sh"; - } - v = rb_str_new2(shellname); - argc = 1; - argv = &v; - } - getDevice(&master,&slave); - - info->thread = rb_thread_current(); - currentPid = getpid(); - if((i = fork()) < 0) { - rb_sys_fail("fork failed"); - } - - if(i == 0) { /* child */ - currentPid = getpid(); - - /* - * Set free from process group and controlling terminal - */ -#ifdef HAVE_SETSID - (void) setsid(); -#else /* HAS_SETSID */ -# ifdef HAVE_SETPGRP -# ifdef SETGRP_VOID - if (setpgrp() == -1) - perror("setpgrp()"); -# else /* SETGRP_VOID */ - if (setpgrp(0, currentPid) == -1) - rb_sys_fail("setpgrp()"); - if ((i = open("/dev/tty", O_RDONLY)) < 0) - rb_sys_fail("/dev/tty"); - else { - if (ioctl(i, TIOCNOTTY, (char *)0)) - perror("ioctl(TIOCNOTTY)"); - close(i); - } -# endif /* SETGRP_VOID */ -# endif /* HAVE_SETPGRP */ -#endif /* HAS_SETSID */ - - /* - * obtain new controlling terminal - */ -#if defined(TIOCSCTTY) - close(master); - (void) ioctl(slave, TIOCSCTTY, (char *)0); - /* errors ignored for sun */ -#else - close(slave); - slave = open(SlaveName, O_RDWR); - if (slave < 0) { - perror("open: pty slave"); - _exit(1); - } - close(master); -#endif - dup2(slave,0); - dup2(slave,1); - dup2(slave,2); - close(slave); -#if defined(HAVE_SETEUID) || defined(HAVE_SETREUID) || defined(HAVE_SETRESUID) - seteuid(getuid()); -#endif - - arg.argc = argc; - arg.argv = argv; - rb_protect(pty_exec, (VALUE)&arg, &status); - sleep(1); - _exit(1); - } - - close(slave); - - info->child_pid = i; - info->fd = master; -} - -static VALUE -pty_kill_child(info) - struct pty_info *info; -{ - if (rb_funcall(info->thread, rb_intern("alive?"), 0, 0) == Qtrue && - kill(info->child_pid, 0) == 0) { - rb_thread_schedule(); - if (kill(info->child_pid, SIGTERM) == 0) { - rb_thread_schedule(); - if (kill(info->child_pid, 0) == 0) { - kill(info->child_pid, SIGINT); - rb_thread_schedule(); - if (kill(info->child_pid, 0) == 0) - kill(info->child_pid, SIGKILL); - } - } - } - rb_funcall(info->thread, rb_intern("join"), 0, 0); - return Qnil; -} - - -#ifdef HAVE_OPENPTY -/* - * Use openpty(3) of 4.3BSD Reno and later, - * or the same interface function. - */ -static void -getDevice(master,slave) - int *master,*slave; -{ - if (openpty(master, slave, SlaveName, - (struct termios *)0, (struct winsize *)0) == -1) { - rb_raise(rb_eRuntimeError, "openpty() failed"); - } -} -#else /* HAVE_OPENPTY */ -#ifdef HAVE__GETPTY -static void -getDevice(master,slave) - int *master,*slave; -{ - char *name; - - if (!(name = _getpty(master, O_RDWR, 0622, 0))) { - rb_raise(rb_eRuntimeError, "_getpty() failed"); - } - - *slave = open(name, O_RDWR); - strcpy(SlaveName, name); -} -#else /* HAVE__GETPTY */ -static void -getDevice(master,slave) - int *master,*slave; -{ - char **p; - int i,j; - char MasterName[DEVICELEN]; - -#ifdef HAVE_PTSNAME - char *pn; - void (*s)(); - - extern char *ptsname(int); - extern int unlockpt(int); - extern int grantpt(int); - - if((i = open("/dev/ptmx", O_RDWR, 0)) != -1) { - s = signal(SIGCHLD, SIG_DFL); - if(grantpt(i) != -1) { - signal(SIGCHLD, s); - if(unlockpt(i) != -1) { - if((pn = ptsname(i)) != NULL) { - if((j = open(pn, O_RDWR, 0)) != -1) { -#if defined I_PUSH && !defined linux - if(ioctl(j, I_PUSH, "ptem") != -1) { - if(ioctl(j, I_PUSH, "ldterm") != -1) { -#endif - *master = i; - *slave = j; - strcpy(SlaveName, pn); - return; -#if defined I_PUSH && !defined linux - } - } -#endif - } - } - } - } - close(i); - } - rb_raise(rb_eRuntimeError, "Cannot get Master/Slave device"); -#else - for (p = deviceNo; *p != NULL; p++) { - sprintf(MasterName,MasterDevice,*p); - if ((i = open(MasterName,O_RDWR,0)) >= 0) { - *master = i; - sprintf(SlaveName,SlaveDevice,*p); - if ((j = open(SlaveName,O_RDWR,0)) >= 0) { - *slave = j; - chown(SlaveName, getuid(), getgid()); - chmod(SlaveName, 0622); - return; - } - close(i); - } - } - rb_raise(rb_eRuntimeError, "Cannot get %s", SlaveName); -#endif -} -#endif /* HAVE__GETPTY */ -#endif /* HAVE_OPENPTY */ - -static void -freeDevice() -{ - chmod(SlaveName, 0666); - chown(SlaveName, 0, 0); -} - -/* ruby function: getpty */ -static VALUE -pty_getpty(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - VALUE res, th; - struct pty_info info, thinfo; - OpenFile *wfptr,*rfptr; - VALUE rport = rb_obj_alloc(rb_cFile); - VALUE wport = rb_obj_alloc(rb_cFile); - - MakeOpenFile(rport, rfptr); - MakeOpenFile(wport, wfptr); - - establishShell(argc, argv, &info); - - rfptr->mode = rb_io_mode_flags("r"); - rfptr->f = fdopen(info.fd, "r"); - rfptr->path = strdup(SlaveName); - - wfptr->mode = rb_io_mode_flags("w") | FMODE_SYNC; - wfptr->f = fdopen(dup(info.fd), "w"); - wfptr->path = strdup(SlaveName); - - res = rb_ary_new2(3); - rb_ary_store(res,0,(VALUE)rport); - rb_ary_store(res,1,(VALUE)wport); - rb_ary_store(res,2,INT2FIX(info.child_pid)); - - th = rb_thread_create(pty_syswait, (void*)&info); - thinfo.thread = th; - thinfo.child_pid = info.child_pid; - - if (rb_block_given_p()) { - rb_ensure(rb_yield, res, pty_kill_child, (VALUE)&thinfo); - return Qnil; - } - return res; -} - -/* ruby function: protect_signal - obsolete */ -static VALUE -pty_protect(self) - VALUE self; -{ - rb_warn("PTY::protect_signal is no longer needed"); - rb_yield(Qnil); - return self; -} - -/* ruby function: reset_signal - obsolete */ -static VALUE -pty_reset_signal(self) - VALUE self; -{ - rb_warn("PTY::reset_signal is no longer needed"); - return self; -} - -static VALUE cPTY; - -void -Init_pty() -{ - cPTY = rb_define_module("PTY"); - rb_define_module_function(cPTY,"getpty",pty_getpty,-1); - rb_define_module_function(cPTY,"spawn",pty_getpty,-1); - rb_define_module_function(cPTY,"protect_signal",pty_protect,0); - rb_define_module_function(cPTY,"reset_signal",pty_reset_signal,0); - - eChildExited = rb_define_class_under(cPTY,"ChildExited",rb_eRuntimeError); - rb_define_method(eChildExited,"status",echild_status,0); -} diff --git a/ext/pty/script.rb b/ext/pty/script.rb deleted file mode 100644 index 3084935637..0000000000 --- a/ext/pty/script.rb +++ /dev/null @@ -1,38 +0,0 @@ -require 'pty' - -if ARGV.size == 0 then - ofile = "typescript" -else - ofile = ARGV[0] -end - -logfile = File.open(ofile,"a") - -system "stty -echo raw lnext ^_" - -PTY.spawn("/bin/csh") do - |r_pty,w_pty,pid| - - Thread.new do - while true - w_pty.print STDIN.getc.chr - w_pty.flush - end - end - - begin - while true - c = r_pty.sysread(512) - break if c.nil? - print c - STDOUT.flush - logfile.print c - end - rescue - # print $@,':',$!,"\n" - logfile.close - end -end - -system "stty echo -raw lnext ^v" - diff --git a/ext/pty/shl.rb b/ext/pty/shl.rb deleted file mode 100644 index cdaf8d7398..0000000000 --- a/ext/pty/shl.rb +++ /dev/null @@ -1,92 +0,0 @@ -# -# old-fashioned 'shl' like program -# by A. Ito -# -# commands: -# c creates new shell -# C-z suspends shell -# p lists all shell -# 0,1,... choose shell -# q quit - -require 'pty' - -$shells = [] -$n_shells = 0 - -$r_pty = nil -$w_pty = nil - -def writer - system "stty -echo raw" - begin - while true - c = STDIN.getc - if c == 26 then # C-z - $reader.raise(nil) - return 'Suspend' - end - $w_pty.print c.chr - $w_pty.flush - end - rescue - $reader.raise(nil) - return 'Exit' - ensure - system "stty echo -raw" - end -end - -$reader = Thread.new { - while true - begin - next if $r_pty.nil? - c = $r_pty.getc - if c.nil? then - Thread.stop - end - print c.chr - STDOUT.flush - rescue - Thread.stop - end - end -} - -# $reader.raise(nil) - - -while true - print ">> " - STDOUT.flush - case gets - when /^c/i - $shells[$n_shells] = PTY.spawn("/bin/csh") - $r_pty,$w_pty = $shells[$n_shells] - $n_shells += 1 - $reader.run - if writer == 'Exit' - $n_shells -= 1 - $shells[$n_shells] = nil - end - when /^p/i - for i in 0..$n_shells - unless $shells[i].nil? - print i,"\n" - end - end - when /^([0-9]+)/ - n = $1.to_i - if $shells[n].nil? - print "\##{i} doesn't exist\n" - else - $r_pty,$w_pty = $shells[n] - $reader.run - if writer == 'Exit' then - $shells[n] = nil - end - end - when /^q/i - exit - end -end diff --git a/ext/readline/.cvsignore b/ext/readline/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/readline/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/readline/MANIFEST b/ext/readline/MANIFEST deleted file mode 100644 index 4dd1d9e1a1..0000000000 --- a/ext/readline/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -MANIFEST -README -README.ja -depend -extconf.rb -readline.c diff --git a/ext/readline/README b/ext/readline/README deleted file mode 100644 index 9bbf325c99..0000000000 --- a/ext/readline/README +++ /dev/null @@ -1,62 +0,0 @@ -Extension for GNU Readline Library - -Example: - - require "readline" - include Readline - - line = readline("Prompt> ", true) - -[Readline] - - - -readline(prompt, add_history=nil) - - Reads one line with line editing. The inputted line is added to the - history if add_history is true. - - - -completion_proc = proc - - Specifies a Proc object to determine completion behavior. It - should take input-string, and return an array of completion - candidates. - -completion_proc - - Returns the completion Proc object. - -completion_case_fold = bool - - Sets whether or not to ignore case on completion. - -completion_case_fold - - Returns true if completion ignores case. - -completion_append_character = char - - Specifies a character to be appended on completion. - Nothing will be appended if an empty string ("") or nil is - specified. - -completion_append_character - - Returns a string containing a character to be appended on - completion. The default is a space (" "). - -vi_editing_mode - - Specifies VI editing mode. - -emacs_editing_mode - - Specifies Emacs editing mode. - - - -HISTORY - -The history buffer. It behaves just like an array. diff --git a/ext/readline/README.ja b/ext/readline/README.ja deleted file mode 100644 index beb951fbf0..0000000000 --- a/ext/readline/README.ja +++ /dev/null @@ -1,63 +0,0 @@ -GNU Readline Library¤òÍøÍѤ¹¤ë¤¿¤á¤Î³ÈÄ¥¥â¥¸¥å¡¼¥ë¤Ç¤¹¡£ - -require "readline" -include Readline - -line = readline("Prompt> ", true) - -¤Î¤è¤¦¤Ë»ÈÍѤ·¤Æ¤¯¤À¤µ¤¤¡£ - -[Readline] - -<¥â¥¸¥å¡¼¥ë´Ø¿ô> - -readline(prompt, add_history=nil) - - °ì¹ÔÆþÎϤòÆɤ߹þ¤ß¤Þ¤¹¡£ - add_history¤¬true¤Î¾ì¹ç¡¢¥Ò¥¹¥È¥ê¤ËÆɤ߹þ¤ó¤Àʸ»úÎó¤òÄɲä·¤Þ¤¹¡£ - -<¥¯¥é¥¹¥á¥½¥Ã¥É> - -completion_proc = proc - - Êä´°»þ¤ÎÆ°ºî¤ò·èÄꤹ¤ëProc¥ª¥Ö¥¸¥§¥¯¥È¤ò»ØÄꤷ¤Þ¤¹¡£ - proc¤Ï°ú¿ô¤ËÆþÎÏʸ»úÎó¤ò¼è¤ê¡¢¸õÊäʸ»úÎó¤ÎÇÛÎó¤òÊÖ¤¹¤è¤¦¤Ë - ¤·¤Æ¤¯¤À¤µ¤¤¡£ - -completion_proc - - Êä´°»þ¤ÎÆ°ºî¤ò·èÄꤹ¤ëProc¥ª¥Ö¥¸¥§¥¯¥È¤òÊÖ¤·¤Þ¤¹¡£ - -completion_case_fold = case_fold - - Êä´°»þ¤ËÂçʸ»ú¾®Ê¸»ú¤ò¶èÊ̤·¤Ê¤¤¾ì¹ç¡¢true¤ò»ØÄꤷ¤Þ¤¹¡£ - -completion_case_fold - - Êä´°»þ¤ËÂçʸ»ú¾®Ê¸»ú¤ò¶èÊ̤·¤Ê¤¤¾ì¹ç¡¢true¤òÊÖ¤·¤Þ¤¹¡£ - -completion_append_character = char - - Êä´°»þ¤ËÉղ䵤ì¤ëʸ»ú¤òʸ»úÎó¤Ç»ØÄꤷ¤Þ¤¹¡£ÀèƬ¤Î°ìʸ»ú¤¬ - ÀßÄꤵ¤ì¡¢¶õʸ»úÎó ("") ¤Þ¤¿¤Ï nil ¤ò»ØÄꤹ¤ë¤È²¿¤âÉղà - ¤µ¤ì¤Ê¤¯¤Ê¤ê¤Þ¤¹¡£ - -completion_append_character - - Êä´°»þ¤ËÉղ䵤ì¤ëʸ»ú¤òʸ»úÎó¤ÇÊÖ¤·¤Þ¤¹¡£¥Ç¥Õ¥©¥ë¥È¤Ï - ¶õÇò (" ") ¤Ç¤¹¡£ - -vi_editing_mode - - VI¥â¡¼¥É¤Ë¤Ê¤ê¤Þ¤¹¡£ - -emacs_editing_mode - - Emacs¥â¡¼¥É¤Ë¤Ê¤ê¤Þ¤¹¡£ - -<¥¯¥é¥¹Äê¿ô> - -HISTORY - -¥Ò¥¹¥È¥ê¤ËÂФ¹¤ëÁàºî¤Ï¤³¤ÎÄê¿ô¤òÄ̤·¤Æ¹Ô¤Ã¤Æ¤¯¤À¤µ¤¤¡£ -ÇÛÎó¤ÈƱ¤¸¤è¤¦¤Ë°·¤¨¤ë¤è¤¦¤Ë¤Ê¤Ã¤Æ¤¤¤Þ¤¹¡£ diff --git a/ext/readline/depend b/ext/readline/depend deleted file mode 100644 index 6570c5a036..0000000000 --- a/ext/readline/depend +++ /dev/null @@ -1 +0,0 @@ -readline.o: readline.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/readline/extconf.rb b/ext/readline/extconf.rb deleted file mode 100644 index b883de3e01..0000000000 --- a/ext/readline/extconf.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "mkmf" - -dir_config("readline") -have_library("user32", nil) if /cygwin/ === RUBY_PLATFORM -have_library("ncurses", "tgetnum") or - have_library("termcap", "tgetnum") or - have_library("curses", "tgetnum") - -if have_header("readline/readline.h") and - have_header("readline/history.h") and - have_library("readline", "readline") - if have_func("rl_filename_completion_function") - $CFLAGS += " -DREADLINE_42_OR_LATER" - end - if have_func("rl_cleanup_after_signal") - $CFLAGS += " -DREADLINE_40_OR_LATER" - end - if try_link(< -#include -main() {rl_completion_append_character = 1;} -EOF - # this feature is implemented in readline-2.1 or later. - $CFLAGS += " -DREADLINE_21_OR_LATER" - end - create_makefile("readline") -end diff --git a/ext/readline/readline.c b/ext/readline/readline.c deleted file mode 100644 index a6554a5b57..0000000000 --- a/ext/readline/readline.c +++ /dev/null @@ -1,737 +0,0 @@ -/* readline.c -- GNU Readline module - Copyright (C) 1997-2001 Shugo Maeda */ - -#include -#include -#include - -#include "ruby.h" -#include "rubysig.h" - -static VALUE mReadline; - -#define TOLOWER(c) (isupper(c) ? tolower(c) : c) - -#define COMPLETION_PROC "completion_proc" -#define COMPLETION_CASE_FOLD "completion_case_fold" - -#ifndef READLINE_42_OR_LATER -# define rl_filename_completion_function filename_completion_function -# define rl_username_completion_function username_completion_function -# define rl_completion_matches completion_matches -#endif - -static int -readline_event() -{ - CHECK_INTS; - rb_thread_schedule(); - return 0; -} - -static VALUE -readline_readline(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - VALUE tmp, add_hist, result; - char *prompt = NULL; - char *buff; - int status; - - if (rb_scan_args(argc, argv, "02", &tmp, &add_hist) > 0) { - prompt = StringValuePtr(tmp); - } - - buff = (char*)rb_protect((VALUE(*)_((VALUE)))readline, (VALUE)prompt, - &status); - if (status) { -#if READLINE_40_OR_LATER - /* restore terminal mode and signal handler*/ - rl_cleanup_after_signal(); -#elif READLINE_21_OR_LATER - /* restore terminal mode */ - (*rl_deprep_term_function)(); -#else - rl_deprep_terminal(); -#endif - rb_jump_tag(status); - } - - if (RTEST(add_hist) && buff) { - add_history(buff); - } - if (buff) - result = rb_tainted_str_new2(buff); - else - result = Qnil; - if (buff) free(buff); - return result; -} - -static VALUE -readline_s_set_completion_proc(self, proc) - VALUE self; - VALUE proc; -{ - if (!rb_respond_to(proc, rb_intern("call"))) - rb_raise(rb_eArgError, "argument have to respond to `call'"); - return rb_iv_set(mReadline, COMPLETION_PROC, proc); -} - -static VALUE -readline_s_get_completion_proc(self) - VALUE self; -{ - return rb_iv_get(mReadline, COMPLETION_PROC); -} - -static VALUE -readline_s_set_completion_case_fold(self, val) - VALUE self; - VALUE val; -{ - return rb_iv_set(mReadline, COMPLETION_CASE_FOLD, val); -} - -static VALUE -readline_s_get_completion_case_fold(self) - VALUE self; -{ - return rb_iv_get(mReadline, COMPLETION_CASE_FOLD); -} - -static char ** -readline_attempted_completion_function(text, start, end) - char *text; - int start; - int end; -{ - VALUE proc, ary, temp; - char **result; - int case_fold; - int i, matches; - - proc = rb_iv_get(mReadline, COMPLETION_PROC); - if (NIL_P(proc)) - return NULL; - rl_attempted_completion_over = 1; - case_fold = RTEST(rb_iv_get(mReadline, COMPLETION_CASE_FOLD)); - ary = rb_funcall(proc, rb_intern("call"), 1, rb_tainted_str_new2(text)); - if (TYPE(ary) != T_ARRAY) - ary = rb_Array(ary); - matches = RARRAY(ary)->len; - if (matches == 0) - return NULL; - result = ALLOC_N(char *, matches + 2); - for (i = 0; i < matches; i++) { - temp = rb_obj_as_string(RARRAY(ary)->ptr[i]); - result[i + 1] = ALLOC_N(char, RSTRING(temp)->len + 1); - strcpy(result[i + 1], RSTRING(temp)->ptr); - } - result[matches + 1] = NULL; - - if (matches == 1) { - result[0] = result[1]; - result[1] = NULL; - } else { - register int i = 1; - int low = 100000; - - while (i < matches) { - register int c1, c2, si; - - if (case_fold) { - for (si = 0; - (c1 = TOLOWER(result[i][si])) && - (c2 = TOLOWER(result[i + 1][si])); - si++) - if (c1 != c2) break; - } else { - for (si = 0; - (c1 = result[i][si]) && - (c2 = result[i + 1][si]); - si++) - if (c1 != c2) break; - } - - if (low > si) low = si; - i++; - } - result[0] = ALLOC_N(char, low + 1); - strncpy(result[0], result[1], low); - result[0][low] = '\0'; - } - - return result; -} - -static VALUE -readline_s_vi_editing_mode(self) - VALUE self; -{ - rl_vi_editing_mode(1,0); - return Qnil; -} - -static VALUE -readline_s_emacs_editing_mode(self) - VALUE self; -{ - rl_emacs_editing_mode(1,0); - return Qnil; -} - -static VALUE -readline_s_set_completion_append_character(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - if (NIL_P(str)) { - rl_completion_append_character = '\0'; - } else { - StringValue(str); - - rl_completion_append_character = RSTRING(str)->ptr[0]; - } - - return self; -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_get_completion_append_character(self) - VALUE self; -{ -#ifdef READLINE_21_OR_LATER - VALUE str; - - if (rl_completion_append_character == '\0') - return Qnil; - - str = rb_str_new("", 1); - RSTRING(str)->ptr[0] = rl_completion_append_character; - - return str; -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_set_basic_word_break_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - static char *basic_word_break_characters = NULL; - char *s; - - StringValue(str); - if (basic_word_break_characters == NULL) { - basic_word_break_characters = - ALLOC_N(char, RSTRING(str)->len + 1); - } - else { - REALLOC_N(basic_word_break_characters, char, RSTRING(str)->len + 1); - } - strncpy(basic_word_break_characters, - RSTRING(str)->ptr, RSTRING(str)->len); - basic_word_break_characters[RSTRING(str)->len] = '\0'; - rl_basic_word_break_characters = basic_word_break_characters; - - return self; -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_get_basic_word_break_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - if (rl_basic_word_break_characters == NULL) - return Qnil; - return rb_str_new2(rl_basic_word_break_characters); -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_set_completer_word_break_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - static char *completer_word_break_characters = NULL; - char *s; - - StringValue(str); - if (completer_word_break_characters == NULL) { - completer_word_break_characters = - ALLOC_N(char, RSTRING(str)->len + 1); - } - else { - REALLOC_N(completer_word_break_characters, char, RSTRING(str)->len + 1); - } - strncpy(completer_word_break_characters, - RSTRING(str)->ptr, RSTRING(str)->len); - completer_word_break_characters[RSTRING(str)->len] = '\0'; - rl_completer_word_break_characters = completer_word_break_characters; - - return self; -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_get_completer_word_break_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - if (rl_completer_word_break_characters == NULL) - return Qnil; - return rb_str_new2(rl_completer_word_break_characters); -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_set_basic_quote_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - static char *basic_quote_characters = NULL; - char *s; - - StringValue(str); - if (basic_quote_characters == NULL) { - basic_quote_characters = - ALLOC_N(char, RSTRING(str)->len + 1); - } - else { - REALLOC_N(basic_quote_characters, char, RSTRING(str)->len + 1); - } - strncpy(basic_quote_characters, - RSTRING(str)->ptr, RSTRING(str)->len); - basic_quote_characters[RSTRING(str)->len] = '\0'; - rl_basic_quote_characters = basic_quote_characters; - - return self; -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_get_basic_quote_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - if (rl_basic_quote_characters == NULL) - return Qnil; - return rb_str_new2(rl_basic_quote_characters); -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_set_completer_quote_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - static char *completer_quote_characters = NULL; - char *s; - - StringValue(str); - if (completer_quote_characters == NULL) { - completer_quote_characters = - ALLOC_N(char, RSTRING(str)->len + 1); - } - else { - REALLOC_N(completer_quote_characters, char, RSTRING(str)->len + 1); - } - strncpy(completer_quote_characters, - RSTRING(str)->ptr, RSTRING(str)->len); - completer_quote_characters[RSTRING(str)->len] = '\0'; - rl_completer_quote_characters = completer_quote_characters; - - return self; -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_get_completer_quote_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - if (rl_completer_quote_characters == NULL) - return Qnil; - return rb_str_new2(rl_completer_quote_characters); -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_set_filename_quote_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - static char *filename_quote_characters = NULL; - char *s; - - StringValue(str); - if (filename_quote_characters == NULL) { - filename_quote_characters = - ALLOC_N(char, RSTRING(str)->len + 1); - } - else { - REALLOC_N(filename_quote_characters, char, RSTRING(str)->len + 1); - } - strncpy(filename_quote_characters, - RSTRING(str)->ptr, RSTRING(str)->len); - filename_quote_characters[RSTRING(str)->len] = '\0'; - rl_filename_quote_characters = filename_quote_characters; - - return self; -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -readline_s_get_filename_quote_characters(self, str) - VALUE self, str; -{ -#ifdef READLINE_21_OR_LATER - if (rl_filename_quote_characters == NULL) - return Qnil; - return rb_str_new2(rl_filename_quote_characters); -#else - rb_notimplement(); -#endif /* READLINE_21_OR_LATER */ -} - -static VALUE -rb_remove_history(index) - int index; -{ - HIST_ENTRY *entry; - VALUE val; - - entry = remove_history(index); - if (entry) { - val = rb_tainted_str_new2(entry->line); - free(entry->line); - free(entry); - return val; - } - return Qnil; -} - -static VALUE -hist_to_s(self) - VALUE self; -{ - return rb_str_new2("HISTORY"); -} - -static VALUE -hist_get(self, index) - VALUE self; - VALUE index; -{ - HISTORY_STATE *state; - int i; - - state = history_get_history_state(); - i = NUM2INT(index); - if (i < 0) { - i += state->length; - } - if (i < 0 || i > state->length - 1) { - rb_raise(rb_eIndexError, "Invalid index"); - } - return rb_tainted_str_new2(state->entries[i]->line); -} - -static VALUE -hist_set(self, index, str) - VALUE self; - VALUE index; - VALUE str; -{ - HISTORY_STATE *state; - VALUE s = str; - int i; - - state = history_get_history_state(); - i = NUM2INT(index); - if (i < 0) { - i += state->length; - } - if (i < 0 || i > state->length - 1) { - rb_raise(rb_eIndexError, "Invalid index"); - } - replace_history_entry(i, StringValuePtr(s), NULL); - return str; -} - -static VALUE -hist_push(self, str) - VALUE self; - VALUE str; -{ - add_history(StringValuePtr(str)); - return self; -} - -static VALUE -hist_push_method(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - VALUE str; - - while (argc--) { - str = *argv++; - add_history(StringValuePtr(str)); - } - return self; -} - -static VALUE -hist_pop(self) - VALUE self; -{ - HISTORY_STATE *state; - - state = history_get_history_state(); - if (state->length > 0) { - return rb_remove_history(state->length - 1); - } else { - return Qnil; - } -} - -static VALUE -hist_shift(self) - VALUE self; -{ - HISTORY_STATE *state; - - state = history_get_history_state(); - if (state->length > 0) { - return rb_remove_history(0); - } else { - return Qnil; - } -} - -static VALUE -hist_each(self) - VALUE self; -{ - HISTORY_STATE *state; - int i; - - state = history_get_history_state(); - for (i = 0; i < state->length; i++) { - rb_yield(rb_tainted_str_new2(state->entries[i]->line)); - } - return self; -} - -static VALUE -hist_length(self) - VALUE self; -{ - HISTORY_STATE *state; - - state = history_get_history_state(); - return INT2NUM(state->length); -} - -static VALUE -hist_empty_p(self) - VALUE self; -{ - HISTORY_STATE *state; - - state = history_get_history_state(); - if (state->length == 0) - return Qtrue; - else - return Qfalse; -} - -static VALUE -hist_delete_at(self, index) - VALUE self; - VALUE index; -{ - HISTORY_STATE *state; - int i; - - state = history_get_history_state(); - i = NUM2INT(index); - if (i < 0) - i += state->length; - if (i < 0 || i > state->length - 1) { - rb_raise(rb_eIndexError, "Invalid index"); - } - return rb_remove_history(i); -} - -static VALUE -filename_completion_proc_call(self, str) - VALUE self; - VALUE str; -{ - VALUE result; - char **matches; - int i; - - matches = rl_completion_matches(StringValuePtr(str), - rl_filename_completion_function); - if (matches) { - result = rb_ary_new(); - for (i = 0; matches[i]; i++) { - rb_ary_push(result, rb_tainted_str_new2(matches[i])); - free(matches[i]); - } - free(matches); - if (RARRAY(result)->len >= 2) - rb_ary_shift(result); - } - else { - result = Qnil; - } - return result; -} - -static VALUE -username_completion_proc_call(self, str) - VALUE self; - VALUE str; -{ - VALUE result; - char **matches; - int i; - - matches = rl_completion_matches(StringValuePtr(str), - rl_username_completion_function); - if (matches) { - result = rb_ary_new(); - for (i = 0; matches[i]; i++) { - rb_ary_push(result, rb_tainted_str_new2(matches[i])); - free(matches[i]); - } - free(matches); - if (RARRAY(result)->len >= 2) - rb_ary_shift(result); - } - else { - result = Qnil; - } - return result; -} - -void -Init_readline() -{ - VALUE histary, fcomp, ucomp; - - /* Allow conditional parsing of the ~/.inputrc file. */ - rl_readline_name = "Ruby"; - - using_history(); - - mReadline = rb_define_module("Readline"); - rb_define_module_function(mReadline, "readline", - readline_readline, -1); - rb_define_singleton_method(mReadline, "completion_proc=", - readline_s_set_completion_proc, 1); - rb_define_singleton_method(mReadline, "completion_proc", - readline_s_get_completion_proc, 0); - rb_define_singleton_method(mReadline, "completion_case_fold=", - readline_s_set_completion_case_fold, 1); - rb_define_singleton_method(mReadline, "completion_case_fold", - readline_s_get_completion_case_fold, 0); - rb_define_singleton_method(mReadline, "vi_editing_mode", - readline_s_vi_editing_mode, 0); - rb_define_singleton_method(mReadline, "emacs_editing_mode", - readline_s_emacs_editing_mode, 0); - rb_define_singleton_method(mReadline, "completion_append_character=", - readline_s_set_completion_append_character, 1); - rb_define_singleton_method(mReadline, "completion_append_character", - readline_s_get_completion_append_character, 0); - rb_define_singleton_method(mReadline, "basic_word_break_characters=", - readline_s_set_basic_word_break_characters, 1); - rb_define_singleton_method(mReadline, "basic_word_break_characters", - readline_s_get_basic_word_break_characters, 0); - rb_define_singleton_method(mReadline, "completer_word_break_characters=", - readline_s_set_completer_word_break_characters, 1); - rb_define_singleton_method(mReadline, "completer_word_break_characters", - readline_s_get_completer_word_break_characters, 0); - rb_define_singleton_method(mReadline, "basic_quote_characters=", - readline_s_set_basic_quote_characters, 1); - rb_define_singleton_method(mReadline, "basic_quote_characters", - readline_s_get_basic_quote_characters, 0); - rb_define_singleton_method(mReadline, "completer_quote_characters=", - readline_s_set_completer_quote_characters, 1); - rb_define_singleton_method(mReadline, "completer_quote_characters", - readline_s_get_completer_quote_characters, 0); - rb_define_singleton_method(mReadline, "filename_quote_characters=", - readline_s_set_filename_quote_characters, 1); - rb_define_singleton_method(mReadline, "filename_quote_characters", - readline_s_get_filename_quote_characters, 0); - - histary = rb_obj_alloc(rb_cObject); - rb_extend_object(histary, rb_mEnumerable); - rb_define_singleton_method(histary,"to_s", hist_to_s, 0); - rb_define_singleton_method(histary,"[]", hist_get, 1); - rb_define_singleton_method(histary,"[]=", hist_set, 2); - rb_define_singleton_method(histary,"<<", hist_push, 1); - rb_define_singleton_method(histary,"push", hist_push_method, -1); - rb_define_singleton_method(histary,"pop", hist_pop, 0); - rb_define_singleton_method(histary,"shift", hist_shift, 0); - rb_define_singleton_method(histary,"each", hist_each, 0); - rb_define_singleton_method(histary,"length", hist_length, 0); - rb_define_singleton_method(histary,"size", hist_length, 0); - - rb_define_singleton_method(histary,"empty?", hist_empty_p, 0); - rb_define_singleton_method(histary,"delete_at", hist_delete_at, 1); - rb_define_const(mReadline, "HISTORY", histary); - - fcomp = rb_obj_alloc(rb_cObject); - rb_define_singleton_method(fcomp, "call", - filename_completion_proc_call, 1); - rb_define_const(mReadline, "FILENAME_COMPLETION_PROC", fcomp); - - ucomp = rb_obj_alloc(rb_cObject); - rb_define_singleton_method(ucomp, "call", - username_completion_proc_call, 1); - rb_define_const(mReadline, "USERNAME_COMPLETION_PROC", ucomp); -#if READLINE_21_OR_LATER - rb_define_const(mReadline, "VERSION", rb_str_new2(rl_library_version)); -#else - rb_define_const(mReadline, "VERSION", - rb_str_new2("2.0 or before version")); -#endif - - rl_attempted_completion_function - = (CPPFunction *) readline_attempted_completion_function; - rl_event_hook = readline_event; - rl_clear_signals(); -} diff --git a/ext/sdbm/.cvsignore b/ext/sdbm/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/sdbm/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/sdbm/MANIFEST b/ext/sdbm/MANIFEST deleted file mode 100644 index 8888e69ad4..0000000000 --- a/ext/sdbm/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -MANIFEST -_sdbm.c -depend -extconf.rb -init.c -sdbm.h diff --git a/ext/sdbm/_sdbm.c b/ext/sdbm/_sdbm.c deleted file mode 100644 index d8bfae80b2..0000000000 --- a/ext/sdbm/_sdbm.c +++ /dev/null @@ -1,973 +0,0 @@ -/* - * sdbm - ndbm work-alike hashed database library - * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978). - * author: oz@nexus.yorku.ca - * status: public domain. - * - * core routines - */ - -#ifndef lint -/*char sdbm_rcsid[] = "$Id$";*/ -#endif - -#include "sdbm.h" -#include "config.h" - -/* - * sdbm - ndbm work-alike hashed database library - * tuning and portability constructs [not nearly enough] - * author: oz@nexus.yorku.ca - */ - -#define BYTESIZ 8 - -#ifdef HAVE_UNISTD_H -#include -#endif - -#ifdef BSD42 -#define SEEK_SET L_SET -#define memset(s,c,n) bzero(s, n) /* only when c is zero */ -#define memcpy(s1,s2,n) bcopy(s2, s1, n) -#define memcmp(s1,s2,n) bcmp(s1,s2,n) -#endif - -/* - * important tuning parms (hah) - */ - -#define SEEDUPS /* always detect duplicates */ -#define BADMESS /* generate a message for worst case: - cannot make room after SPLTMAX splits */ -/* - * misc - */ -#ifdef DEBUG -#define debug(x) printf x -#else -#define debug(x) -#endif - -#ifdef BIG_E -#define GET_SHORT(p, i) (((unsigned)((unsigned char *)(p))[(i)*2] << 8) + (((unsigned char *)(p))[(i)*2 + 1])) -#define PUT_SHORT(p, i, s) (((unsigned char *)(p))[(i)*2] = (unsigned char)((s) >> 8), ((unsigned char *)(p))[(i)*2 + 1] = (unsigned char)(s)) -#else -#define GET_SHORT(p, i) ((p)[i]) -#define PUT_SHORT(p, i, s) ((p)[i] = (s)) -#endif - -/*#include "pair.h"*/ -static int fitpair proto((char *, int)); -static void putpair proto((char *, datum, datum)); -static datum getpair proto((char *, datum)); -static int delpair proto((char *, datum)); -static int chkpage proto((char *)); -static datum getnkey proto((char *, int)); -static void splpage proto((char *, char *, long)); -#ifdef SEEDUPS -static int duppair proto((char *, datum)); -#endif - -#include -#include -#ifdef MSDOS -#include -#endif -#include -#include -#ifdef BSD42 -#include -#else -#include -/*#include */ -#endif -#ifndef O_BINARY -#define O_BINARY 0 -#endif - -#include -#ifndef EPERM -#define EPERM EACCES -#endif -#include - -#ifdef __STDC__ -#include -#endif - -#ifndef NULL -#define NULL 0 -#endif - -/* - * externals - */ -#if !defined sun && !defined MSDOS && !defined _WIN32 && !defined __CYGWIN__ -extern int errno; -#endif - -/* - * forward - */ -static int getdbit proto((DBM *, long)); -static int setdbit proto((DBM *, long)); -static int getpage proto((DBM *, long)); -static datum getnext proto((DBM *)); -static int makroom proto((DBM *, long, int)); - -/* - * useful macros - */ -#define bad(x) ((x).dptr == NULL || (x).dsize < 0) -#define exhash(item) sdbm_hash((item).dptr, (item).dsize) -#define ioerr(db) ((db)->flags |= DBM_IOERR) - -#define OFF_PAG(off) (long) (off) * PBLKSIZ -#define OFF_DIR(off) (long) (off) * DBLKSIZ - -static long masks[] = { - 000000000000L, 000000000001L, 000000000003L, - 000000000007L, 000000000017L, 000000000037L, - 000000000077L, 000000000177L, 000000000377L, - 000000000777L, 000000001777L, 000000003777L, - 000000007777L, 000000017777L, 000000037777L, - 000000077777L, 000000177777L, 000000377777L, - 000000777777L, 000001777777L, 000003777777L, - 000007777777L, 000017777777L, 000037777777L, - 000077777777L, 000177777777L, 000377777777L, - 000777777777L, 001777777777L, 003777777777L, - 007777777777L, 017777777777L -}; - -datum nullitem = {NULL, 0}; - -DBM * -sdbm_open(file, flags, mode) -register char *file; -register int flags; -register int mode; -{ - register DBM *db; - register char *dirname; - register char *pagname; - register int n; - - if (file == NULL || !*file) - return errno = EINVAL, (DBM *) NULL; -/* - * need space for two seperate filenames - */ - n = strlen(file) * 2 + strlen(DIRFEXT) + strlen(PAGFEXT) + 2; - - if ((dirname = malloc((unsigned) n)) == NULL) - return errno = ENOMEM, (DBM *) NULL; -/* - * build the file names - */ - dirname = strcat(strcpy(dirname, file), DIRFEXT); - pagname = strcpy(dirname + strlen(dirname) + 1, file); - pagname = strcat(pagname, PAGFEXT); - - db = sdbm_prep(dirname, pagname, flags, mode); - free((char *) dirname); - return db; -} - -DBM * -sdbm_prep(dirname, pagname, flags, mode) -char *dirname; -char *pagname; -int flags; -int mode; -{ - register DBM *db; - struct stat dstat; - - if ((db = (DBM *) malloc(sizeof(DBM))) == NULL) - return errno = ENOMEM, (DBM *) NULL; - - db->flags = 0; - db->hmask = 0; - db->blkptr = 0; - db->keyptr = 0; -/* - * adjust user flags so that WRONLY becomes RDWR, - * as required by this package. Also set our internal - * flag for RDONLY. - */ - if (flags & O_WRONLY) - flags = (flags & ~O_WRONLY) | O_RDWR; - if (flags & O_RDONLY) - db->flags = DBM_RDONLY; -/* - * open the files in sequence, and stat the dirfile. - * If we fail anywhere, undo everything, return NULL. - */ - flags |= O_BINARY; - if ((db->pagf = open(pagname, flags, mode)) > -1) { - if ((db->dirf = open(dirname, flags, mode)) > -1) { -/* - * need the dirfile size to establish max bit number. - */ - if (fstat(db->dirf, &dstat) == 0) { -/* - * zero size: either a fresh database, or one with a single, - * unsplit data page: dirpage is all zeros. - */ - db->dirbno = (!dstat.st_size) ? 0 : -1; - db->pagbno = -1; - db->maxbno = dstat.st_size * (long) BYTESIZ; - - (void) memset(db->pagbuf, 0, PBLKSIZ); - (void) memset(db->dirbuf, 0, DBLKSIZ); - /* - * success - */ - return db; - } - (void) close(db->dirf); - } - (void) close(db->pagf); - } - free((char *) db); - return (DBM *) NULL; -} - -void -sdbm_close(db) -register DBM *db; -{ - if (db == NULL) - errno = EINVAL; - else { - (void) close(db->dirf); - (void) close(db->pagf); - free((char *) db); - } -} - -datum -sdbm_fetch(db, key) -register DBM *db; -datum key; -{ - if (db == NULL || bad(key)) - return errno = EINVAL, nullitem; - - if (getpage(db, exhash(key))) - return getpair(db->pagbuf, key); - - return ioerr(db), nullitem; -} - -int -sdbm_delete(db, key) -register DBM *db; -datum key; -{ - if (db == NULL || bad(key)) - return errno = EINVAL, -1; - if (sdbm_rdonly(db)) - return errno = EPERM, -1; - - if (getpage(db, exhash(key))) { - if (!delpair(db->pagbuf, key)) - return -1; -/* - * update the page file - */ - if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 - || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) - return ioerr(db), -1; - - return 0; - } - - return ioerr(db), -1; -} - -int -sdbm_store(db, key, val, flags) -register DBM *db; -datum key; -datum val; -int flags; -{ - int need; - register long hash; - - if (db == NULL || bad(key)) - return errno = EINVAL, -1; - if (sdbm_rdonly(db)) - return errno = EPERM, -1; - - need = key.dsize + val.dsize; -/* - * is the pair too big (or too small) for this database ?? - */ - if (need < 0 || need > PAIRMAX) - return errno = EINVAL, -1; - - if (getpage(db, (hash = exhash(key)))) { -/* - * if we need to replace, delete the key/data pair - * first. If it is not there, ignore. - */ - if (flags == DBM_REPLACE) - (void) delpair(db->pagbuf, key); -#ifdef SEEDUPS - else if (duppair(db->pagbuf, key)) - return 1; -#endif -/* - * if we do not have enough room, we have to split. - */ - if (!fitpair(db->pagbuf, need)) - if (!makroom(db, hash, need)) - return ioerr(db), -1; -/* - * we have enough room or split is successful. insert the key, - * and update the page file. - */ - (void) putpair(db->pagbuf, key, val); - - if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 - || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) - return ioerr(db), -1; - /* - * success - */ - return 0; - } - - return ioerr(db), -1; -} - -/* - * makroom - make room by splitting the overfull page - * this routine will attempt to make room for SPLTMAX times before - * giving up. - */ -static int -makroom(db, hash, need) -register DBM *db; -long hash; -int need; -{ - long newp; - char twin[PBLKSIZ]; -#if defined MSDOS || (defined _WIN32 && !defined __CYGWIN__) - char zer[PBLKSIZ]; - long oldtail; -#endif - char *pag = db->pagbuf; - char *new = twin; - register int smax = SPLTMAX; - - do { -/* - * split the current page - */ - (void) splpage(pag, new, db->hmask + 1); -/* - * address of the new page - */ - newp = (hash & db->hmask) | (db->hmask + 1); - debug(("newp: %ld\n", newp)); -/* - * write delay, read avoidence/cache shuffle: - * select the page for incoming pair: if key is to go to the new page, - * write out the previous one, and copy the new one over, thus making - * it the current page. If not, simply write the new page, and we are - * still looking at the page of interest. current page is not updated - * here, as sdbm_store will do so, after it inserts the incoming pair. - */ - -#if defined MSDOS || (defined _WIN32 && !defined __CYGWIN__) - /* - * Fill hole with 0 if made it. - * (hole is NOT read as 0) - */ - oldtail = lseek(db->pagf, 0L, SEEK_END); - memset(zer, 0, PBLKSIZ); - while (OFF_PAG(newp) > oldtail) { - if (lseek(db->pagf, 0L, SEEK_END) < 0 || - write(db->pagf, zer, PBLKSIZ) < 0) { - - return 0; - } - oldtail += PBLKSIZ; - } -#endif - - if (hash & (db->hmask + 1)) { - if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 - || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) - return 0; - db->pagbno = newp; - (void) memcpy(pag, new, PBLKSIZ); - } - else if (lseek(db->pagf, OFF_PAG(newp), SEEK_SET) < 0 - || write(db->pagf, new, PBLKSIZ) < 0) - return 0; - - if (!setdbit(db, db->curbit)) - return 0; -/* - * see if we have enough room now - */ - if (fitpair(pag, need)) - return 1; -/* - * try again... update curbit and hmask as getpage would have - * done. because of our update of the current page, we do not - * need to read in anything. BUT we have to write the current - * [deferred] page out, as the window of failure is too great. - */ - db->curbit = 2 * db->curbit + - ((hash & (db->hmask + 1)) ? 2 : 1); - db->hmask |= (db->hmask + 1); - - if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 - || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) - return 0; - - } while (--smax); -/* - * if we are here, this is real bad news. After SPLTMAX splits, - * we still cannot fit the key. say goodnight. - */ -#ifdef BADMESS - (void) write(2, "sdbm: cannot insert after SPLTMAX attempts.\n", 44); -#endif - return 0; - -} - -/* - * the following two routines will break if - * deletions aren't taken into account. (ndbm bug) - */ -datum -sdbm_firstkey(db) -register DBM *db; -{ - if (db == NULL) - return errno = EINVAL, nullitem; -/* - * start at page 0 - */ - (void) memset(db->pagbuf, 0, PBLKSIZ); - if (lseek(db->pagf, OFF_PAG(0), SEEK_SET) < 0 - || read(db->pagf, db->pagbuf, PBLKSIZ) < 0) - return ioerr(db), nullitem; - db->pagbno = 0; - db->blkptr = 0; - db->keyptr = 0; - - return getnext(db); -} - -datum -sdbm_nextkey(db) -register DBM *db; -{ - if (db == NULL) - return errno = EINVAL, nullitem; - return getnext(db); -} - -/* - * all important binary trie traversal - */ -static int -getpage(db, hash) -register DBM *db; -register long hash; -{ - register int hbit; - register long dbit; - register long pagb; - - dbit = 0; - hbit = 0; - while (dbit < db->maxbno && getdbit(db, dbit)) - dbit = 2 * dbit + ((hash & ((long) 1 << hbit++)) ? 2 : 1); - - debug(("dbit: %d...", dbit)); - - db->curbit = dbit; - db->hmask = masks[hbit]; - - pagb = hash & db->hmask; -/* - * see if the block we need is already in memory. - * note: this lookaside cache has about 10% hit rate. - */ - if (pagb != db->pagbno) { -/* - * note: here, we assume a "hole" is read as 0s. - * if not, must zero pagbuf first. - */ - (void) memset(db->pagbuf, 0, PBLKSIZ); - - if (lseek(db->pagf, OFF_PAG(pagb), SEEK_SET) < 0 - || read(db->pagf, db->pagbuf, PBLKSIZ) < 0) - return 0; - if (!chkpage(db->pagbuf)) { - return 0; - } - db->pagbno = pagb; - - debug(("pag read: %d\n", pagb)); - } - return 1; -} - -static int -getdbit(db, dbit) -register DBM *db; -register long dbit; -{ - register long c; - register long dirb; - - c = dbit / BYTESIZ; - dirb = c / DBLKSIZ; - - if (dirb != db->dirbno) { - if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0 - || read(db->dirf, db->dirbuf, DBLKSIZ) < 0) - return 0; - db->dirbno = dirb; - - debug(("dir read: %d\n", dirb)); - } - - return db->dirbuf[c % DBLKSIZ] & (1 << (dbit % BYTESIZ)); -} - -static int -setdbit(db, dbit) -register DBM *db; -register long dbit; -{ - register long c; - register long dirb; - - c = dbit / BYTESIZ; - dirb = c / DBLKSIZ; - - if (dirb != db->dirbno) { - if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0 - || read(db->dirf, db->dirbuf, DBLKSIZ) < 0) - return 0; - db->dirbno = dirb; - - debug(("dir read: %d\n", dirb)); - } - - db->dirbuf[c % DBLKSIZ] |= (1 << (dbit % BYTESIZ)); - - if (dbit >= db->maxbno) - db->maxbno += (long) DBLKSIZ * BYTESIZ; - - if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0 - || write(db->dirf, db->dirbuf, DBLKSIZ) < 0) - return 0; - - return 1; -} - -/* - * getnext - get the next key in the page, and if done with - * the page, try the next page in sequence - */ -static datum -getnext(db) -register DBM *db; -{ - datum key; - - for (;;) { - db->keyptr++; - key = getnkey(db->pagbuf, db->keyptr); - if (key.dptr != NULL) - return key; -/* - * we either run out, or there is nothing on this page.. - * try the next one... If we lost our position on the - * file, we will have to seek. - */ - db->keyptr = 0; - if (db->pagbno != db->blkptr++) - if (lseek(db->pagf, OFF_PAG(db->blkptr), SEEK_SET) < 0) - break; - db->pagbno = db->blkptr; - if (read(db->pagf, db->pagbuf, PBLKSIZ) <= 0) - break; - if (!chkpage(db->pagbuf)) { - break; - } - } - - return ioerr(db), nullitem; -} - -/* pair.c */ -/* - * sdbm - ndbm work-alike hashed database library - * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978). - * author: oz@nexus.yorku.ca - * status: public domain. - * - * page-level routines - */ - -#ifndef lint -/*char pair_rcsid[] = "$Id$";*/ -#endif - -#ifndef BSD42 -/*#include */ -#endif - -#define exhash(item) sdbm_hash((item).dptr, (item).dsize) - -/* - * forward - */ -static int seepair proto((char *, int, char *, int)); - -/* - * page format: - * +------------------------------+ - * ino | n | keyoff | datoff | keyoff | - * +------------+--------+--------+ - * | datoff | - - - ----> | - * +--------+---------------------+ - * | F R E E A R E A | - * +--------------+---------------+ - * | <---- - - - | data | - * +--------+-----+----+----------+ - * | key | data | key | - * +--------+----------+----------+ - * - * calculating the offsets for free area: if the number - * of entries (ino[0]) is zero, the offset to the END of - * the free area is the block size. Otherwise, it is the - * nth (ino[ino[0]]) entry's offset. - */ - -static int -fitpair(pag, need) -char *pag; -int need; -{ - register int n; - register int off; - register int free; - register short *ino = (short *) pag; - - off = ((n = GET_SHORT(ino,0)) > 0) ? GET_SHORT(ino,n) : PBLKSIZ; - free = off - (n + 1) * sizeof(short); - need += 2 * sizeof(short); - - debug(("free %d need %d\n", free, need)); - - return need <= free; -} - -static void -putpair(pag, key, val) -char *pag; -datum key; -datum val; -{ - register int n; - register int off; - register short *ino = (short *) pag; - - off = ((n = GET_SHORT(ino,0)) > 0) ? GET_SHORT(ino,n) : PBLKSIZ; -/* - * enter the key first - */ - off -= key.dsize; - if (key.dsize) - (void) memcpy(pag + off, key.dptr, key.dsize); - PUT_SHORT(ino,n + 1,off); -/* - * now the data - */ - off -= val.dsize; - if (val.dsize) - (void) memcpy(pag + off, val.dptr, val.dsize); - PUT_SHORT(ino,n + 2,off); -/* - * adjust item count - */ - PUT_SHORT(ino,0,GET_SHORT(ino,0) + 2); -} - -static datum -getpair(pag, key) -char *pag; -datum key; -{ - register int i; - register int n; - datum val; - register short *ino = (short *) pag; - - if ((n = GET_SHORT(ino,0)) == 0) - return nullitem; - - if ((i = seepair(pag, n, key.dptr, key.dsize)) == 0) - return nullitem; - - val.dptr = pag + GET_SHORT(ino,i + 1); - val.dsize = GET_SHORT(ino,i) - GET_SHORT(ino,i + 1); - return val; -} - -#ifdef SEEDUPS -static int -duppair(pag, key) -char *pag; -datum key; -{ - register short *ino = (short *) pag; - return GET_SHORT(ino,0) > 0 && - seepair(pag, GET_SHORT(ino,0), key.dptr, key.dsize) > 0; -} -#endif - -static datum -getnkey(pag, num) -char *pag; -int num; -{ - datum key; - register int off; - register short *ino = (short *) pag; - - num = num * 2 - 1; - if (GET_SHORT(ino,0) == 0 || num > GET_SHORT(ino,0)) - return nullitem; - - off = (num > 1) ? GET_SHORT(ino,num - 1) : PBLKSIZ; - - key.dptr = pag + GET_SHORT(ino,num); - key.dsize = off - GET_SHORT(ino,num); - - return key; -} - -static int -delpair(pag, key) -char *pag; -datum key; -{ - register int n; - register int i; - register short *ino = (short *) pag; - - if ((n = GET_SHORT(ino,0)) == 0) - return 0; - - if ((i = seepair(pag, n, key.dptr, key.dsize)) == 0) - return 0; -/* - * found the key. if it is the last entry - * [i.e. i == n - 1] we just adjust the entry count. - * hard case: move all data down onto the deleted pair, - * shift offsets onto deleted offsets, and adjust them. - * [note: 0 < i < n] - */ - if (i < n - 1) { - register int m; - register char *dst = pag + (i == 1 ? PBLKSIZ : GET_SHORT(ino,i - 1)); - register char *src = pag + GET_SHORT(ino,i + 1); - register int zoo = dst - src; - - debug(("free-up %d ", zoo)); -/* - * shift data/keys down - */ - m = GET_SHORT(ino,i + 1) - GET_SHORT(ino,n); -#ifdef DUFF -#define MOVB *--dst = *--src - - if (m > 0) { - register int loop = (m + 8 - 1) >> 3; - - switch (m & (8 - 1)) { - case 0: do { - MOVB; case 7: MOVB; - case 6: MOVB; case 5: MOVB; - case 4: MOVB; case 3: MOVB; - case 2: MOVB; case 1: MOVB; - } while (--loop); - } - } -#else -#ifdef MEMMOVE - memmove(dst, src, m); -#else - while (m--) - *--dst = *--src; -#endif -#endif -/* - * adjust offset index up - */ - while (i < n - 1) { - PUT_SHORT(ino,i, GET_SHORT(ino,i + 2) + zoo); - i++; - } - } - PUT_SHORT(ino, 0, GET_SHORT(ino, 0) - 2); - return 1; -} - -/* - * search for the key in the page. - * return offset index in the range 0 < i < n. - * return 0 if not found. - */ -static int -seepair(pag, n, key, siz) -char *pag; -register int n; -register char *key; -register int siz; -{ - register int i; - register int off = PBLKSIZ; - register short *ino = (short *) pag; - - for (i = 1; i < n; i += 2) { - if (siz == off - GET_SHORT(ino,i) && - memcmp(key, pag + GET_SHORT(ino,i), siz) == 0) - return i; - off = GET_SHORT(ino,i + 1); - } - return 0; -} - -static void -splpage(pag, new, sbit) -char *pag; -char *new; -long sbit; -{ - datum key; - datum val; - - register int n; - register int off = PBLKSIZ; - char cur[PBLKSIZ]; - register short *ino = (short *) cur; - - (void) memcpy(cur, pag, PBLKSIZ); - (void) memset(pag, 0, PBLKSIZ); - (void) memset(new, 0, PBLKSIZ); - - n = GET_SHORT(ino,0); - for (ino++; n > 0; ino += 2) { - key.dptr = cur + GET_SHORT(ino,0); - key.dsize = off - GET_SHORT(ino,0); - val.dptr = cur + GET_SHORT(ino,1); - val.dsize = GET_SHORT(ino,0) - GET_SHORT(ino,1); -/* - * select the page pointer (by looking at sbit) and insert - */ - (void) putpair((exhash(key) & sbit) ? new : pag, key, val); - - off = GET_SHORT(ino,1); - n -= 2; - } - - debug(("%d split %d/%d\n", ((short *) cur)[0] / 2, - ((short *) new)[0] / 2, - ((short *) pag)[0] / 2)); -} - -/* - * check page sanity: - * number of entries should be something - * reasonable, and all offsets in the index should be in order. - * this could be made more rigorous. - */ -static int -chkpage(pag) -char *pag; -{ - register int n; - register int off; - register short *ino = (short *) pag; - - if ((n = GET_SHORT(ino,0)) < 0 || n > PBLKSIZ / sizeof(short)) - return 0; - - if (n > 0) { - off = PBLKSIZ; - for (ino++; n > 0; ino += 2) { - if (GET_SHORT(ino,0) > off || GET_SHORT(ino,1) > off || - GET_SHORT(ino,1) > GET_SHORT(ino,0)) - return 0; - off = GET_SHORT(ino,1); - n -= 2; - } - } - return 1; -} - -/* hash.c */ -/* - * sdbm - ndbm work-alike hashed database library - * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978). - * author: oz@nexus.yorku.ca - * status: public domain. keep it that way. - * - * hashing routine - */ - -/* - * polynomial conversion ignoring overflows - * [this seems to work remarkably well, in fact better - * then the ndbm hash function. Replace at your own risk] - * use: 65599 nice. - * 65587 even better. - */ -long -sdbm_hash(str, len) -register char *str; -register int len; -{ - register unsigned long n = 0; - -#ifdef DUFF - -#define HASHC n = *str++ + 65599 * n - - if (len > 0) { - register int loop = (len + 8 - 1) >> 3; - - switch(len & (8 - 1)) { - case 0: do { - HASHC; case 7: HASHC; - case 6: HASHC; case 5: HASHC; - case 4: HASHC; case 3: HASHC; - case 2: HASHC; case 1: HASHC; - } while (--loop); - } - - } -#else - while (len--) - n = ((*str++) & 255) + 65587L * n; -#endif - return n; -} diff --git a/ext/sdbm/depend b/ext/sdbm/depend deleted file mode 100644 index 1d8b13d13f..0000000000 --- a/ext/sdbm/depend +++ /dev/null @@ -1,2 +0,0 @@ -_sdbm.o: _sdbm.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h -init.o: init.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/sdbm/extconf.rb b/ext/sdbm/extconf.rb deleted file mode 100644 index cc6c8cefd1..0000000000 --- a/ext/sdbm/extconf.rb +++ /dev/null @@ -1,3 +0,0 @@ -require 'mkmf' - -create_makefile("sdbm") diff --git a/ext/sdbm/init.c b/ext/sdbm/init.c deleted file mode 100644 index 5412dd8452..0000000000 --- a/ext/sdbm/init.c +++ /dev/null @@ -1,761 +0,0 @@ -/************************************************ - - sdbminit.c - - - $Author$ - $Date$ - created at: Fri May 7 08:34:24 JST 1999 - - Copyright (C) 1995-2001 Yukihiro Matsumoto - -************************************************/ - -#include "ruby.h" - -#include "sdbm.h" -#include -#include - -static VALUE rb_cDBM, rb_eDBMError; - -struct dbmdata { - int di_size; - DBM *di_dbm; -}; - -static void -closed_sdbm() -{ - rb_raise(rb_eDBMError, "closed SDBM file"); -} - -#define GetDBM(obj, dbmp) {\ - Data_Get_Struct(obj, struct dbmdata, dbmp);\ - if (dbmp->di_dbm == 0) closed_sdbm();\ -} - -static void -free_sdbm(dbmp) - struct dbmdata *dbmp; -{ - - if (dbmp->di_dbm) sdbm_close(dbmp->di_dbm); - free(dbmp); -} - -static VALUE -fsdbm_close(obj) - VALUE obj; -{ - struct dbmdata *dbmp; - - GetDBM(obj, dbmp); - sdbm_close(dbmp->di_dbm); - dbmp->di_dbm = 0; - - return Qnil; -} - -static VALUE -fsdbm_s_new(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = Data_Wrap_Struct(klass, 0, free_sdbm, 0); - rb_obj_call_init(obj, argc, argv); - return obj; -} - -static VALUE -fsdbm_initialize(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE file, vmode; - DBM *dbm; - struct dbmdata *dbmp; - int mode; - - if (rb_scan_args(argc, argv, "11", &file, &vmode) == 1) { - mode = 0666; /* default value */ - } - else if (NIL_P(vmode)) { - mode = -1; /* return nil if DB not exist */ - } - else { - mode = NUM2INT(vmode); - } - SafeStringValue(file); - - dbm = 0; - if (mode >= 0) - dbm = sdbm_open(RSTRING(file)->ptr, O_RDWR|O_CREAT, mode); - if (!dbm) - dbm = sdbm_open(RSTRING(file)->ptr, O_RDWR, 0); - if (!dbm) - dbm = sdbm_open(RSTRING(file)->ptr, O_RDONLY, 0); - - if (!dbm) { - if (mode == -1) return Qnil; - rb_sys_fail(RSTRING(file)->ptr); - } - - dbmp = ALLOC(struct dbmdata); - DATA_PTR(obj) = dbmp; - dbmp->di_dbm = dbm; - dbmp->di_size = -1; - - return obj; -} - -static VALUE -fsdbm_s_open(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = Data_Wrap_Struct(klass, 0, free_sdbm, 0); - - if (NIL_P(fsdbm_initialize(argc, argv, obj))) { - return Qnil; - } - - if (rb_block_given_p()) { - return rb_ensure(rb_yield, obj, fsdbm_close, obj); - } - - return obj; -} - -static VALUE -fsdbm_fetch(obj, keystr, ifnone) - VALUE obj, keystr, ifnone; -{ - datum key, value; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(keystr); - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - value = sdbm_fetch(dbm, key); - if (value.dptr == 0) { - if (ifnone == Qnil && rb_block_given_p()) - return rb_yield(rb_tainted_str_new(key.dptr, key.dsize)); - return ifnone; - } - return rb_tainted_str_new(value.dptr, value.dsize); -} - -static VALUE -fsdbm_aref(obj, keystr) - VALUE obj, keystr; -{ - return fsdbm_fetch(obj, keystr, Qnil); -} - -static VALUE -fsdbm_fetch_m(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE keystr, valstr, ifnone; - - rb_scan_args(argc, argv, "11", &keystr, &ifnone); - valstr = fsdbm_fetch(obj, keystr, ifnone); - if (argc == 1 && !rb_block_given_p() && NIL_P(valstr)) - rb_raise(rb_eIndexError, "key not found"); - - return valstr; -} - -static VALUE -fsdbm_index(obj, valstr) - VALUE obj, valstr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(valstr); - val.dptr = RSTRING(valstr)->ptr; - val.dsize = RSTRING(valstr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - if (val.dsize == RSTRING(valstr)->len && - memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0) - return rb_tainted_str_new(key.dptr, key.dsize); - } - return Qnil; -} - -static VALUE -fsdbm_indexes(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE new; - int i; - - new = rb_ary_new2(argc); - for (i=0; i 0) { - rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc); - } - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - VALUE assoc; - val = sdbm_fetch(dbm, key); - assoc = rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize), - rb_tainted_str_new(val.dptr, val.dsize)); - if (RTEST(rb_yield(assoc))) - rb_ary_push(new, assoc); - } - } - else { - for (i=0; iptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - dbmp->di_size = -1; - - value = sdbm_fetch(dbm, key); - if (value.dptr == 0) { - if (rb_block_given_p()) return rb_yield(keystr); - return Qnil; - } - - /* need to save value before sdbm_delete() */ - valstr = rb_tainted_str_new(value.dptr, value.dsize); - - if (sdbm_delete(dbm, key)) { - dbmp->di_size = -1; - rb_raise(rb_eDBMError, "dbm_delete failed"); - } - else if (dbmp->di_size >= 0) { - dbmp->di_size--; - } - return valstr; -} - -static VALUE -fsdbm_shift(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE keystr, valstr; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - key = sdbm_firstkey(dbm); - if (!key.dptr) return Qnil; - val = sdbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - sdbm_delete(dbm, key); - if (dbmp->di_size >= 0) { - dbmp->di_size--; - } - - return rb_assoc_new(keystr, valstr); -} - -static VALUE -fsdbm_delete_if(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE keystr, valstr; - VALUE ret, ary = rb_ary_new(); - int i, status = 0, n; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - n = dbmp->di_size; - dbmp->di_size = -1; - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - ret = rb_protect(rb_yield, rb_assoc_new(rb_str_dup(keystr), valstr), &status); - if (status != 0) break; - if (RTEST(ret)) rb_ary_push(ary, keystr); - } - - for (i = 0; i < RARRAY(ary)->len; i++) { - keystr = RARRAY(ary)->ptr[i]; - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - if (sdbm_delete(dbm, key)) { - rb_raise(rb_eDBMError, "sdbm_delete failed"); - } - } - if (status) rb_jump_tag(status); - if (n > 0) dbmp->di_size = n - RARRAY(ary)->len; - - return obj; -} - -static VALUE -fsdbm_clear(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - - rb_secure(4); - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - dbmp->di_size = -1; - while (key = sdbm_firstkey(dbm), key.dptr) { - if (sdbm_delete(dbm, key)) { - rb_raise(rb_eDBMError, "sdbm_delete failed"); - } - } - dbmp->di_size = 0; - - return obj; -} - -static VALUE -fsdbm_invert(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE keystr, valstr; - VALUE hash = rb_hash_new(); - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - rb_hash_aset(hash, valstr, keystr); - } - return hash; -} - -static VALUE -each_pair(obj) - VALUE obj; -{ - return rb_funcall(obj, rb_intern("each_pair"), 0, 0); -} - -static VALUE fsdbm_store _((VALUE,VALUE,VALUE)); - -static VALUE -update_i(pair, dbm) - VALUE pair, dbm; -{ - Check_Type(pair, T_ARRAY); - if (RARRAY(pair)->len < 2) { - rb_raise(rb_eArgError, "pair must be [key, value]"); - } - fsdbm_store(dbm, RARRAY(pair)->ptr[0], RARRAY(pair)->ptr[1]); - return Qnil; -} - -static VALUE -fsdbm_update(obj, other) - VALUE obj, other; -{ - rb_iterate(each_pair, other, update_i, obj); - return obj; -} - -static VALUE -fsdbm_replace(obj, other) - VALUE obj, other; -{ - fsdbm_clear(obj); - rb_iterate(each_pair, other, update_i, obj); - return obj; -} - -static VALUE -fsdbm_store(obj, keystr, valstr) - VALUE obj, keystr, valstr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - if (valstr == Qnil) { - fsdbm_delete(obj, keystr); - return Qnil; - } - - rb_secure(4); - keystr = rb_obj_as_string(keystr); - - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - if (NIL_P(valstr)) return fsdbm_delete(obj, keystr); - - valstr = rb_obj_as_string(valstr); - val.dptr = RSTRING(valstr)->ptr; - val.dsize = RSTRING(valstr)->len; - - GetDBM(obj, dbmp); - dbmp->di_size = -1; - dbm = dbmp->di_dbm; - if (sdbm_store(dbm, key, val, DBM_REPLACE)) { -#ifdef HAVE_DBM_CLAERERR - sdbm_clearerr(dbm); -#endif - if (errno == EPERM) rb_sys_fail(0); - rb_raise(rb_eDBMError, "sdbm_store failed"); - } - - return valstr; -} - -static VALUE -fsdbm_length(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - int i = 0; - - GetDBM(obj, dbmp); - if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size); - dbm = dbmp->di_dbm; - - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - i++; - } - dbmp->di_size = i; - - return INT2FIX(i); -} - -static VALUE -fsdbm_empty_p(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - int i = 0; - - GetDBM(obj, dbmp); - if (dbmp->di_size < 0) { - dbm = dbmp->di_dbm; - - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - i++; - } - } - else { - i = dbmp->di_size; - } - if (i == 0) return Qtrue; - return Qfalse; -} - -static VALUE -fsdbm_each_value(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - rb_yield(rb_tainted_str_new(val.dptr, val.dsize)); - } - return obj; -} - -static VALUE -fsdbm_each_key(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - rb_yield(rb_tainted_str_new(key.dptr, key.dsize)); - } - return obj; -} - -static VALUE -fsdbm_each_pair(obj) - VALUE obj; -{ - datum key, val; - DBM *dbm; - struct dbmdata *dbmp; - VALUE keystr, valstr; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - keystr = rb_tainted_str_new(key.dptr, key.dsize); - valstr = rb_tainted_str_new(val.dptr, val.dsize); - rb_yield(rb_assoc_new(keystr, valstr)); - } - - return obj; -} - -static VALUE -fsdbm_keys(obj) - VALUE obj; -{ - datum key; - struct dbmdata *dbmp; - DBM *dbm; - VALUE ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - rb_ary_push(ary, rb_tainted_str_new(key.dptr, key.dsize)); - } - - return ary; -} - -static VALUE -fsdbm_values(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - rb_ary_push(ary, rb_tainted_str_new(val.dptr, val.dsize)); - } - - return ary; -} - -static VALUE -fsdbm_has_key(obj, keystr) - VALUE obj, keystr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(keystr); - key.dptr = RSTRING(keystr)->ptr; - key.dsize = RSTRING(keystr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - val = sdbm_fetch(dbm, key); - if (val.dptr) return Qtrue; - return Qfalse; -} - -static VALUE -fsdbm_has_value(obj, valstr) - VALUE obj, valstr; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - - StringValue(valstr); - val.dptr = RSTRING(valstr)->ptr; - val.dsize = RSTRING(valstr)->len; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - if (val.dsize == RSTRING(valstr)->len && - memcmp(val.dptr, RSTRING(valstr)->ptr, val.dsize) == 0) - return Qtrue; - } - return Qfalse; -} - -static VALUE -fsdbm_to_a(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE ary; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - ary = rb_ary_new(); - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - rb_ary_push(ary, rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize), - rb_tainted_str_new(val.dptr, val.dsize))); - } - - return ary; -} - -static VALUE -fsdbm_to_hash(obj) - VALUE obj; -{ - datum key, val; - struct dbmdata *dbmp; - DBM *dbm; - VALUE hash; - - GetDBM(obj, dbmp); - dbm = dbmp->di_dbm; - - hash = rb_hash_new(); - for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) { - val = sdbm_fetch(dbm, key); - rb_hash_aset(hash, rb_tainted_str_new(key.dptr, key.dsize), - rb_tainted_str_new(val.dptr, val.dsize)); - } - - return hash; -} - -static VALUE -fsdbm_reject(obj) - VALUE obj; -{ - return rb_hash_delete_if(fsdbm_to_hash(obj)); -} - -void -Init_sdbm() -{ - rb_cDBM = rb_define_class("SDBM", rb_cObject); - rb_eDBMError = rb_define_class("SDBMError", rb_eStandardError); - rb_include_module(rb_cDBM, rb_mEnumerable); - - rb_define_singleton_method(rb_cDBM, "new", fsdbm_s_new, -1); - rb_define_singleton_method(rb_cDBM, "open", fsdbm_s_open, -1); - - rb_define_method(rb_cDBM, "initialize", fsdbm_initialize, -1); - rb_define_method(rb_cDBM, "close", fsdbm_close, 0); - rb_define_method(rb_cDBM, "[]", fsdbm_aref, 1); - rb_define_method(rb_cDBM, "fetch", fsdbm_fetch_m, -1); - rb_define_method(rb_cDBM, "[]=", fsdbm_store, 2); - rb_define_method(rb_cDBM, "store", fsdbm_store, 2); - rb_define_method(rb_cDBM, "index", fsdbm_index, 1); - rb_define_method(rb_cDBM, "indexes", fsdbm_indexes, -1); - rb_define_method(rb_cDBM, "indices", fsdbm_indexes, -1); - rb_define_method(rb_cDBM, "select", fsdbm_select, -1); - rb_define_method(rb_cDBM, "length", fsdbm_length, 0); - rb_define_method(rb_cDBM, "size", fsdbm_length, 0); - rb_define_method(rb_cDBM, "empty?", fsdbm_empty_p, 0); - rb_define_method(rb_cDBM, "each", fsdbm_each_pair, 0); - rb_define_method(rb_cDBM, "each_value", fsdbm_each_value, 0); - rb_define_method(rb_cDBM, "each_key", fsdbm_each_key, 0); - rb_define_method(rb_cDBM, "each_pair", fsdbm_each_pair, 0); - rb_define_method(rb_cDBM, "keys", fsdbm_keys, 0); - rb_define_method(rb_cDBM, "values", fsdbm_values, 0); - rb_define_method(rb_cDBM, "shift", fsdbm_shift, 0); - rb_define_method(rb_cDBM, "delete", fsdbm_delete, 1); - rb_define_method(rb_cDBM, "delete_if", fsdbm_delete_if, 0); - rb_define_method(rb_cDBM, "reject!", fsdbm_delete_if, 0); - rb_define_method(rb_cDBM, "reject", fsdbm_reject, 0); - rb_define_method(rb_cDBM, "clear", fsdbm_clear, 0); - rb_define_method(rb_cDBM,"invert", fsdbm_invert, 0); - rb_define_method(rb_cDBM,"update", fsdbm_update, 1); - rb_define_method(rb_cDBM,"replace", fsdbm_replace, 1); - - rb_define_method(rb_cDBM, "include?", fsdbm_has_key, 1); - rb_define_method(rb_cDBM, "has_key?", fsdbm_has_key, 1); - rb_define_method(rb_cDBM, "member?", fsdbm_has_key, 1); - rb_define_method(rb_cDBM, "has_value?", fsdbm_has_value, 1); - rb_define_method(rb_cDBM, "key?", fsdbm_has_key, 1); - rb_define_method(rb_cDBM, "value?", fsdbm_has_value, 1); - - rb_define_method(rb_cDBM, "to_a", fsdbm_to_a, 0); - rb_define_method(rb_cDBM, "to_hash", fsdbm_to_hash, 0); -} diff --git a/ext/sdbm/sdbm.h b/ext/sdbm/sdbm.h deleted file mode 100644 index ce8f54c4d4..0000000000 --- a/ext/sdbm/sdbm.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * sdbm - ndbm work-alike hashed database library - * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978). - * author: oz@nexus.yorku.ca - * status: public domain. - */ -#ifndef _SDBM_H_ -#define _SDBM_H_ - -#define DBLKSIZ 4096 -#define PBLKSIZ 1024 -#define PAIRMAX 1008 /* arbitrary on PBLKSIZ-N */ -#define SPLTMAX 10 /* maximum allowed splits */ - /* for a single insertion */ -#define DIRFEXT ".dir" -#define PAGFEXT ".pag" - -typedef struct { - int dirf; /* directory file descriptor */ - int pagf; /* page file descriptor */ - int flags; /* status/error flags, see below */ - long maxbno; /* size of dirfile in bits */ - long curbit; /* current bit number */ - long hmask; /* current hash mask */ - long blkptr; /* current block for nextkey */ - int keyptr; /* current key for nextkey */ - long blkno; /* current page to read/write */ - long pagbno; /* current page in pagbuf */ - char pagbuf[PBLKSIZ]; /* page file block buffer */ - long dirbno; /* current block in dirbuf */ - char dirbuf[DBLKSIZ]; /* directory file block buffer */ -} DBM; - -#define DBM_RDONLY 0x1 /* data base open read-only */ -#define DBM_IOERR 0x2 /* data base I/O error */ - -/* - * utility macros - */ -#define sdbm_rdonly(db) ((db)->flags & DBM_RDONLY) -#define sdbm_error(db) ((db)->flags & DBM_IOERR) - -#define sdbm_clearerr(db) ((db)->flags &= ~DBM_IOERR) /* ouch */ - -#define sdbm_dirfno(db) ((db)->dirf) -#define sdbm_pagfno(db) ((db)->pagf) - -typedef struct { - char *dptr; - int dsize; -} datum; - -extern datum nullitem; - -#if defined(__STDC__) || defined(MSDOS) -#define proto(p) p -#else -#define proto(p) () -#endif - -/* - * flags to sdbm_store - */ -#define DBM_INSERT 0 -#define DBM_REPLACE 1 - -/* - * ndbm interface - */ -extern DBM *sdbm_open proto((char *, int, int)); -extern void sdbm_close proto((DBM *)); -extern datum sdbm_fetch proto((DBM *, datum)); -extern int sdbm_delete proto((DBM *, datum)); -extern int sdbm_store proto((DBM *, datum, datum, int)); -extern datum sdbm_firstkey proto((DBM *)); -extern datum sdbm_nextkey proto((DBM *)); - -/* - * other - */ -extern DBM *sdbm_prep proto((char *, char *, int, int)); -extern long sdbm_hash proto((char *, int)); - -#endif /* _SDBM_H_ */ diff --git a/ext/sdbm/testsdbm.rb b/ext/sdbm/testsdbm.rb deleted file mode 100644 index 550b47a008..0000000000 --- a/ext/sdbm/testsdbm.rb +++ /dev/null @@ -1,556 +0,0 @@ -require 'runit/testcase' -require 'runit/cui/testrunner' - -if $".grep(/\bsdbm.so\b/).empty? - begin - require './sdbm' - rescue LoadError - require 'sdbm' - end -end - -def uname_s - require 'rbconfig' - case Config::CONFIG['host_os'] - when 'cygwin' - require 'Win32API' - uname = Win32API.new 'cygwin1', 'uname', 'P', 'I' - utsname = ' ' * 100 - raise 'cannot get system name' if uname.call(utsname) == -1 - - utsname.unpack('A20' * 5)[0] - else - Config::CONFIG['host_os'] - end -end - -SYSTEM = uname_s - -class TestSDBM < RUNIT::TestCase - def setup - @path = "tmptest_sdbm_" - assert_instance_of(SDBM, @sdbm = SDBM.new(@path)) - end - def teardown - assert_nil(@sdbm.close) - GC.start - File.delete *Dir.glob("tmptest_sdbm*").to_a - p Dir.glob("tmptest_sdbm*") if $DEBUG - end - - def check_size(expect, sdbm=@sdbm) - assert_equals(expect, sdbm.size) - n = 0 - sdbm.each { n+=1 } - assert_equals(expect, n) - if expect == 0 - assert_equals(true, sdbm.empty?) - else - assert_equals(false, sdbm.empty?) - end - end - - def test_version - STDERR.print SDBM::VERSION - end - - def test_s_new_has_no_block - # SDBM.new ignore the block - foo = true - assert_instance_of(SDBM, sdbm = SDBM.new("tmptest_sdbm") { foo = false }) - assert_equals(foo, true) - assert_nil(sdbm.close) - end - def test_s_open_no_create - assert_nil(sdbm = SDBM.open("tmptest_sdbm", nil)) - ensure - sdbm.close if sdbm - end - def test_s_open_with_block - assert_equals(SDBM.open("tmptest_sdbm") { :foo }, :foo) - end -=begin - # Is it guaranteed on many OS? - def test_s_open_lock_one_process - # locking on one process - assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644)) - assert_exception(Errno::EWOULDBLOCK) { - begin - SDBM.open("tmptest_sdbm", 0644) - rescue Errno::EAGAIN - raise Errno::EWOULDBLOCK - end - } - end -=end - - def test_s_open_nolock - # sdbm 1.8.0 specific - if not defined? SDBM::NOLOCK - return - end - - fork() { - assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644, - SDBM::NOLOCK)) - sleep 2 - } - sleep 1 - begin - sdbm2 = nil - assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { - assert_instance_of(SDBM, sdbm2 = SDBM.open("tmptest_sdbm", 0644)) - } - ensure - Process.wait - sdbm2.close if sdbm2 - end - - p Dir.glob("tmptest_sdbm*") if $DEBUG - - fork() { - assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644)) - sleep 2 - } - begin - sleep 1 - sdbm2 = nil - assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { - # this test is failed on Cygwin98 (???) - assert_instance_of(SDBM, sdbm2 = SDBM.open("tmptest_sdbm", 0644, - SDBM::NOLOCK)) - } - ensure - Process.wait - sdbm2.close if sdbm2 - end - end - - def test_s_open_error - assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0)) - assert_exception(Errno::EACCES) { - SDBM.open("tmptest_sdbm", 0) - } - sdbm.close - end - - def test_close - assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm")) - assert_nil(sdbm.close) - - # closed SDBM file - assert_exception(SDBMError) { sdbm.close } - end - - def test_aref - assert_equals('bar', @sdbm['foo'] = 'bar') - assert_equals('bar', @sdbm['foo']) - - assert_nil(@sdbm['bar']) - end - - def test_fetch - assert_equals('bar', @sdbm['foo']='bar') - assert_equals('bar', @sdbm.fetch('foo')) - - # key not found - assert_exception(IndexError) { - @sdbm.fetch('bar') - } - - # test for `ifnone' arg - assert_equals('baz', @sdbm.fetch('bar', 'baz')) - - # test for `ifnone' block - assert_equals('foobar', @sdbm.fetch('bar') {|key| 'foo' + key }) - end - - def test_aset - num = 0 - 2.times {|i| - assert_equals('foo', @sdbm['foo'] = 'foo') - assert_equals('foo', @sdbm['foo']) - assert_equals('bar', @sdbm['foo'] = 'bar') - assert_equals('bar', @sdbm['foo']) - - num += 1 if i == 0 - assert_equals(num, @sdbm.size) - - # assign nil - assert_equals('', @sdbm['bar'] = '') - assert_equals('', @sdbm['bar']) - - num += 1 if i == 0 - assert_equals(num, @sdbm.size) - - # empty string - assert_equals('', @sdbm[''] = '') - assert_equals('', @sdbm['']) - - num += 1 if i == 0 - assert_equals(num, @sdbm.size) - - # Fixnum - assert_equals('200', @sdbm['100'] = '200') - assert_equals('200', @sdbm['100']) - - num += 1 if i == 0 - assert_equals(num, @sdbm.size) - - # Big key and value - assert_equals('y' * 100, @sdbm['x' * 100] = 'y' * 100) - assert_equals('y' * 100, @sdbm['x' * 100]) - - num += 1 if i == 0 - assert_equals(num, @sdbm.size) - } - end - - def test_index - assert_equals('bar', @sdbm['foo'] = 'bar') - assert_equals('foo', @sdbm.index('bar')) - assert_nil(@sdbm['bar']) - end - - def test_indexes - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - assert_equals(values.reverse, @sdbm.indexes(*keys.reverse)) - end - - def test_select - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - assert_equals(values.reverse, @sdbm.select(*keys.reverse)) - end - - def test_select_with_block - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - ret = @sdbm.select {|k,v| - assert_equals(k.upcase, v) - k != "bar" - } - assert_equals([['baz', 'BAZ'], ['foo', 'FOO']], - ret.sort) - end - - def test_length - num = 10 - assert_equals(0, @sdbm.size) - num.times {|i| - i = i.to_s - @sdbm[i] = i - } - assert_equals(num, @sdbm.size) - - @sdbm.shift - - assert_equals(num - 1, @sdbm.size) - end - - def test_empty? - assert_equals(true, @sdbm.empty?) - @sdbm['foo'] = 'FOO' - assert_equals(false, @sdbm.empty?) - end - - def test_each_pair - n = 0 - @sdbm.each_pair { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - - n = 0 - ret = @sdbm.each_pair {|key, val| - assert_not_nil(i = keys.index(key)) - assert_equals(val, values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@sdbm, ret) - end - - def test_each_value - n = 0 - @sdbm.each_value { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - - n = 0 - ret = @sdbm.each_value {|val| - assert_not_nil(key = @sdbm.index(val)) - assert_not_nil(i = keys.index(key)) - assert_equals(val, values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@sdbm, ret) - end - - def test_each_key - n = 0 - @sdbm.each_key { n += 1 } - assert_equals(0, n) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - - n = 0 - ret = @sdbm.each_key {|key| - assert_not_nil(i = keys.index(key)) - assert_equals(@sdbm[key], values[i]) - - n += 1 - } - assert_equals(keys.size, n) - assert_equals(@sdbm, ret) - end - - def test_keys - assert_equals([], @sdbm.keys) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - - assert_equals(keys.sort, @sdbm.keys.sort) - assert_equals(values.sort, @sdbm.values.sort) - end - - def test_values - test_keys - end - - def test_shift - assert_nil(@sdbm.shift) - assert_equals(0, @sdbm.size) - - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - - ret_keys = [] - ret_values = [] - while ret = @sdbm.shift - ret_keys.push ret[0] - ret_values.push ret[1] - - assert_equals(keys.size - ret_keys.size, @sdbm.size) - end - - assert_equals(keys.sort, ret_keys.sort) - assert_equals(values.sort, ret_values.sort) - end - - def test_delete - keys = %w(foo bar baz) - values = %w(FOO BAR BAZ) - key = keys[1] - - assert_nil(@sdbm.delete(key)) - assert_equals(0, @sdbm.size) - - @sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values - - assert_equals('BAR', @sdbm.delete(key)) - assert_nil(@sdbm[key]) - assert_equals(2, @sdbm.size) - - assert_nil(@sdbm.delete(key)) - end - def test_delete_with_block - key = 'no called block' - @sdbm[key] = 'foo' - assert_equals('foo', @sdbm.delete(key) {|k| k.replace 'called block'}) - assert_equals('no called block', key) - assert_equals(0, @sdbm.size) - - key = 'no called block' - assert_equals(:blockval, - @sdbm.delete(key) {|k| k.replace 'called block'; :blockval}) - assert_equals('called block', key) - assert_equals(0, @sdbm.size) - end - - def test_delete_if - v = "0" - 100.times {@sdbm[v] = v; v = v.next} - - ret = @sdbm.delete_if {|key, val| key.to_i < 50} - assert_equals(@sdbm, ret) - check_size(50, @sdbm) - - ret = @sdbm.delete_if {|key, val| key.to_i >= 50} - assert_equals(@sdbm, ret) - check_size(0, @sdbm) - - # break - v = "0" - 100.times {@sdbm[v] = v; v = v.next} - check_size(100, @sdbm) - n = 0; - @sdbm.delete_if {|key, val| - break if n > 50 - n+=1 - true - } - assert_equals(51, n) - check_size(49, @sdbm) - - @sdbm.clear - - # raise - v = "0" - 100.times {@sdbm[v] = v; v = v.next} - check_size(100, @sdbm) - n = 0; - begin - @sdbm.delete_if {|key, val| - raise "runtime error" if n > 50 - n+=1 - true - } - rescue - end - assert_equals(51, n) - check_size(49, @sdbm) - end - - def test_reject - v = "0" - 100.times {@sdbm[v] = v; v = v.next} - - hash = @sdbm.reject {|key, val| key.to_i < 50} - assert_instance_of(Hash, hash) - assert_equals(100, @sdbm.size) - - assert_equals(50, hash.size) - hash.each_pair {|key,val| - assert_equals(false, key.to_i < 50) - assert_equals(key, val) - } - - hash = @sdbm.reject {|key, val| key.to_i < 100} - assert_instance_of(Hash, hash) - assert_equals(true, hash.empty?) - end - - def test_clear - v = "1" - 100.times {v = v.next; @sdbm[v] = v} - - assert_equals(@sdbm, @sdbm.clear) - - # validate SDBM#size - i = 0 - @sdbm.each { i += 1 } - assert_equals(@sdbm.size, i) - assert_equals(0, i) - end - - def test_invert - v = "0" - 100.times {@sdbm[v] = v; v = v.next} - - hash = @sdbm.invert - assert_instance_of(Hash, hash) - assert_equals(100, hash.size) - hash.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_update - hash = {} - v = "0" - 100.times {v = v.next; hash[v] = v} - - @sdbm["101"] = "101" - @sdbm.update hash - assert_equals(101, @sdbm.size) - @sdbm.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_replace - hash = {} - v = "0" - 100.times {v = v.next; hash[v] = v} - - @sdbm["101"] = "101" - @sdbm.replace hash - assert_equals(100, @sdbm.size) - @sdbm.each_pair {|key, val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_haskey? - assert_equals('bar', @sdbm['foo']='bar') - assert_equals(true, @sdbm.has_key?('foo')) - assert_equals(false, @sdbm.has_key?('bar')) - end - - def test_has_value? - assert_equals('bar', @sdbm['foo']='bar') - assert_equals(true, @sdbm.has_value?('bar')) - assert_equals(false, @sdbm.has_value?('foo')) - end - - def test_to_a - v = "0" - 100.times {v = v.next; @sdbm[v] = v} - - ary = @sdbm.to_a - assert_instance_of(Array, ary) - assert_equals(100, ary.size) - ary.each {|key,val| - assert_equals(key.to_i, val.to_i) - } - end - - def test_to_hash - v = "0" - 100.times {v = v.next; @sdbm[v] = v} - - hash = @sdbm.to_hash - assert_instance_of(Hash, hash) - assert_equals(100, hash.size) - hash.each {|key,val| - assert_equals(key.to_i, val.to_i) - } - end -end - -if $0 == __FILE__ - if ARGV.size == 0 - suite = RUNIT::TestSuite.new - suite.add_test(TestSDBM.suite) - else - suite = RUNIT::TestSuite.new - ARGV.each do |testmethod| - suite.add_test(TestSDBM.new(testmethod)) - end - end - - RUNIT::CUI::TestRunner.run(suite) -end diff --git a/ext/socket/.cvsignore b/ext/socket/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/socket/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/socket/MANIFEST b/ext/socket/MANIFEST deleted file mode 100644 index 616d459d92..0000000000 --- a/ext/socket/MANIFEST +++ /dev/null @@ -1,8 +0,0 @@ -MANIFEST -addrinfo.h -depend -extconf.rb -getaddrinfo.c -getnameinfo.c -sockport.h -socket.c diff --git a/ext/socket/addrinfo.h b/ext/socket/addrinfo.h deleted file mode 100644 index bd3de72e10..0000000000 --- a/ext/socket/addrinfo.h +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#ifndef ADDR_INFO_H -#define ADDR_INFO_H -#ifndef HAVE_GETADDRINFO - -/* special compatibility hack */ -#undef EAI_ADDRFAMILY -#undef EAI_AGAIN -#undef EAI_BADFLAGS -#undef EAI_FAIL -#undef EAI_FAMILY -#undef EAI_MEMORY -#undef EAI_NODATA -#undef EAI_NONAME -#undef EAI_SERVICE -#undef EAI_SOCKTYPE -#undef EAI_SYSTEM -#undef EAI_BADHINTS -#undef EAI_PROTOCOL -#undef EAI_MAX - -#undef AI_PASSIVE -#undef AI_CANONNAME -#undef AI_NUMERICHOST -#undef AI_ALL -#undef AI_ADDRCONFIG -#undef AI_V4MAPPED -#undef AI_DEFAULT - -#undef NI_NOFQDN -#undef NI_NUMERICHOST -#undef NI_NAMEREQD -#undef NI_NUMERICSERV -#undef NI_DGRAM - -#define addrinfo addrinfo__compat -#define getaddrinfo getaddrinfo__compat -#define getnameinfo getnameinfo__compat -#define freehostent freehostent__compat -#define freeaddrinfo freeaddrinfo__compat - -#ifndef __P -# ifdef HAVE_PROTOTYPES -# define __P(args) args -# else -# define __P(args) () -# endif -#endif - -/* special compatibility hack -- end*/ - - -/* - * Error return codes from getaddrinfo() - */ -#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ -#define EAI_AGAIN 2 /* temporary failure in name resolution */ -#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ -#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ -#define EAI_FAMILY 5 /* ai_family not supported */ -#define EAI_MEMORY 6 /* memory allocation failure */ -#define EAI_NODATA 7 /* no address associated with hostname */ -#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ -#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ -#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ -#define EAI_SYSTEM 11 /* system error returned in errno */ -#define EAI_BADHINTS 12 -#define EAI_PROTOCOL 13 -#define EAI_MAX 14 - -/* - * Flag values for getaddrinfo() - */ -#define AI_PASSIVE 0x00000001 /* get address to use bind() */ -#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ -#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ -/* valid flags for addrinfo */ -#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) - -#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ -#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ -#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ -#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ -/* special recommended flags for getipnodebyname */ -#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) - -/* - * Constants for getnameinfo() - */ -#define NI_MAXHOST 1025 -#define NI_MAXSERV 32 - -/* - * Flag values for getnameinfo() - */ -#define NI_NOFQDN 0x00000001 -#define NI_NUMERICHOST 0x00000002 -#define NI_NAMEREQD 0x00000004 -#define NI_NUMERICSERV 0x00000008 -#define NI_DGRAM 0x00000010 - -struct addrinfo { - int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ - int ai_family; /* PF_xxx */ - int ai_socktype; /* SOCK_xxx */ - int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ - size_t ai_addrlen; /* length of ai_addr */ - char *ai_canonname; /* canonical name for hostname */ - struct sockaddr *ai_addr; /* binary address */ - struct addrinfo *ai_next; /* next structure in linked list */ -}; - -extern int getaddrinfo __P(( - const char *hostname, const char *servname, - const struct addrinfo *hints, - struct addrinfo **res)); - -extern int getnameinfo __P(( - const struct sockaddr *sa, - size_t salen, - char *host, - size_t hostlen, - char *serv, - size_t servlen, - int flags)); - -extern void freehostent __P((struct hostent *)); -extern void freeaddrent __P((struct addrinfo *)); -#if defined __UCLIBC__ -const -#endif -extern char *gai_strerror __P((int)); - -/* In case there is no definition of offsetof() provided - though any proper -Standard C system should have one. */ - -#ifndef offsetof -#define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field)) -#endif - -#endif -#endif diff --git a/ext/socket/depend b/ext/socket/depend deleted file mode 100644 index cca6d4e62a..0000000000 --- a/ext/socket/depend +++ /dev/null @@ -1,3 +0,0 @@ -socket.o : socket.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/rubyio.h $(hdrdir)/rubysig.h sockport.h -getnameinfo.o: getnameinfo.c $(topdir)/config.h addrinfo.h sockport.h -getaddrinfo.o: getaddrinfo.c $(topdir)/config.h addrinfo.h sockport.h diff --git a/ext/socket/extconf.rb b/ext/socket/extconf.rb deleted file mode 100644 index 46557682a7..0000000000 --- a/ext/socket/extconf.rb +++ /dev/null @@ -1,386 +0,0 @@ -require 'mkmf' - -$CPPFLAGS += " -Dss_family=__ss_family -Dss_len=__ss_len" - -def have_struct_member(type, member, header=nil) - #printf "checking for %s.%s... ", type, member - #STDOUT.flush - - libs = $libs - src = - if /mswin32|mingw/ =~ RUBY_PLATFORM - r = <<"SRC" -#include -#include -SRC - else - "" - end - unless header.nil? - header = [header] unless header.kind_of? Array - header.each {|h| - src << <<"SRC" -#include <#{h}> -SRC - } - end - src << <<"SRC" -int main() { return 0; } -int s = (char *)&((#{type}*)0)->#{member} - (char *)0; -SRC - r = try_link(src, libs) # xxx try_compile is not available. - unless r - #print "no\n" - return false - end - $defs.push(format("-DHAVE_ST_%s", member.upcase)) - #print "yes\n" - return true -end - -case RUBY_PLATFORM -when /mswin32|mingw/ - test_func = "WSACleanup" - have_library("wsock32", "WSACleanup") - have_func("closesocket") -when /cygwin/ -# $LDFLAGS << " -L/usr/lib" if File.directory?("/usr/lib") -# $CFLAGS << " -I/usr/include" - test_func = "socket" -# have_library("bind", "gethostbyaddr") -when /beos/ - test_func = "socket" - have_library("net", "socket") - have_func("closesocket") -when /i386-os2_emx/ - test_func = "socket" - have_library("socket", "socket") -else - test_func = "socket" - have_library("nsl", "t_open") - have_library("socket", "socket") -end - -$ipv6 = false -if enable_config("ipv6", false) - if try_link(< -#include -main() -{ - socket(AF_INET6, SOCK_STREAM, 0); -} -EOF - $CFLAGS+=" -DENABLE_IPV6" - $ipv6 = true - end -end - -$ipv6type = nil -$ipv6lib = nil -$ipv6libdir = nil -$ipv6trylibc = nil -if $ipv6 - if egrep_cpp("yes", < -#ifdef IPV6_INRIA_VERSION -yes -#endif -EOF - $ipv6type = "inria" - $CFLAGS="-DINET6 "+$CFLAGS - elsif egrep_cpp("yes", < -#ifdef __KAME__ -yes -#endif -EOF - $ipv6type = "kame" - $ipv6lib="inet6" - $ipv6libdir="/usr/local/v6/lib" - $ipv6trylibc=true - $CFLAGS="-DINET6 "+$CFLAGS - elsif File.directory? "/usr/inet6" - $ipv6type = "linux" - $ipv6lib="inet6" - $ipv6libdir="/usr/inet6/lib" - $CFLAGS="-DINET6 -I/usr/inet6/include "+$CFLAGS - elsif egrep_cpp("yes", < -#ifdef _TOSHIBA_INET6 -yes -#endif -EOF - $ipv6type = "toshiba" - $ipv6lib="inet6" - $ipv6libdir="/usr/local/v6/lib" - $CFLAGS="-DINET6 "+$CFLAGS - elsif egrep_cpp("yes", < -#ifdef __V6D__ -yes -#endif -EOF - $ipv6type = "v6d" - $ipv6lib="v6" - $ipv6libdir="/usr/local/v6/lib" - $CFLAGS="-DINET6 -I/usr/local/v6/include "+$CFLAGS - elsif egrep_cpp("yes", < -#ifdef _ZETA_MINAMI_INET6 -yes -#endif -EOF - $ipv6type = "zeta" - $ipv6lib="inet6" - $ipv6libdir="/usr/local/v6/lib" - $CFLAGS="-DINET6 "+$CFLAGS - else - $ipv6lib=with_config("ipv6-lib", nil) - $ipv6libdir=with_config("ipv6-libdir", nil) - $CFLAGS="-DINET6 "+$CFLAGS - end - - if $ipv6lib - if File.directory? $ipv6libdir and File.exist? "#{$ipv6libdir}/lib#{$ipv6lib}.a" - $LOCAL_LIBS = " -L#$ipv6libdir -l#$ipv6lib" - elsif !$ipv6trylibc - print < -#include -#include -#include -#include -int -main() -{ - struct sockaddr_in sin; - - sin.sin_len; - return 0; -} -EOF - $CFLAGS="-DHAVE_SIN_LEN "+$CFLAGS -end - - if try_link(< -#include -#include -#include -int -main() -{ - struct sockaddr_storage ss; - - ss.ss_family; - return 0; -} -EOF - $CFLAGS="-DHAVE_SOCKADDR_STORAGE "+$CFLAGS -end - - if try_link(< -#include -#include -#include -#include -int -main() -{ - struct sockaddr sa; - - sa.sa_len; - return 0; -} -EOF - $CFLAGS="-DHAVE_SA_LEN "+$CFLAGS -end - -have_header("netinet/tcp.h") if not /cygwin/ === RUBY_PLATFORM # for cygwin 1.1.5 -have_header("netinet/udp.h") - -have_struct_member('struct msghdr', 'msg_control', header=['sys/types.h', 'sys/socket.h']) -have_struct_member('struct msghdr', 'msg_accrights', header=['sys/types.h', 'sys/socket.h']) - -$getaddr_info_ok = false -if not enable_config("wide-getaddrinfo", false) and try_run(< -#include -#include -#include -#include - -#ifndef AF_LOCAL -#define AF_LOCAL AF_UNIX -#endif - -main() -{ - int passive, gaierr, inet4 = 0, inet6 = 0; - struct addrinfo hints, *ai, *aitop; - char straddr[INET6_ADDRSTRLEN], strport[16]; - - for (passive = 0; passive <= 1; passive++) { - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_flags = passive ? AI_PASSIVE : 0; - hints.ai_socktype = SOCK_STREAM; - if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) { - (void)gai_strerror(gaierr); - goto bad; - } - for (ai = aitop; ai; ai = ai->ai_next) { - if (ai->ai_family == AF_LOCAL) continue; - if (ai->ai_addr == NULL || - ai->ai_addrlen == 0 || - getnameinfo(ai->ai_addr, ai->ai_addrlen, - straddr, sizeof(straddr), strport, sizeof(strport), - NI_NUMERICHOST|NI_NUMERICSERV) != 0) { - goto bad; - } - if (strcmp(strport, "54321") != 0) { - goto bad; - } - switch (ai->ai_family) { - case AF_INET: - if (passive) { - if (strcmp(straddr, "0.0.0.0") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "127.0.0.1") != 0) { - goto bad; - } - } - inet4++; - break; - case AF_INET6: - if (passive) { - if (strcmp(straddr, "::") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "::1") != 0) { - goto bad; - } - } - inet6++; - break; - case AF_UNSPEC: - goto bad; - break; - default: - /* another family support? */ - break; - } - } - } - - if (!(inet4 == 0 || inet4 == 2)) - goto bad; - if (!(inet6 == 0 || inet6 == 2)) - goto bad; - - if (aitop) - freeaddrinfo(aitop); - exit(0); - - bad: - if (aitop) - freeaddrinfo(aitop); - exit(1); -} -EOF - $getaddr_info_ok = true -end -if $ipv6 and not $getaddr_info_ok - print < -#include -#include -#include -#include -int -main() -{ - socklen_t len; - return 0; -} -EOF - $CFLAGS="-Dsocklen_t=int "+$CFLAGS -end - -have_header("sys/un.h") -have_header("sys/uio.h") - -if have_func(test_func) - have_func("hsterror") - unless have_func("gethostname") - have_func("uname") - end - if ENV["SOCKS_SERVER"] or enable_config("socks", false) - if have_library("socks5", "SOCKSinit") - $CFLAGS+=" -DSOCKS5 -DSOCKS" - elsif have_library("socks", "Rconnect") - $CFLAGS+=" -DSOCKS" - end - end - create_makefile("socket") -end diff --git a/ext/socket/getaddrinfo.c b/ext/socket/getaddrinfo.c deleted file mode 100644 index fa060ad171..0000000000 --- a/ext/socket/getaddrinfo.c +++ /dev/null @@ -1,686 +0,0 @@ -/* - * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -/* - * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator. - * - * Issues to be discussed: - * - Thread safe-ness must be checked. - * - Return values. There are nonstandard return values defined and used - * in the source code. This is because RFC2133 is silent about which error - * code must be returned for which situation. - * - PF_UNSPEC case would be handled in getipnodebyname() with the AI_ALL flag. - */ - -#include "config.h" -#include -#ifndef NT -#include -#if defined(__BEOS__) -# include -#else -# include -#endif -#include -#if defined(HAVE_ARPA_INET_H) -#include -#endif -#if defined(HAVE_ARPA_NAMESER_H) -#include -#endif -#include -#if defined(HAVE_RESOLV_H) -#include -#endif -#include -#else -#include -#include -#endif -#include -#include -#include -#include -#include - -#ifdef SOCKS5 -#include -#endif - -#include "addrinfo.h" -#include "sockport.h" - -#if defined(__KAME__) && defined(INET6) -# define FAITH -#endif - -#define SUCCESS 0 -#define ANY 0 -#define YES 1 -#define NO 0 - -#ifdef FAITH -static int translate = NO; -static struct in6_addr faith_prefix = IN6ADDR_ANY_INIT; -#endif - -static const char in_addrany[] = { 0, 0, 0, 0 }; -static const char in6_addrany[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; -static const char in_loopback[] = { 127, 0, 0, 1 }; -static const char in6_loopback[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 -}; - -struct sockinet { - u_char si_len; - u_char si_family; - u_short si_port; -}; - -static struct afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; - const char *a_addrany; - const char *a_loopback; -} afdl [] = { -#ifdef INET6 -#define N_INET6 0 - {PF_INET6, sizeof(struct in6_addr), - sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr), - in6_addrany, in6_loopback}, -#define N_INET 1 -#else -#define N_INET 0 -#endif - {PF_INET, sizeof(struct in_addr), - sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr), - in_addrany, in_loopback}, - {0, 0, 0, 0, NULL, NULL}, -}; - -#ifdef INET6 -#define PTON_MAX 16 -#else -#define PTON_MAX 4 -#endif - -static int get_name __P((const char *, struct afd *, - struct addrinfo **, char *, struct addrinfo *, - int)); -static int get_addr __P((const char *, int, struct addrinfo **, - struct addrinfo *, int)); -static int str_isnumber __P((const char *)); - -static char *ai_errlist[] = { - "success.", - "address family for hostname not supported.", /* EAI_ADDRFAMILY */ - "temporary failure in name resolution.", /* EAI_AGAIN */ - "invalid value for ai_flags.", /* EAI_BADFLAGS */ - "non-recoverable failure in name resolution.", /* EAI_FAIL */ - "ai_family not supported.", /* EAI_FAMILY */ - "memory allocation failure.", /* EAI_MEMORY */ - "no address associated with hostname.", /* EAI_NODATA */ - "hostname nor servname provided, or not known.",/* EAI_NONAME */ - "servname not supported for ai_socktype.", /* EAI_SERVICE */ - "ai_socktype not supported.", /* EAI_SOCKTYPE */ - "system error returned in errno.", /* EAI_SYSTEM */ - "invalid value for hints.", /* EAI_BADHINTS */ - "resolved protocol is unknown.", /* EAI_PROTOCOL */ - "unknown error.", /* EAI_MAX */ -}; - -#define GET_CANONNAME(ai, str) \ -if (pai->ai_flags & AI_CANONNAME) {\ - if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ - strcpy((ai)->ai_canonname, (str));\ - } else {\ - error = EAI_MEMORY;\ - goto free;\ - }\ -} - -#define GET_AI(ai, afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((afd)->a_socklen)))\ - == NULL) {\ - error = EAI_MEMORY;\ - goto free;\ - }\ - memcpy(ai, pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - memset((ai)->ai_addr, 0, (afd)->a_socklen);\ - SET_SA_LEN((ai)->ai_addr, (ai)->ai_addrlen = (afd)->a_socklen);\ - (ai)->ai_addr->sa_family = (ai)->ai_family = (afd)->a_af;\ - ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (afd)->a_off, (addr), (afd)->a_addrlen);\ -} - -#define ERR(err) { error = (err); goto bad; } - -#if defined __UCLIBC__ -const -#endif -char * -gai_strerror(ecode) - int ecode; -{ - if (ecode < 0 || ecode > EAI_MAX) - ecode = EAI_MAX; - return ai_errlist[ecode]; -} - -void -freeaddrinfo(ai) - struct addrinfo *ai; -{ - struct addrinfo *next; - - do { - next = ai->ai_next; - if (ai->ai_canonname) - free(ai->ai_canonname); - /* no need to free(ai->ai_addr) */ - free(ai); - } while ((ai = next) != NULL); -} - -static int -str_isnumber(p) - const char *p; -{ - char *q = (char *)p; - while (*q) { - if (! isdigit(*q)) - return NO; - q++; - } - return YES; -} - -#ifndef HAVE_INET_PTON - -static int -inet_pton(af, hostname, pton) - int af; - const char *hostname; - void *pton; -{ - struct in_addr in; - -#ifdef HAVE_INET_ATON - if (!inet_aton(hostname, &in)) - return 0; -#else - int d1, d2, d3, d4; - char ch; - - if (sscanf(hostname, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && - 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && - 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { - in.s_addr = htonl( - ((long) d1 << 24) | ((long) d2 << 16) | - ((long) d3 << 8) | ((long) d4 << 0)); - } - else { - return 0; - } -#endif - memcpy(pton, &in, sizeof(in)); - return 1; -} -#endif - -int -getaddrinfo(hostname, servname, hints, res) - const char *hostname, *servname; - const struct addrinfo *hints; - struct addrinfo **res; -{ - struct addrinfo sentinel; - struct addrinfo *top = NULL; - struct addrinfo *cur; - int i, error = 0; - char pton[PTON_MAX]; - struct addrinfo ai; - struct addrinfo *pai; - u_short port; - -#ifdef FAITH - static int firsttime = 1; - - if (firsttime) { - /* translator hack */ - { - char *q = getenv("GAI"); - if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) - translate = YES; - } - firsttime = 0; - } -#endif - - /* initialize file static vars */ - sentinel.ai_next = NULL; - cur = &sentinel; - pai = &ai; - pai->ai_flags = 0; - pai->ai_family = PF_UNSPEC; - pai->ai_socktype = ANY; - pai->ai_protocol = ANY; - pai->ai_addrlen = 0; - pai->ai_canonname = NULL; - pai->ai_addr = NULL; - pai->ai_next = NULL; - port = ANY; - - if (hostname == NULL && servname == NULL) - return EAI_NONAME; - if (hints) { - /* error check for hints */ - if (hints->ai_addrlen || hints->ai_canonname || - hints->ai_addr || hints->ai_next) - ERR(EAI_BADHINTS); /* xxx */ - if (hints->ai_flags & ~AI_MASK) - ERR(EAI_BADFLAGS); - switch (hints->ai_family) { - case PF_UNSPEC: - case PF_INET: -#ifdef INET6 - case PF_INET6: -#endif - break; - default: - ERR(EAI_FAMILY); - } - memcpy(pai, hints, sizeof(*pai)); - switch (pai->ai_socktype) { - case ANY: - switch (pai->ai_protocol) { - case ANY: - break; - case IPPROTO_UDP: - pai->ai_socktype = SOCK_DGRAM; - break; - case IPPROTO_TCP: - pai->ai_socktype = SOCK_STREAM; - break; - default: -#if defined(SOCK_RAW) - pai->ai_socktype = SOCK_RAW; -#endif - break; - } - break; -#if defined(SOCK_RAW) - case SOCK_RAW: - break; -#endif - case SOCK_DGRAM: - if (pai->ai_protocol != IPPROTO_UDP && - pai->ai_protocol != ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_UDP; - break; - case SOCK_STREAM: - if (pai->ai_protocol != IPPROTO_TCP && - pai->ai_protocol != ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_TCP; - break; - default: - ERR(EAI_SOCKTYPE); - break; - } - } - - /* - * service port - */ - if (servname) { - if (str_isnumber(servname)) { - if (pai->ai_socktype == ANY) { - /* caller accept *ANY* socktype */ - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } - port = htons((unsigned short)atoi(servname)); - } else { - struct servent *sp; - char *proto; - - proto = NULL; - switch (pai->ai_socktype) { - case ANY: - proto = NULL; - break; - case SOCK_DGRAM: - proto = "udp"; - break; - case SOCK_STREAM: - proto = "tcp"; - break; - default: - fprintf(stderr, "panic!\n"); - break; - } - if ((sp = getservbyname(servname, proto)) == NULL) - ERR(EAI_SERVICE); - port = sp->s_port; - if (pai->ai_socktype == ANY) - if (strcmp(sp->s_proto, "udp") == 0) { - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } else if (strcmp(sp->s_proto, "tcp") == 0) { - pai->ai_socktype = SOCK_STREAM; - pai->ai_protocol = IPPROTO_TCP; - } else - ERR(EAI_PROTOCOL); /*xxx*/ - } - } - - /* - * hostname == NULL. - * passive socket -> anyaddr (0.0.0.0 or ::) - * non-passive socket -> localhost (127.0.0.1 or ::1) - */ - if (hostname == NULL) { - struct afd *afd; - int s; - - for (afd = &afdl[0]; afd->a_af; afd++) { - if (!(pai->ai_family == PF_UNSPEC - || pai->ai_family == afd->a_af)) { - continue; - } - - /* - * filter out AFs that are not supported by the kernel - * XXX errno? - */ - s = socket(afd->a_af, SOCK_DGRAM, 0); - if (s < 0) - continue; -#if defined(HAVE_CLOSESOCKET) - closesocket(s); -#else - close(s); -#endif - - if (pai->ai_flags & AI_PASSIVE) { - GET_AI(cur->ai_next, afd, afd->a_addrany, port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "anyaddr"); - */ - } else { - GET_AI(cur->ai_next, afd, afd->a_loopback, - port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "localhost"); - */ - } - cur = cur->ai_next; - } - top = sentinel.ai_next; - if (top) - goto good; - else - ERR(EAI_FAMILY); - } - - /* hostname as numeric name */ - for (i = 0; afdl[i].a_af; i++) { - if (inet_pton(afdl[i].a_af, hostname, pton)) { - u_long v4a; -#ifdef INET6 - u_char pfx; -#endif - - switch (afdl[i].a_af) { - case AF_INET: - v4a = ((struct in_addr *)pton)->s_addr; - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - pai->ai_flags &= ~AI_CANONNAME; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - pai->ai_flags &= ~AI_CANONNAME; - break; -#ifdef INET6 - case AF_INET6: - pfx = ((struct in6_addr *)pton)->s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - pai->ai_flags &= ~AI_CANONNAME; - break; -#endif - } - - if (pai->ai_family == afdl[i].a_af || - pai->ai_family == PF_UNSPEC) { - if (! (pai->ai_flags & AI_CANONNAME)) { - GET_AI(top, &afdl[i], pton, port); - goto good; - } - /* - * if AI_CANONNAME and if reverse lookup - * fail, return ai anyway to pacify - * calling application. - * - * XXX getaddrinfo() is a name->address - * translation function, and it looks strange - * that we do addr->name translation here. - */ - get_name(pton, &afdl[i], &top, pton, pai, port); - goto good; - } else - ERR(EAI_FAMILY); /*xxx*/ - } - } - - if (pai->ai_flags & AI_NUMERICHOST) - ERR(EAI_NONAME); - - /* hostname as alphabetical name */ - error = get_addr(hostname, pai->ai_family, &top, pai, port); - if (error == 0) { - if (top) { - good: - *res = top; - return SUCCESS; - } else - error = EAI_FAIL; - } - free: - if (top) - freeaddrinfo(top); - bad: - *res = NULL; - return error; -} - -static int -get_name(addr, afd, res, numaddr, pai, port0) - const char *addr; - struct afd *afd; - struct addrinfo **res; - char *numaddr; - struct addrinfo *pai; - int port0; -{ - u_short port = port0 & 0xffff; - struct hostent *hp; - struct addrinfo *cur; - int error = 0; -#ifdef INET6 - int h_error; -#endif - -#ifdef INET6 - hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); -#else - hp = gethostbyaddr(addr, afd->a_addrlen, AF_INET); -#endif - if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { - GET_AI(cur, afd, hp->h_addr_list[0], port); - GET_CANONNAME(cur, hp->h_name); - } else - GET_AI(cur, afd, numaddr, port); - -#ifdef INET6 - if (hp) - freehostent(hp); -#endif - *res = cur; - return SUCCESS; - free: - if (cur) - freeaddrinfo(cur); -#ifdef INET6 - if (hp) - freehostent(hp); -#endif - /* bad: */ - *res = NULL; - return error; -} - -static int -get_addr(hostname, af, res, pai, port0) - const char *hostname; - int af; - struct addrinfo **res; - struct addrinfo *pai; - int port0; -{ - u_short port = port0 & 0xffff; - struct addrinfo sentinel; - struct hostent *hp; - struct addrinfo *top, *cur; - struct afd *afd; - int i, error = 0, h_error; - char *ap; - - top = NULL; - sentinel.ai_next = NULL; - cur = &sentinel; -#ifdef INET6 - if (af == AF_UNSPEC) { - hp = getipnodebyname(hostname, AF_INET6, - AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); - } else - hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); -#else - hp = gethostbyname(hostname); - h_error = h_errno; -#endif - if (hp == NULL) { - switch (h_error) { - case HOST_NOT_FOUND: - case NO_DATA: - error = EAI_NODATA; - break; - case TRY_AGAIN: - error = EAI_AGAIN; - break; - case NO_RECOVERY: - default: - error = EAI_FAIL; - break; - } - goto bad; - } - - if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || - (hp->h_addr_list[0] == NULL)) - ERR(EAI_FAIL); - - for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { - switch (af) { -#ifdef INET6 - case AF_INET6: - afd = &afdl[N_INET6]; - break; -#endif -#ifndef INET6 - default: /* AF_UNSPEC */ -#endif - case AF_INET: - afd = &afdl[N_INET]; - break; -#ifdef INET6 - default: /* AF_UNSPEC */ - if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { - ap += sizeof(struct in6_addr) - - sizeof(struct in_addr); - afd = &afdl[N_INET]; - } else - afd = &afdl[N_INET6]; - break; -#endif - } -#ifdef FAITH - if (translate && afd->a_af == AF_INET) { - struct in6_addr *in6; - - GET_AI(cur->ai_next, &afdl[N_INET6], ap, port); - in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; - memcpy(&in6->s6_addr32[0], &faith_prefix, - sizeof(struct in6_addr) - sizeof(struct in_addr)); - memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); - } else -#endif /* FAITH */ - GET_AI(cur->ai_next, afd, ap, port); - if (cur == &sentinel) { - top = cur->ai_next; - GET_CANONNAME(top, hp->h_name); - } - cur = cur->ai_next; - } -#ifdef INET6 - freehostent(hp); -#endif - *res = top; - return SUCCESS; - free: - if (top) - freeaddrinfo(top); -#ifdef INET6 - if (hp) - freehostent(hp); -#endif - bad: - *res = NULL; - return error; -} diff --git a/ext/socket/getnameinfo.c b/ext/socket/getnameinfo.c deleted file mode 100644 index b8a1e310a3..0000000000 --- a/ext/socket/getnameinfo.c +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -/* - * Issues to be discussed: - * - Thread safe-ness must be checked - * - Return values. There seems to be no standard for return value (RFC2133) - * but INRIA implementation returns EAI_xxx defined for getaddrinfo(). - */ - -#include "config.h" -#include -#ifndef NT -#if defined(__BEOS__) -# include -#else -# include -#endif -#include -#if defined(HAVE_ARPA_INET_H) -#include -#endif -#if defined(HAVE_ARPA_NAMESER_H) -#include -#endif -#include -#if defined(HAVE_RESOLV_H) -#include -#endif -#endif -#ifdef NT -#include -#include -#define snprintf _snprintf -#endif - -#include -#include - -#ifdef SOCKS5 -#include -#endif - -#include "addrinfo.h" -#include "sockport.h" - -#define SUCCESS 0 -#define ANY 0 -#define YES 1 -#define NO 0 - -struct sockinet { - u_char si_len; - u_char si_family; - u_short si_port; -}; - -static struct afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; -} afdl [] = { -#ifdef INET6 -#define N_INET6 0 - {PF_INET6, sizeof(struct in6_addr), - sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr)}, -#define N_INET 1 -#else -#define N_INET 0 -#endif - {PF_INET, sizeof(struct in_addr), - sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr)}, - {0, 0, 0, 0}, -}; - -#define ENI_NOSOCKET 0 -#define ENI_NOSERVNAME 1 -#define ENI_NOHOSTNAME 2 -#define ENI_MEMORY 3 -#define ENI_SYSTEM 4 -#define ENI_FAMILY 5 -#define ENI_SALEN 6 - -#ifndef HAVE_INET_NTOP -static const char * -inet_ntop(af, addr, numaddr, numaddr_len) - int af; - const void *addr; - char *numaddr; - size_t numaddr_len; -{ -#ifdef HAVE_INET_NTOA - struct in_addr in; - memcpy(&in.s_addr, addr, sizeof(in.s_addr)); - snprintf(numaddr, numaddr_len, "%s", inet_ntoa(in)); -#else - unsigned long x = ntohl(*(unsigned long*)addr); - snprintf(numaddr, numaddr_len, "%d.%d.%d.%d", - (int) (x>>24) & 0xff, (int) (x>>16) & 0xff, - (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff); -#endif - return numaddr; -} -#endif - -int -getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) - const struct sockaddr *sa; - size_t salen; - char *host; - size_t hostlen; - char *serv; - size_t servlen; - int flags; -{ - struct afd *afd; - struct servent *sp; - struct hostent *hp; - u_short port; - int family, len, i; - char *addr, *p; - u_long v4a; -#ifdef INET6 - u_char pfx; -#endif - int h_error; - char numserv[512]; - char numaddr[512]; - - if (sa == NULL) - return ENI_NOSOCKET; - - len = SA_LEN(sa); - if (len != salen) return ENI_SALEN; - - family = sa->sa_family; - for (i = 0; afdl[i].a_af; i++) - if (afdl[i].a_af == family) { - afd = &afdl[i]; - goto found; - } - return ENI_FAMILY; - - found: - if (len != afd->a_socklen) return ENI_SALEN; - - port = ((struct sockinet *)sa)->si_port; /* network byte order */ - addr = (char *)sa + afd->a_off; - - if (serv == NULL || servlen == 0) { - /* what we should do? */ - } else if (flags & NI_NUMERICSERV) { - snprintf(numserv, sizeof(numserv), "%d", ntohs(port)); - if (strlen(numserv) + 1 > servlen) - return ENI_MEMORY; - strcpy(serv, numserv); - } else { -#if defined(HAVE_GETSERVBYPORT) - sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); - if (sp) { - if (strlen(sp->s_name) + 1 > servlen) - return ENI_MEMORY; - strcpy(serv, sp->s_name); - } else - return ENI_NOSERVNAME; -#else - return ENI_NOSERVNAME; -#endif - } - - switch (sa->sa_family) { - case AF_INET: - v4a = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr); - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - flags |= NI_NUMERICHOST; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0) - flags |= NI_NUMERICHOST; - break; -#ifdef INET6 - case AF_INET6: - pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - flags |= NI_NUMERICHOST; - break; -#endif - } - if (host == NULL || hostlen == 0) { - /* what should we do? */ - } else if (flags & NI_NUMERICHOST) { - if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_SYSTEM; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } else { -#ifdef INET6 - hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); -#else - hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af); - h_error = h_errno; -#endif - - if (hp) { - if (flags & NI_NOFQDN) { - p = strchr(hp->h_name, '.'); - if (p) *p = '\0'; - } - if (strlen(hp->h_name) + 1 > hostlen) { -#ifdef INET6 - freehostent(hp); -#endif - return ENI_MEMORY; - } - strcpy(host, hp->h_name); -#ifdef INET6 - freehostent(hp); -#endif - } else { - if (flags & NI_NAMEREQD) - return ENI_NOHOSTNAME; - if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_NOHOSTNAME; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } - } - return SUCCESS; -} diff --git a/ext/socket/socket.c b/ext/socket/socket.c deleted file mode 100644 index 281a1fe1ea..0000000000 --- a/ext/socket/socket.c +++ /dev/null @@ -1,2837 +0,0 @@ -/************************************************ - - socket.c - - - $Author$ - $Date$ - created at: Thu Mar 31 12:21:29 JST 1994 - - Copyright (C) 1993-2001 Yukihiro Matsumoto - -************************************************/ - -#include "ruby.h" -#include "rubyio.h" -#include "rubysig.h" -#include -#include - -#ifdef HAVE_UNISTD_H -#include -#endif - -#ifdef HAVE_SYS_UIO_H -#include -#endif - -#ifndef NT -#if defined(__BEOS__) -# include -#else -# include -#endif -#include -#ifdef HAVE_NETINET_TCP_H -# include -#endif -#ifdef HAVE_NETINET_UDP_H -# include -#endif -#include -#endif -#include -#ifdef HAVE_SYS_UN_H -#include -#endif - -#if defined(HAVE_FCNTL) -#ifdef HAVE_SYS_SELECT_H -#include -#endif -#include -#include -#include -#endif -#ifndef EWOULDBLOCK -#define EWOULDBLOCK EAGAIN -#endif -#ifndef HAVE_GETADDRINFO -# include "addrinfo.h" -#endif -#include "sockport.h" - -static int do_not_reverse_lookup = 0; - -VALUE rb_cBasicSocket; -VALUE rb_cIPSocket; -VALUE rb_cTCPSocket; -VALUE rb_cTCPServer; -VALUE rb_cUDPSocket; -#ifdef AF_UNIX -VALUE rb_cUNIXSocket; -VALUE rb_cUNIXServer; -#endif -VALUE rb_cSocket; - -static VALUE rb_eSocket; - -#ifdef SOCKS -VALUE rb_cSOCKSSocket; -#ifdef SOCKS5 -#include -#else -void SOCKSinit(); -int Rconnect(); -#endif -#endif - -#define INET_CLIENT 0 -#define INET_SERVER 1 -#define INET_SOCKS 2 - -#ifndef HAVE_SOCKADDR_STORAGE -/* - * RFC 2553: protocol-independent placeholder for socket addresses - */ -#define _SS_MAXSIZE 128 -#define _SS_ALIGNSIZE (sizeof(double)) -#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(unsigned char) * 2) -#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(unsigned char) * 2 - \ - _SS_PAD1SIZE - _SS_ALIGNSIZE) - -struct sockaddr_storage { -#ifdef HAVE_SA_LEN - unsigned char ss_len; /* address length */ - unsigned char ss_family; /* address family */ -#else - unsigned short ss_family; -#endif - char __ss_pad1[_SS_PAD1SIZE]; - double __ss_align; /* force desired structure storage alignment */ - char __ss_pad2[_SS_PAD2SIZE]; -}; -#endif - -#if defined(INET6) && (defined(LOOKUP_ORDER_HACK_INET) || defined(LOOKUP_ORDER_HACK_INET6)) -#define LOOKUP_ORDERS 3 -static int lookup_order_table[LOOKUP_ORDERS] = { -#if defined(LOOKUP_ORDER_HACK_INET) - PF_INET, PF_INET6, PF_UNSPEC, -#elif defined(LOOKUP_ORDER_HACK_INET6) - PF_INET6, PF_INET, PF_UNSPEC, -#else - /* should not happen */ -#endif -}; - -static int -rb_getaddrinfo(nodename, servname, hints, res) - char *nodename; - char *servname; - struct addrinfo *hints; - struct addrinfo **res; -{ - struct addrinfo tmp_hints; - int i, af, error; - - if (hints->ai_family != PF_UNSPEC) { - return getaddrinfo(nodename, servname, hints, res); - } - - for (i = 0; i < LOOKUP_ORDERS; i++) { - af = lookup_order_table[i]; - MEMCPY(&tmp_hints, hints, struct addrinfo, 1); - tmp_hints.ai_family = af; - error = getaddrinfo(nodename, servname, &tmp_hints, res); - if (error) { - if (tmp_hints.ai_family == PF_UNSPEC) { - break; - } - } - else { - break; - } - } - - return error; -} -#define getaddrinfo(node,serv,hints,res) rb_getaddrinfo((node),(serv),(hints),(res)) -#endif - -#ifdef NT -static void sock_finalize _((OpenFile *fptr)); - -static void -sock_finalize(fptr) - OpenFile *fptr; -{ - SOCKET s; - - if (!fptr->f) return; - s = get_osfhandle(fileno(fptr->f)); - myfdclose(fptr->f); - if (fptr->f2) myfdclose(fptr->f2); - closesocket(s); -} -#endif - -static VALUE -init_sock(sock, fd) - VALUE sock; - int fd; -{ - OpenFile *fp; - - MakeOpenFile(sock, fp); - fp->f = rb_fdopen(fd, "r"); -#ifdef NT - fp->finalize = sock_finalize; -#else -#endif - fp->f2 = rb_fdopen(fd, "w"); - fp->mode = FMODE_READWRITE; - rb_io_synchronized(fp); - - return sock; -} - -static VALUE -bsock_s_for_fd(klass, fd) - VALUE klass, fd; -{ - return init_sock(rb_obj_alloc(klass), NUM2INT(fd)); -} - -static VALUE -bsock_shutdown(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE howto; - int how; - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't shutdown socket"); - } - rb_scan_args(argc, argv, "01", &howto); - if (howto == Qnil) - how = 2; - else { - how = NUM2INT(howto); - if (how < 0 || 2 < how) { - rb_raise(rb_eArgError, "`how' should be either 0, 1, 2"); - } - } - GetOpenFile(sock, fptr); - if (shutdown(fileno(fptr->f), how) == -1) - rb_sys_fail(0); - - return INT2FIX(0); -} - -static VALUE -bsock_close_read(sock) - VALUE sock; -{ - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't close socket"); - } - GetOpenFile(sock, fptr); - shutdown(fileno(fptr->f), 0); - if (!(fptr->mode & FMODE_WRITABLE)) { - return rb_io_close(sock); - } - fptr->mode &= ~FMODE_READABLE; - - return Qnil; -} - -static VALUE -bsock_close_write(sock) - VALUE sock; -{ - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't close socket"); - } - GetOpenFile(sock, fptr); - if (!(fptr->mode & FMODE_READABLE)) { - return rb_io_close(sock); - } - shutdown(fileno(fptr->f2), 1); - fptr->mode &= ~FMODE_WRITABLE; - - return Qnil; -} - -static VALUE -bsock_setsockopt(sock, lev, optname, val) - VALUE sock, lev, optname, val; -{ - int level, option; - OpenFile *fptr; - int i; - char *v; - int vlen; - - rb_secure(2); - level = NUM2INT(lev); - option = NUM2INT(optname); - switch (TYPE(val)) { - case T_FIXNUM: - i = FIX2INT(val); - goto numval; - case T_FALSE: - i = 0; - goto numval; - case T_TRUE: - i = 1; - numval: - v = (char*)&i; vlen = sizeof(i); - break; - default: - StringValue(val); - v = RSTRING(val)->ptr; - vlen = RSTRING(val)->len; - break; - } - - GetOpenFile(sock, fptr); - if (setsockopt(fileno(fptr->f), level, option, v, vlen) < 0) - rb_sys_fail(fptr->path); - - return INT2FIX(0); -} - -static VALUE -bsock_getsockopt(sock, lev, optname) - VALUE sock, lev, optname; -{ -#if !defined(__BEOS__) - int level, option; - socklen_t len; - char *buf; - OpenFile *fptr; - - level = NUM2INT(lev); - option = NUM2INT(optname); - len = 256; - buf = ALLOCA_N(char,len); - - GetOpenFile(sock, fptr); - if (getsockopt(fileno(fptr->f), level, option, buf, &len) < 0) - rb_sys_fail(fptr->path); - - return rb_tainted_str_new(buf, len); -#else - rb_notimplement(); -#endif -} - -static VALUE -bsock_getsockname(sock) - VALUE sock; -{ - char buf[1024]; - socklen_t len = sizeof buf; - OpenFile *fptr; - - GetOpenFile(sock, fptr); - if (getsockname(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0) - rb_sys_fail("getsockname(2)"); - return rb_tainted_str_new(buf, len); -} - -static VALUE -bsock_getpeername(sock) - VALUE sock; -{ - char buf[1024]; - socklen_t len = sizeof buf; - OpenFile *fptr; - - GetOpenFile(sock, fptr); - if (getpeername(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0) - rb_sys_fail("getpeername(2)"); - return rb_tainted_str_new(buf, len); -} - -static VALUE -bsock_send(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE mesg, to; - VALUE flags; - OpenFile *fptr; - FILE *f; - int fd, n; - - rb_secure(4); - rb_scan_args(argc, argv, "21", &mesg, &flags, &to); - - GetOpenFile(sock, fptr); - f = GetWriteFile(fptr); - fd = fileno(f); - retry: - rb_thread_fd_writable(fd); - StringValue(mesg); - if (!NIL_P(to)) { - StringValue(to); - n = sendto(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags), - (struct sockaddr*)RSTRING(to)->ptr, RSTRING(to)->len); - } - else { - n = send(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags)); - } - if (n < 0) { - switch (errno) { - case EINTR: - rb_thread_schedule(); - goto retry; - } - rb_sys_fail("send(2)"); - } - return INT2FIX(n); -} - -static VALUE ipaddr _((struct sockaddr *)); -#ifdef HAVE_SYS_UN_H -static VALUE unixaddr _((struct sockaddr_un *)); -#endif - -enum sock_recv_type { - RECV_RECV, /* BasicSocket#recv(no from) */ - RECV_IP, /* IPSocket#recvfrom */ - RECV_UNIX, /* UNIXSocket#recvfrom */ - RECV_SOCKET /* Socket#recvfrom */ -}; - -static VALUE -s_recvfrom(sock, argc, argv, from) - VALUE sock; - int argc; - VALUE *argv; - enum sock_recv_type from; -{ - OpenFile *fptr; - VALUE str; - char buf[1024]; - socklen_t alen = sizeof buf; - VALUE len, flg; - int fd, flags; - - rb_scan_args(argc, argv, "11", &len, &flg); - - if (flg == Qnil) flags = 0; - else flags = NUM2INT(flg); - - GetOpenFile(sock, fptr); - if (rb_read_pending(fptr->f)) { - rb_raise(rb_eIOError, "recv for buffered IO"); - } - fd = fileno(fptr->f); - - str = rb_tainted_str_new(0, NUM2INT(len)); - - retry: - rb_thread_wait_fd(fd); - TRAP_BEG; - RSTRING(str)->len = recvfrom(fd, RSTRING(str)->ptr, RSTRING(str)->len, flags, - (struct sockaddr*)buf, &alen); - TRAP_END; - - if (RSTRING(str)->len < 0) { - switch (errno) { - case EINTR: - rb_thread_schedule(); - goto retry; - } - rb_sys_fail("recvfrom(2)"); - } - rb_obj_taint(str); - switch (from) { - case RECV_RECV: - return (VALUE)str; - case RECV_IP: -#if 0 - if (alen != sizeof(struct sockaddr_in)) { - rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); - } -#endif - return rb_assoc_new(str, ipaddr((struct sockaddr *)buf)); -#ifdef HAVE_SYS_UN_H - case RECV_UNIX: - return rb_assoc_new(str, unixaddr((struct sockaddr_un *)buf)); -#endif - case RECV_SOCKET: - return rb_assoc_new(str, rb_tainted_str_new(buf, alen)); - default: - rb_bug("s_recvfrom called with bad value"); - } -} - -static VALUE -bsock_recv(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - return s_recvfrom(sock, argc, argv, RECV_RECV); -} - -static VALUE -bsock_do_not_rev_lookup() -{ - return do_not_reverse_lookup?Qtrue:Qfalse; -} - -static VALUE -bsock_do_not_rev_lookup_set(self, val) -{ - do_not_reverse_lookup = RTEST(val); - return val; -} - -static void -mkipaddr0(addr, buf, len) - struct sockaddr *addr; - char *buf; - size_t len; -{ - int error; - - error = getnameinfo(addr, SA_LEN(addr), buf, len, NULL, 0, NI_NUMERICHOST); - if (error) { - rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error)); - } -} - -static VALUE -mkipaddr(addr) - struct sockaddr *addr; -{ - char buf[1024]; - - mkipaddr0(addr, buf, sizeof(buf)); - return rb_tainted_str_new2(buf); -} - -static void -mkinetaddr(host, buf, len) - long host; - char *buf; - size_t len; -{ - struct sockaddr_in sin; - - MEMZERO(&sin, struct sockaddr_in, 1); - sin.sin_family = AF_INET; - SET_SIN_LEN(&sin, sizeof(sin)); - sin.sin_addr.s_addr = host; - mkipaddr0((struct sockaddr *)&sin, buf, len); -} - -static struct addrinfo* -ip_addrsetup(host, port) - VALUE host, port; -{ - struct addrinfo hints, *res; - char *hostp, *portp; - int error; - char hbuf[1024], pbuf[16]; - - if (NIL_P(host)) { - hostp = NULL; - } - else if (rb_obj_is_kind_of(host, rb_cInteger)) { - long i = NUM2LONG(host); - - mkinetaddr(htonl(i), hbuf, sizeof(hbuf)); - hostp = hbuf; - } - else { - char *name; - - SafeStringValue(host); - name = RSTRING(host)->ptr; - if (*name == 0) { - mkinetaddr(INADDR_ANY, hbuf, sizeof(hbuf)); - } - else if (name[0] == '<' && strcmp(name, "") == 0) { - mkinetaddr(INADDR_BROADCAST, hbuf, sizeof(hbuf)); - } - else if (strlen(name) >= sizeof(hbuf)) { - rb_raise(rb_eArgError, "hostname too long (%d)", strlen(name)); - } - else { - strcpy(hbuf, name); - } - hostp = hbuf; - } - if (NIL_P(port)) { - portp = 0; - } - else if (FIXNUM_P(port)) { - snprintf(pbuf, sizeof(pbuf), "%ld", FIX2INT(port)); - portp = pbuf; - } - else { - SafeStringValue(port); - portp = RSTRING(port)->ptr; - } - - MEMZERO(&hints, struct addrinfo, 1); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; - error = getaddrinfo(hostp, portp, &hints, &res); - if (error) { - if (hostp && hostp[strlen(hostp)-1] == '\n') { - rb_raise(rb_eSocket, "newline at the end of hostname"); - } - rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error)); - } - - return res; -} - -static void -setipaddr(name, addr) - VALUE name; - struct sockaddr *addr; -{ - struct addrinfo *res = ip_addrsetup(name, Qnil); - - /* just take the first one */ - memcpy(addr, res->ai_addr, res->ai_addrlen); - freeaddrinfo(res); -} - -static VALUE -ipaddr(sockaddr) - struct sockaddr *sockaddr; -{ - VALUE family, port, addr1, addr2; - VALUE ary; - int error; - char hbuf[1024], pbuf[1024]; - - switch (sockaddr->sa_family) { - case AF_UNSPEC: - family = rb_str_new2("AF_UNSPEC"); - break; - case AF_INET: - family = rb_str_new2("AF_INET"); - break; -#ifdef INET6 - case AF_INET6: - family = rb_str_new2("AF_INET6"); - break; -#endif -#ifdef AF_LOCAL - case AF_LOCAL: - family = rb_str_new2("AF_LOCAL"); - break; -#elif AF_UNIX - case AF_UNIX: - family = rb_str_new2("AF_UNIX"); - break; -#endif - default: - sprintf(pbuf, "unknown:%d", sockaddr->sa_family); - family = rb_str_new2(pbuf); - break; - } - if (!do_not_reverse_lookup) { - error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf), - NULL, 0, 0); - if (error) { - rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error)); - } - addr1 = rb_tainted_str_new2(hbuf); - } - error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf), - pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV); - if (error) { - rb_raise(rb_eSocket, "getnameinfo %s", gai_strerror(error)); - } - addr2 = rb_tainted_str_new2(hbuf); - if (do_not_reverse_lookup) { - addr1 = addr2; - } - port = INT2FIX(atoi(pbuf)); - ary = rb_ary_new3(4, family, port, addr1, addr2); - - return ary; -} - -static int -ruby_socket(domain, type, proto) - int domain, type, proto; -{ - int fd; - - fd = socket(domain, type, proto); - if (fd < 0) { - if (errno == EMFILE || errno == ENFILE) { - rb_gc(); - fd = socket(domain, type, proto); - } - } - return fd; -} - -static void -thread_read_select(fd) - int fd; -{ - fd_set fds; - - FD_ZERO(&fds); - FD_SET(fd, &fds); - rb_thread_select(fd+1, &fds, 0, 0, 0); -} - -static void -thread_write_select(fd) - int fd; -{ - fd_set fds; - - FD_ZERO(&fds); - FD_SET(fd, &fds); - rb_thread_select(fd+1, 0, &fds, 0, 0); -} - -static int -ruby_connect(fd, sockaddr, len, socks) - int fd; - struct sockaddr *sockaddr; - int len; - int socks; -{ - int status; - int mode; -#if defined __CYGWIN__ - int wait_in_progress = -1; -#endif - -#if defined(HAVE_FCNTL) - mode = fcntl(fd, F_GETFL, 0); - -#ifdef O_NDELAY -# define NONBLOCKING O_NDELAY -#else -#ifdef O_NBIO -# define NONBLOCKING O_NBIO -#else -# define NONBLOCKING O_NONBLOCK -#endif -#endif -#ifdef SOCKS5 - if (!socks) -#endif - fcntl(fd, F_SETFL, mode|NONBLOCKING); -#endif /* HAVE_FCNTL */ - - for (;;) { -#if defined(SOCKS) && !defined(SOCKS5) - if (socks) { - status = Rconnect(fd, sockaddr, len); - } - else -#endif - { - status = connect(fd, sockaddr, len); - } - if (status < 0) { - switch (errno) { - case EAGAIN: -#ifdef EINPROGRESS - case EINPROGRESS: -#if defined __CYGWIN__ - case EALREADY: - wait_in_progress = 10; -#endif -#endif - thread_write_select(fd); - continue; - -#if defined __CYGWIN__ - case EINVAL: - if (wait_in_progress-- > 0) { - struct timeval tv = {0, 100000}; - rb_thread_wait_for(tv); - continue; - } - break; -#endif - -#ifdef EISCONN - case EISCONN: - status = 0; - errno = 0; - break; -#endif - default: - break; - } - } -#ifdef HAVE_FCNTL - fcntl(fd, F_SETFL, mode); -#endif - return status; - } -} - -static void -load_addr_info(h, serv, type, res) - VALUE h, serv; - int type; - struct addrinfo **res; -{ - char *host; - char pbuf[1024], *portp; - struct addrinfo hints; - int error; - - if (!NIL_P(h)) { - SafeStringValue(h); - host = RSTRING(h)->ptr; - } - else { - host = NULL; - } - if (FIXNUM_P(serv)) { - snprintf(pbuf, sizeof(pbuf), "%ld", FIX2UINT(serv)); - portp = pbuf; - } - else { - SafeStringValue(serv); - if (RSTRING(serv)->len >= sizeof(pbuf)) - rb_raise(rb_eArgError, "servicename too long (%d)", RSTRING(serv)->len); - strcpy(pbuf, RSTRING(serv)->ptr); - portp = pbuf; - } - MEMZERO(&hints, struct addrinfo, 1); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - if (type == INET_SERVER) { - hints.ai_flags = AI_PASSIVE; - } - error = getaddrinfo(host, portp, &hints, res); - if (error) { - rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error)); - } -} - -static VALUE -init_inetsock(sock, remote_host, remote_serv, local_host, local_serv, type) - VALUE sock, remote_host, remote_serv, local_host, local_serv; - int type; -{ - struct addrinfo hints, *res, *res_remote, *res_local = NULL; - int fd, status; - char *syscall; - - load_addr_info(remote_host, remote_serv, type, &res_remote); - - /* - * Maybe also accept a local address - */ - - if (type != INET_SERVER && (!NIL_P(local_host) || !NIL_P(local_serv))) - load_addr_info(local_host, local_serv, type, &res_local); - - fd = -1; - for (res = res_remote; res; res = res->ai_next) { - status = ruby_socket(res->ai_family,res->ai_socktype,res->ai_protocol); - syscall = "socket(2)"; - fd = status; - if (fd < 0) { - continue; - } - if (type == INET_SERVER) { -#ifndef NT - status = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, - (char*)&status, sizeof(status)); -#endif - status = bind(fd, res->ai_addr, res->ai_addrlen); - syscall = "bind(2)"; - } - else { - if (res_local) { - status = bind(fd, res_local->ai_addr, res_local->ai_addrlen); - syscall = "bind(2)"; - } - - if (status >= 0) { - status = ruby_connect(fd, res->ai_addr, res->ai_addrlen, - (type == INET_SOCKS)); - syscall = "connect(2)"; - } - } - - if (status < 0) { -#if defined(HAVE_CLOSESOCKET) - closesocket(fd); -#else - close(fd); -#endif - fd = -1; - continue; - } else - break; - } - if (status < 0) { - if (fd >= 0) -#if defined(HAVE_CLOSESOCKET) - closesocket(fd); -#else - close(fd); -#endif - freeaddrinfo(res_remote); - if (res_local) { - freeaddrinfo(res_local); - } - rb_sys_fail(syscall); - } - - if (type == INET_SERVER) - listen(fd, 5); - - /* create new instance */ - if (res_local) - freeaddrinfo(res_local); - freeaddrinfo(res_remote); - return init_sock(sock, fd); -} - -static VALUE -tcp_init(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE remote_host, remote_serv; - VALUE local_host, local_serv; - - int pcount = rb_scan_args(argc, argv, "22", - &remote_host, &remote_serv, - &local_host, &local_serv); - - return init_inetsock(sock, remote_host, remote_serv, - local_host, local_serv, INET_CLIENT); -} - -#ifdef SOCKS -static VALUE -socks_init(sock, host, serv) - VALUE sock, host, serv; -{ - static init = 0; - - if (init == 0) { - SOCKSinit("ruby"); - init = 1; - } - - return init_inetsock(class, host, serv, Qnil, Qnil, INET_SOCKS); -} - -#ifdef SOCKS5 -static VALUE -socks_s_close(sock) - VALUE sock; -{ - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't close socket"); - } - GetOpenFile(sock, fptr); - shutdown(fileno(fptr->f), 2); - shutdown(fileno(fptr->f2), 2); - return rb_io_close(sock); -} -#endif -#endif - -/* - * NOTE: using gethostbyname() against AF_INET6 is a bad idea, as it - * does not initialize sin_flowinfo nor sin_scope_id properly. - */ -static VALUE -tcp_s_gethostbyname(obj, host) - VALUE obj, host; -{ - struct sockaddr_storage addr; - struct hostent *h; - char **pch; - VALUE ary, names; - - rb_secure(3); - if (rb_obj_is_kind_of(host, rb_cInteger)) { - long i = NUM2LONG(host); - struct sockaddr_in *sin; - - sin = (struct sockaddr_in *)&addr; - MEMZERO(sin, struct sockaddr_in, 1); - sin->sin_family = AF_INET; - SET_SIN_LEN(sin, sizeof(*sin)); - sin->sin_addr.s_addr = htonl(i); - } - else { - setipaddr(host, &addr); - } - switch (addr.ss_family) { - case AF_INET: - { - struct sockaddr_in *sin; - sin = (struct sockaddr_in *)&addr; - h = gethostbyaddr((char *)&sin->sin_addr, - sizeof(sin->sin_addr), - sin->sin_family); - break; - } -#ifdef INET6 - case AF_INET6: - { - struct sockaddr_in6 *sin6; - sin6 = (struct sockaddr_in6 *)&addr; - h = gethostbyaddr((char *)&sin6->sin6_addr, - sizeof(sin6->sin6_addr), - sin6->sin6_family); - break; - } -#endif - default: - h = NULL; - } - - if (h == NULL) { -#ifdef HAVE_HSTERROR - extern int h_errno; - rb_raise(rb_eSocket, "%s", (char *)hsterror(h_errno)); -#else - rb_raise(rb_eSocket, "host not found"); -#endif - } - ary = rb_ary_new(); - rb_ary_push(ary, rb_tainted_str_new2(h->h_name)); - names = rb_ary_new(); - rb_ary_push(ary, names); - for (pch = h->h_aliases; *pch; pch++) { - rb_ary_push(names, rb_tainted_str_new2(*pch)); - } - rb_ary_push(ary, INT2NUM(h->h_addrtype)); -#ifdef h_addr - for (pch = h->h_addr_list; *pch; pch++) { - switch (addr.ss_family) { - case AF_INET: - { - struct sockaddr_in sin; - MEMZERO(&sin, struct sockaddr_in, 1); - sin.sin_family = AF_INET; - SET_SIN_LEN(&sin, sizeof(sin)); - memcpy((char *) &sin.sin_addr, *pch, h->h_length); - h = gethostbyaddr((char *)&sin.sin_addr, - sizeof(sin.sin_addr), - sin.sin_family); - rb_ary_push(ary, mkipaddr((struct sockaddr *)&sin)); - break; - } -#ifdef INET6 - case AF_INET6: - { - struct sockaddr_in6 sin6; - MEMZERO(&sin6, struct sockaddr_in6, 1); - sin6.sin6_family = AF_INET; -#ifdef SIN6_LEN - sin6.sin6_len = sizeof(sin6); -#endif - memcpy((char *) &sin6.sin6_addr, *pch, h->h_length); - h = gethostbyaddr((char *)&sin6.sin6_addr, - sizeof(sin6.sin6_addr), - sin6.sin6_family); - rb_ary_push(ary, mkipaddr((struct sockaddr *)&sin6)); - break; - } -#endif - default: - h = NULL; - } - } -#else - memcpy((char *)&addr.sin_addr, h->h_addr, h->h_length); - rb_ary_push(ary, mkipaddr((struct sockaddr *)&addr)); -#endif - - return ary; -} - -static VALUE -tcp_svr_init(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE arg1, arg2; - - if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) - return init_inetsock(sock, arg1, arg2, NULL, Qnil, INET_SERVER); - else - return init_inetsock(sock, Qnil, arg1, NULL, Qnil, INET_SERVER); -} - -static VALUE -s_accept(klass, fd, sockaddr, len) - VALUE klass; - int fd; - struct sockaddr *sockaddr; - socklen_t *len; -{ - int fd2; - int retry = 0; - - rb_secure(3); - retry: - rb_thread_wait_fd(fd); -#if defined(_nec_ews) - fd2 = accept(fd, sockaddr, len); -#else - TRAP_BEG; - fd2 = accept(fd, sockaddr, len); - TRAP_END; -#endif - if (fd2 < 0) { - switch (errno) { - case EMFILE: - case ENFILE: - if (retry) break; - rb_gc(); - retry = 1; - goto retry; - case EINTR: - rb_thread_schedule(); - goto retry; - } - rb_sys_fail(0); - } - return init_sock(rb_obj_alloc(klass), fd2); -} - -static VALUE -tcp_accept(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_storage from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(from); - return s_accept(rb_cTCPSocket, fileno(fptr->f), - (struct sockaddr*)&from, &fromlen); -} - -#ifdef HAVE_SYS_UN_H -static VALUE -init_unixsock(sock, path, server) - VALUE sock; - VALUE path; - int server; -{ - struct sockaddr_un sockaddr; - int fd, status; - OpenFile *fptr; - - SafeStringValue(path); - fd = ruby_socket(AF_UNIX, SOCK_STREAM, 0); - if (fd < 0) { - rb_sys_fail("socket(2)"); - } - - MEMZERO(&sockaddr, struct sockaddr_un, 1); - sockaddr.sun_family = AF_UNIX; - strncpy(sockaddr.sun_path, RSTRING(path)->ptr, sizeof(sockaddr.sun_path)-1); - sockaddr.sun_path[sizeof(sockaddr.sun_path)-1] = '\0'; - - if (server) { - status = bind(fd, (struct sockaddr*)&sockaddr, sizeof(sockaddr)); - } - else { - status = ruby_connect(fd, (struct sockaddr*)&sockaddr, sizeof(sockaddr), 0); - } - - if (status < 0) { -#if defined(HAVE_CLOSESOCKET) - closesocket(fd); -#else - close(fd); -#endif - rb_sys_fail(sockaddr.sun_path); - } - - if (server) listen(fd, 5); - - init_sock(sock, fd); - GetOpenFile(sock, fptr); - fptr->path = strdup(RSTRING(path)->ptr); - - return sock; -} -#endif - -static VALUE -ip_addr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_storage addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getsockname(2)"); - return ipaddr((struct sockaddr *)&addr); -} - -static VALUE -ip_peeraddr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_storage addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getpeername(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getpeername(2)"); - return ipaddr((struct sockaddr *)&addr); -} - -static VALUE -ip_recvfrom(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - return s_recvfrom(sock, argc, argv, RECV_IP); -} - -static VALUE -ip_s_getaddress(obj, host) - VALUE obj, host; -{ - struct sockaddr_storage addr; - - setipaddr(host, &addr); - return mkipaddr((struct sockaddr *)&addr); -} - -static VALUE -udp_init(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE arg; - int socktype = AF_INET; - int fd; - - rb_secure(3); - if (rb_scan_args(argc, argv, "01", &arg) == 1) { - socktype = NUM2INT(arg); - } - fd = ruby_socket(socktype, SOCK_DGRAM, 0); - if (fd < 0) { - rb_sys_fail("socket(2) - udp"); - } - - return init_sock(sock, fd); -} - -static VALUE -udp_connect(sock, host, port) - VALUE sock, host, port; -{ - OpenFile *fptr; - int fd; - struct addrinfo *res0, *res; - - rb_secure(3); - GetOpenFile(sock, fptr); - fd = fileno(fptr->f); - res0 = ip_addrsetup(host, port); - for (res = res0; res; res = res->ai_next) { - if (ruby_connect(fd, res->ai_addr, res->ai_addrlen, 0) >= 0) { - freeaddrinfo(res0); - return INT2FIX(0); - } - } - - freeaddrinfo(res0); - rb_sys_fail("connect(2)"); - return INT2FIX(0); -} - -static VALUE -udp_bind(sock, host, port) - VALUE sock, host, port; -{ - OpenFile *fptr; - struct addrinfo *res0, *res; - - rb_secure(3); - GetOpenFile(sock, fptr); - res0 = ip_addrsetup(host, port); - for (res = res0; res; res = res->ai_next) { - if (bind(fileno(fptr->f), res->ai_addr, res->ai_addrlen) < 0) { - continue; - } - freeaddrinfo(res0); - return INT2FIX(0); - } - freeaddrinfo(res0); - rb_sys_fail("bind(2)"); - return INT2FIX(0); -} - -static VALUE -udp_send(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE mesg, flags, host, port; - OpenFile *fptr; - FILE *f; - int n; - struct addrinfo *res0, *res; - - if (argc == 2 || argc == 3) { - return bsock_send(argc, argv, sock); - } - rb_secure(4); - rb_scan_args(argc, argv, "4", &mesg, &flags, &host, &port); - - GetOpenFile(sock, fptr); - res0 = ip_addrsetup(host, port); - f = GetWriteFile(fptr); - StringValue(mesg); - for (res = res0; res; res = res->ai_next) { - retry: - n = sendto(fileno(f), RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags), - res->ai_addr, res->ai_addrlen); - if (n >= 0) { - freeaddrinfo(res0); - return INT2FIX(n); - } - switch (errno) { - case EINTR: - rb_thread_schedule(); - goto retry; - } - } - freeaddrinfo(res0); - rb_sys_fail("sendto(2)"); - return INT2FIX(n); -} - -#ifdef HAVE_SYS_UN_H -static VALUE -unix_init(sock, path) - VALUE sock, path; -{ - return init_unixsock(sock, path, 0); -} - -static VALUE -unix_path(sock) - VALUE sock; -{ - OpenFile *fptr; - - GetOpenFile(sock, fptr); - if (fptr->path == 0) { - struct sockaddr_un addr; - socklen_t len = sizeof(addr); - if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail(0); - fptr->path = strdup(addr.sun_path); - } - return rb_tainted_str_new2(fptr->path); -} - -static VALUE -unix_svr_s_open(klass, path) - VALUE klass, path; -{ - return init_unixsock(rb_obj_alloc(klass), path, 1); -} - -static VALUE -unix_svr_init(sock, path) - VALUE sock, path; -{ - return init_unixsock(sock, path, 1); -} - -static VALUE -unix_recvfrom(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - return s_recvfrom(sock, argc, argv, RECV_UNIX); -} - -static VALUE -unix_send_io(sock, val) - VALUE sock, val; -{ -#if defined(HAVE_ST_MSG_CONTROL) || defined(HAVE_ST_MSG_ACCRIGHTS) - int fd; - OpenFile *fptr; - struct msghdr msg; - struct iovec vec[1]; - char buf[1]; - -#if defined(HAVE_ST_MSG_CONTROL) - struct { - struct cmsghdr hdr; - int fd; - } cmsg; -#endif - - if (rb_obj_is_kind_of(val, rb_cIO)) { - OpenFile *valfptr; - GetOpenFile(val, valfptr); - fd = fileno(valfptr->f); - } - else if (FIXNUM_P(val)) { - fd = FIX2INT(val); - } - else { - rb_raise(rb_eTypeError, "IO nor file descriptor"); - } - - GetOpenFile(sock, fptr); - - msg.msg_name = NULL; - msg.msg_namelen = 0; - - /* Linux and Solaris doesn't work if msg_iov is NULL. */ - buf[0] = '\0'; - vec[0].iov_base = buf; - vec[0].iov_len = 1; - msg.msg_iov = vec; - msg.msg_iovlen = 1; - -#if defined(HAVE_ST_MSG_CONTROL) - msg.msg_control = (caddr_t)&cmsg; - msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(int); - msg.msg_flags = 0; - cmsg.hdr.cmsg_len = sizeof(struct cmsghdr) + sizeof(int); - cmsg.hdr.cmsg_level = SOL_SOCKET; - cmsg.hdr.cmsg_type = SCM_RIGHTS; - cmsg.fd = fd; -#else - msg.msg_accrights = (caddr_t)&fd; - msg.msg_accrightslen = sizeof(fd); -#endif - - if (sendmsg(fileno(fptr->f), &msg, 0) == -1) - rb_sys_fail("sendmsg(2)"); - - return Qnil; -#else - rb_notimplement(); -#endif -} - -static VALUE -unix_recv_io(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ -#if defined(HAVE_ST_MSG_CONTROL) || defined(HAVE_ST_MSG_ACCRIGHTS) - VALUE klass, mode; - OpenFile *fptr; - struct msghdr msg; - struct iovec vec[2]; - char buf[1]; - - int fd; -#if defined(HAVE_ST_MSG_CONTROL) - struct { - struct cmsghdr hdr; - int fd; - } cmsg; -#endif - - rb_scan_args(argc, argv, "02", &klass, &mode); - if (argc == 0) - klass = rb_cIO; - if (argc <= 1) - mode = Qnil; - - GetOpenFile(sock, fptr); - - thread_read_select(fileno(fptr->f)); - - msg.msg_name = NULL; - msg.msg_namelen = 0; - - vec[0].iov_base = buf; - vec[0].iov_len = sizeof(buf); - msg.msg_iov = vec; - msg.msg_iovlen = 1; - -#if defined(HAVE_ST_MSG_CONTROL) - msg.msg_control = (caddr_t)&cmsg; - msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(int); - msg.msg_flags = 0; - cmsg.hdr.cmsg_len = sizeof(struct cmsghdr) + sizeof(int); - cmsg.hdr.cmsg_level = SOL_SOCKET; - cmsg.hdr.cmsg_type = SCM_RIGHTS; - cmsg.fd = -1; -#else - msg.msg_accrights = (caddr_t)&fd; - msg.msg_accrightslen = sizeof(fd); - fd = -1; -#endif - - if (recvmsg(fileno(fptr->f), &msg, 0) == -1) - rb_sys_fail("recvmsg(2)"); - - if ( -#if defined(HAVE_ST_MSG_CONTROL) - msg.msg_controllen != sizeof(struct cmsghdr) + sizeof(int) || - cmsg.hdr.cmsg_len != sizeof(struct cmsghdr) + sizeof(int) || - cmsg.hdr.cmsg_level != SOL_SOCKET || - cmsg.hdr.cmsg_type != SCM_RIGHTS -#else - msg.msg_accrightslen != sizeof(fd) -#endif - ) { - rb_raise(rb_eSocket, "File descriptor was not passed"); - } - -#if defined(HAVE_ST_MSG_CONTROL) - fd = cmsg.fd; -#endif - - if (klass == Qnil) - return INT2FIX(fd); - else { - static ID for_fd = 0; - int ff_argc; - VALUE ff_argv[2]; - if (!for_fd) - for_fd = rb_intern("for_fd"); - ff_argc = mode == Qnil ? 1 : 2; - ff_argv[0] = INT2FIX(fd); - ff_argv[1] = mode; - return rb_funcall2(klass, for_fd, ff_argc, ff_argv); - } -#else - rb_notimplement(); -#endif -} - -static VALUE -unix_accept(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(struct sockaddr_un); - return s_accept(rb_cUNIXSocket, fileno(fptr->f), - (struct sockaddr*)&from, &fromlen); -} - -static VALUE -unixaddr(sockaddr) - struct sockaddr_un *sockaddr; -{ - return rb_assoc_new(rb_str_new2("AF_UNIX"), - rb_tainted_str_new2(sockaddr->sun_path)); -} - -static VALUE -unix_addr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getsockname(2)"); - if (len == 0) - addr.sun_path[0] = '\0'; - return unixaddr(&addr); -} - -static VALUE -unix_peeraddr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getpeername(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getsockname(2)"); - if (len == 0) - addr.sun_path[0] = '\0'; - return unixaddr(&addr); -} -#endif - -static void -setup_domain_and_type(domain, dv, type, tv) - VALUE domain, type; - int *dv, *tv; -{ - char *ptr; - - if (TYPE(domain) == T_STRING) { - SafeStringValue(domain); - ptr = RSTRING(domain)->ptr; - if (strcmp(ptr, "AF_INET") == 0) - *dv = AF_INET; -#ifdef AF_UNIX - else if (strcmp(ptr, "AF_UNIX") == 0) - *dv = AF_UNIX; -#endif -#ifdef AF_ISO - else if (strcmp(ptr, "AF_ISO") == 0) - *dv = AF_ISO; -#endif -#ifdef AF_NS - else if (strcmp(ptr, "AF_NS") == 0) - *dv = AF_NS; -#endif -#ifdef AF_IMPLINK - else if (strcmp(ptr, "AF_IMPLINK") == 0) - *dv = AF_IMPLINK; -#endif -#ifdef PF_INET - else if (strcmp(ptr, "PF_INET") == 0) - *dv = PF_INET; -#endif -#ifdef PF_UNIX - else if (strcmp(ptr, "PF_UNIX") == 0) - *dv = PF_UNIX; -#endif -#ifdef PF_IMPLINK - else if (strcmp(ptr, "PF_IMPLINK") == 0) - *dv = PF_IMPLINK; - else if (strcmp(ptr, "AF_IMPLINK") == 0) - *dv = AF_IMPLINK; -#endif -#ifdef PF_AX25 - else if (strcmp(ptr, "PF_AX25") == 0) - *dv = PF_AX25; -#endif -#ifdef PF_IPX - else if (strcmp(ptr, "PF_IPX") == 0) - *dv = PF_IPX; -#endif - else - rb_raise(rb_eSocket, "Unknown socket domain %s", ptr); - } - else { - *dv = NUM2INT(domain); - } - if (TYPE(type) == T_STRING) { - SafeStringValue(type); - ptr = RSTRING(type)->ptr; - if (strcmp(ptr, "SOCK_STREAM") == 0) - *tv = SOCK_STREAM; - else if (strcmp(ptr, "SOCK_DGRAM") == 0) - *tv = SOCK_DGRAM; -#ifdef SOCK_RAW - else if (strcmp(ptr, "SOCK_RAW") == 0) - *tv = SOCK_RAW; -#endif -#ifdef SOCK_SEQPACKET - else if (strcmp(ptr, "SOCK_SEQPACKET") == 0) - *tv = SOCK_SEQPACKET; -#endif -#ifdef SOCK_RDM - else if (strcmp(ptr, "SOCK_RDM") == 0) - *tv = SOCK_RDM; -#endif -#ifdef SOCK_PACKET - else if (strcmp(ptr, "SOCK_PACKET") == 0) - *tv = SOCK_PACKET; -#endif - else - rb_raise(rb_eSocket, "Unknown socket type %s", ptr); - } - else { - *tv = NUM2INT(type); - } -} - -static VALUE -sock_init(sock, domain, type, protocol) - VALUE sock, domain, type, protocol; -{ - int fd; - int d, t; - - rb_secure(3); - setup_domain_and_type(domain, &d, type, &t); - fd = ruby_socket(d, t, NUM2INT(protocol)); - if (fd < 0) rb_sys_fail("socket(2)"); - - return init_sock(sock, fd); -} - -static VALUE -sock_s_socketpair(klass, domain, type, protocol) - VALUE klass, domain, type, protocol; -{ -#if !defined(NT) && !defined(__BEOS__) && !defined(__EMX__) && !defined(__QNXNTO__) - int d, t, sp[2]; - - setup_domain_and_type(domain, &d, type, &t); - again: - if (socketpair(d, t, NUM2INT(protocol), sp) < 0) { - if (errno == EMFILE || errno == ENFILE) { - rb_gc(); - goto again; - } - rb_sys_fail("socketpair(2)"); - } - - return rb_assoc_new(init_sock(rb_obj_alloc(klass), sp[0]), - init_sock(rb_obj_alloc(klass), sp[1])); -#else - rb_notimplement(); -#endif -} - -#ifdef HAVE_SYS_UN_H -static VALUE -unix_s_socketpair(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE domain, type, protocol; - domain = INT2FIX(PF_UNIX); - - rb_scan_args(argc, argv, "02", &type, &protocol); - if (argc == 0) - type = INT2FIX(SOCK_STREAM); - if (argc <= 1) - protocol = INT2FIX(0); - - return sock_s_socketpair(klass, domain, type, protocol); -} -#endif - -static VALUE -sock_connect(sock, addr) - VALUE sock, addr; -{ - OpenFile *fptr; - int fd; - - StringValue(addr); - rb_str_modify(addr); - - GetOpenFile(sock, fptr); - fd = fileno(fptr->f); - if (ruby_connect(fd, (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len, 0) < 0) { - rb_sys_fail("connect(2)"); - } - - return INT2FIX(0); -} - -static VALUE -sock_bind(sock, addr) - VALUE sock, addr; -{ - OpenFile *fptr; - - StringValue(addr); - rb_str_modify(addr); - - GetOpenFile(sock, fptr); - if (bind(fileno(fptr->f), (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len) < 0) - rb_sys_fail("bind(2)"); - - return INT2FIX(0); -} - -static VALUE -sock_listen(sock, log) - VALUE sock, log; -{ - OpenFile *fptr; - - rb_secure(4); - GetOpenFile(sock, fptr); - if (listen(fileno(fptr->f), NUM2INT(log)) < 0) - rb_sys_fail("listen(2)"); - - return INT2FIX(0); -} - -static VALUE -sock_recvfrom(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - return s_recvfrom(sock, argc, argv, RECV_SOCKET); -} - -static VALUE -sock_accept(sock) - VALUE sock; -{ - OpenFile *fptr; - VALUE sock2; - char buf[1024]; - socklen_t len = sizeof buf; - - GetOpenFile(sock, fptr); - sock2 = s_accept(rb_cSocket,fileno(fptr->f),(struct sockaddr*)buf,&len); - - return rb_assoc_new(sock2, rb_tainted_str_new(buf, len)); -} - -#ifdef HAVE_GETHOSTNAME -static VALUE -sock_gethostname(obj) - VALUE obj; -{ - char buf[1024]; - - rb_secure(3); - if (gethostname(buf, (int)sizeof buf - 1) < 0) - rb_sys_fail("gethostname"); - - buf[sizeof buf - 1] = '\0'; - return rb_tainted_str_new2(buf); -} -#else -#ifdef HAVE_UNAME - -#include - -static VALUE -sock_gethostname(obj) - VALUE obj; -{ - struct utsname un; - - rb_secure(3); - uname(&un); - return rb_tainted_str_new2(un.nodename); -} -#else -static VALUE -sock_gethostname(obj) - VALUE obj; -{ - rb_notimplement(); -} -#endif -#endif - -static VALUE -mkhostent(h) - struct hostent *h; -{ - char **pch; - VALUE ary, names; - - if (h == NULL) { -#ifdef HAVE_HSTRERROR - extern int h_errno; - rb_raise(rb_eSocket, "%s", (char *)hstrerror(h_errno)); -#else - rb_raise(rb_eSocket, "host not found"); -#endif - } - ary = rb_ary_new(); - rb_ary_push(ary, rb_tainted_str_new2(h->h_name)); - names = rb_ary_new(); - rb_ary_push(ary, names); - for (pch = h->h_aliases; *pch; pch++) { - rb_ary_push(names, rb_tainted_str_new2(*pch)); - } - rb_ary_push(ary, INT2NUM(h->h_addrtype)); -#ifdef h_addr - for (pch = h->h_addr_list; *pch; pch++) { - rb_ary_push(ary, rb_tainted_str_new(*pch, h->h_length)); - } -#else - rb_ary_push(ary, rb_tainted_str_new(h->h_addr, h->h_length)); -#endif - - return ary; -} - -static VALUE -mkaddrinfo(res0) - struct addrinfo *res0; -{ - VALUE base, ary; - struct addrinfo *res; - - if (res0 == NULL) { - rb_raise(rb_eSocket, "host not found"); - } - base = rb_ary_new(); - for (res = res0; res; res = res->ai_next) { - ary = ipaddr(res->ai_addr); - rb_ary_push(ary, INT2FIX(res->ai_family)); - rb_ary_push(ary, INT2FIX(res->ai_socktype)); - rb_ary_push(ary, INT2FIX(res->ai_protocol)); - rb_ary_push(base, ary); - } - return base; -} - -/* - * NOTE: using gethostbyname() against AF_INET6 is a bad idea, as it - * does not initialize sin_flowinfo nor sin_scope_id properly. - */ -static VALUE -sock_s_gethostbyname(obj, host) - VALUE obj, host; -{ - struct sockaddr_storage addr; - struct hostent *h; - - if (rb_obj_is_kind_of(host, rb_cInteger)) { - long i = NUM2LONG(host); - struct sockaddr_in *sin; - sin = (struct sockaddr_in *)&addr; - MEMZERO(sin, struct sockaddr_in, 1); - sin->sin_family = AF_INET; - SET_SIN_LEN(sin, sizeof(*sin)); - sin->sin_addr.s_addr = htonl(i); - } - else { - setipaddr(host, (struct sockaddr *)&addr); - } - switch (addr.ss_family) { - case AF_INET: - { - struct sockaddr_in *sin; - sin = (struct sockaddr_in *)&addr; - h = gethostbyaddr((char *)&sin->sin_addr, - sizeof(sin->sin_addr), - sin->sin_family); - break; - } -#ifdef INET6 - case AF_INET6: - { - struct sockaddr_in6 *sin6; - sin6 = (struct sockaddr_in6 *)&addr; - h = gethostbyaddr((char *)&sin6->sin6_addr, - sizeof(sin6->sin6_addr), - sin6->sin6_family); - break; - } -#endif - default: - h = NULL; - } - - return mkhostent(h); -} - -static VALUE -sock_s_gethostbyaddr(argc, argv) - int argc; - VALUE *argv; -{ - VALUE addr, type; - struct hostent *h; - struct sockaddr *sa; - int t = AF_INET; - - rb_scan_args(argc, argv, "11", &addr, &type); - sa = (struct sockaddr*)StringValuePtr(addr); - if (!NIL_P(type)) { - t = NUM2INT(type); - } -#ifdef INET6 - else if (RSTRING(addr)->len == 16) { - t = AF_INET6; - } -#endif - h = gethostbyaddr(RSTRING(addr)->ptr, RSTRING(addr)->len, t); - - return mkhostent(h); -} - -static VALUE -sock_s_getservbyaname(argc, argv) - int argc; - VALUE *argv; -{ - VALUE service, protocol; - char *proto; - struct servent *sp; - int port; - - rb_scan_args(argc, argv, "11", &service, &protocol); - if (NIL_P(protocol)) proto = "tcp"; - else proto = StringValuePtr(protocol); - - StringValue(service); - sp = getservbyname(RSTRING(service)->ptr, proto); - if (sp) { - port = ntohs(sp->s_port); - } - else { - char *s = RSTRING(service)->ptr; - char *end; - - port = strtoul(s, &end, 0); - if (*end != '\0') { - rb_raise(rb_eSocket, "no such service %s/%s", s, proto); - } - } - return INT2FIX(port); -} - -static VALUE -sock_s_getaddrinfo(argc, argv) - int argc; - VALUE *argv; -{ - VALUE host, port, family, socktype, protocol, flags, ret; - char hbuf[1024], pbuf[1024]; - char *hptr, *pptr; - struct addrinfo hints, *res; - int error; - - host = port = family = socktype = protocol = flags = Qnil; - rb_scan_args(argc, argv, "24", &host, &port, &family, &socktype, &protocol, &flags); - if (NIL_P(host)) { - hptr = NULL; - } - else { - strncpy(hbuf, StringValuePtr(host), sizeof(hbuf)); - hbuf[sizeof(hbuf) - 1] = '\0'; - hptr = hbuf; - } - if (NIL_P(port)) { - pptr = NULL; - } - else if (FIXNUM_P(port)) { - snprintf(pbuf, sizeof(pbuf), "%ld", FIX2INT(port)); - pptr = pbuf; - } - else { - strncpy(pbuf, StringValuePtr(port), sizeof(pbuf)); - pbuf[sizeof(pbuf) - 1] = '\0'; - pptr = pbuf; - } - - MEMZERO(&hints, struct addrinfo, 1); - if (NIL_P(family)) { - hints.ai_family = PF_UNSPEC; - } - else if (FIXNUM_P(family)) { - hints.ai_family = FIX2INT(family); - } - else { - StringValue(family); - if (strcmp(RSTRING(family)->ptr, "AF_INET") == 0) { - hints.ai_family = PF_INET; - } -#ifdef INET6 - else if (strcmp(RSTRING(family)->ptr, "AF_INET6") == 0) { - hints.ai_family = PF_INET6; - } -#endif - } - - if (!NIL_P(socktype)) { - hints.ai_socktype = NUM2INT(socktype); - } - if (!NIL_P(protocol)) { - hints.ai_protocol = NUM2INT(protocol); - } - if (!NIL_P(flags)) { - hints.ai_flags = NUM2INT(flags); - } - error = getaddrinfo(hptr, pptr, &hints, &res); - if (error) { - rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error)); - } - - ret = mkaddrinfo(res); - freeaddrinfo(res); - return ret; -} - -static VALUE -sock_s_getnameinfo(argc, argv) - int argc; - VALUE *argv; -{ - VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags; - char *hptr, *pptr; - char hbuf[1024], pbuf[1024]; - int fl; - struct addrinfo hints, *res = NULL, *r; - int error; - struct sockaddr_storage ss; - struct sockaddr *sap; - char *ep; - - sa = flags = Qnil; - rb_scan_args(argc, argv, "11", &sa, &flags); - - fl = 0; - if (!NIL_P(flags)) { - fl = NUM2INT(flags); - } - if (TYPE(sa) == T_STRING) { - if (sizeof(ss) < RSTRING(sa)->len) { - rb_raise(rb_eTypeError, "sockaddr length too big"); - } - memcpy(&ss, RSTRING(sa)->ptr, RSTRING(sa)->len); - if (RSTRING(sa)->len != SA_LEN((struct sockaddr *)&ss)) { - rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); - } - sap = (struct sockaddr *)&ss; - } - else if (TYPE(sa) == T_ARRAY) { - MEMZERO(&hints, struct addrinfo, 1); - if (RARRAY(sa)->len == 3) { - af = RARRAY(sa)->ptr[0]; - port = RARRAY(sa)->ptr[1]; - host = RARRAY(sa)->ptr[2]; - } - else if (RARRAY(sa)->len >= 4) { - af = RARRAY(sa)->ptr[0]; - port = RARRAY(sa)->ptr[1]; - host = RARRAY(sa)->ptr[3]; - if (NIL_P(host)) { - host = RARRAY(sa)->ptr[2]; - } - else { - /* - * 4th element holds numeric form, don't resolve. - * see ipaddr(). - */ - hints.ai_flags |= AI_NUMERICHOST; - } - } - else { - rb_raise(rb_eArgError, "array size should be 3 or 4, %d given", - RARRAY(sa)->len); - } - /* host */ - if (NIL_P(host)) { - hptr = NULL; - } - else { - strncpy(hbuf, StringValuePtr(host), sizeof(hbuf)); - hbuf[sizeof(hbuf) - 1] = '\0'; - hptr = hbuf; - } - /* port */ - if (NIL_P(port)) { - strcpy(pbuf, "0"); - pptr = NULL; - } - else if (FIXNUM_P(port)) { - snprintf(pbuf, sizeof(pbuf), "%ld", NUM2INT(port)); - pptr = pbuf; - } - else { - strncpy(pbuf, StringValuePtr(port), sizeof(pbuf)); - pbuf[sizeof(pbuf) - 1] = '\0'; - pptr = pbuf; - } - hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; - /* af */ - if (NIL_P(af)) { - hints.ai_family = PF_UNSPEC; - } - else if (FIXNUM_P(af)) { - hints.ai_family = FIX2INT(af); - } - else { - StringValue(af); - if (strcmp(RSTRING(af)->ptr, "AF_INET") == 0) { - hints.ai_family = PF_INET; - } -#ifdef INET6 - else if (strcmp(RSTRING(af)->ptr, "AF_INET6") == 0) { - hints.ai_family = PF_INET6; - } -#endif - } - error = getaddrinfo(hptr, pptr, &hints, &res); - if (error) goto error_exit_addr; - sap = res->ai_addr; - } - else { - rb_raise(rb_eTypeError, "expecting String or Array"); - } - - error = getnameinfo(sap, SA_LEN(sap), hbuf, sizeof(hbuf), - pbuf, sizeof(pbuf), fl); - if (error) goto error_exit_name; - if (res) { - for (r = res->ai_next; r; r = r->ai_next) { - char hbuf2[1024], pbuf2[1024]; - - sap = r->ai_addr; - error = getnameinfo(sap, SA_LEN(sap), hbuf2, sizeof(hbuf2), - pbuf2, sizeof(pbuf2), fl); - if (error) goto error_exit_name; - if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) { - freeaddrinfo(res); - rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename"); - } - } - freeaddrinfo(res); - } - return rb_assoc_new(rb_tainted_str_new2(hbuf), rb_tainted_str_new2(pbuf)); - - error_exit_addr: - if (res) freeaddrinfo(res); - rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error)); - - error_exit_name: - if (res) freeaddrinfo(res); - rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error)); -} - -static VALUE -sock_s_pack_sockaddr_in(self, port, host) - VALUE self, port, host; -{ - struct addrinfo *res = ip_addrsetup(host, port); - VALUE addr = rb_str_new((char*)res->ai_addr, res->ai_addrlen); - - freeaddrinfo(res); - OBJ_INFECT(addr, port); - OBJ_INFECT(addr, host); - - return addr; -} - -static VALUE -sock_s_unpack_sockaddr_in(self, addr) - VALUE self, addr; -{ - struct sockaddr_in * sockaddr; - - sockaddr = (struct sockaddr_in*)StringValuePtr(addr); - return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), mkipaddr(sockaddr)); -} - -#ifdef HAVE_SYS_UN_H -static VALUE -sock_s_pack_sockaddr_un(self, path) - VALUE self, path; -{ - struct sockaddr_un sockaddr; - VALUE addr; - - MEMZERO(&sockaddr, struct sockaddr_un, 1); - sockaddr.sun_family = AF_UNIX; - strncpy(sockaddr.sun_path, StringValuePtr(path), sizeof(sockaddr.sun_path)-1); - addr = rb_str_new((char*)&sockaddr, sizeof(sockaddr)); - OBJ_INFECT(addr, path); - - return addr; -} - -static VALUE -sock_s_unpack_sockaddr_un(self, addr) - VALUE self, addr; -{ - struct sockaddr_un * sockaddr; - - sockaddr = (struct sockaddr_un*)StringValuePtr(addr); - /* xxx: should I check against sun_path size? */ - return rb_tainted_str_new2(sockaddr->sun_path); -} -#endif - -static VALUE mConst; - -static void -sock_define_const(name, value) - char *name; - int value; -{ - rb_define_const(rb_cSocket, name, INT2FIX(value)); - rb_define_const(mConst, name, INT2FIX(value)); -} - -void -Init_socket() -{ - rb_eSocket = rb_define_class("SocketError", rb_eStandardError); - - rb_cBasicSocket = rb_define_class("BasicSocket", rb_cIO); - rb_undef_method(rb_cBasicSocket, "initialize"); - - rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup", - bsock_do_not_rev_lookup, 0); - rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup=", - bsock_do_not_rev_lookup_set, 1); - rb_define_singleton_method(rb_cBasicSocket, "for_fd", bsock_s_for_fd, 1); - - rb_define_method(rb_cBasicSocket, "close_read", bsock_close_read, 0); - rb_define_method(rb_cBasicSocket, "close_write", bsock_close_write, 0); - rb_define_method(rb_cBasicSocket, "shutdown", bsock_shutdown, -1); - rb_define_method(rb_cBasicSocket, "setsockopt", bsock_setsockopt, 3); - rb_define_method(rb_cBasicSocket, "getsockopt", bsock_getsockopt, 2); - rb_define_method(rb_cBasicSocket, "getsockname", bsock_getsockname, 0); - rb_define_method(rb_cBasicSocket, "getpeername", bsock_getpeername, 0); - rb_define_method(rb_cBasicSocket, "send", bsock_send, -1); - rb_define_method(rb_cBasicSocket, "recv", bsock_recv, -1); - - rb_cIPSocket = rb_define_class("IPSocket", rb_cBasicSocket); - rb_define_global_const("IPsocket", rb_cIPSocket); - rb_define_method(rb_cIPSocket, "addr", ip_addr, 0); - rb_define_method(rb_cIPSocket, "peeraddr", ip_peeraddr, 0); - rb_define_method(rb_cIPSocket, "recvfrom", ip_recvfrom, -1); - rb_define_singleton_method(rb_cIPSocket, "getaddress", ip_s_getaddress, 1); - - rb_cTCPSocket = rb_define_class("TCPSocket", rb_cIPSocket); - rb_define_global_const("TCPsocket", rb_cTCPSocket); - rb_define_singleton_method(rb_cTCPSocket, "gethostbyname", tcp_s_gethostbyname, 1); - rb_define_method(rb_cTCPSocket, "initialize", tcp_init, -1); - -#ifdef SOCKS - rb_cSOCKSSocket = rb_define_class("SOCKSSocket", rb_cTCPSocket); - rb_define_global_const("SOCKSsocket", rb_cSOCKSSocket); - rb_define_method(rb_cSOCKSSocket, "initialize", socks_init, 2); -#ifdef SOCKS5 - rb_define_method(rb_cSOCKSSocket, "close", socks_s_close, 0); -#endif -#endif - - rb_cTCPServer = rb_define_class("TCPServer", rb_cTCPSocket); - rb_define_global_const("TCPserver", rb_cTCPServer); - rb_define_method(rb_cTCPServer, "accept", tcp_accept, 0); - rb_define_method(rb_cTCPServer, "initialize", tcp_svr_init, -1); - rb_define_method(rb_cTCPServer, "listen", sock_listen, 1); - - rb_cUDPSocket = rb_define_class("UDPSocket", rb_cIPSocket); - rb_define_global_const("UDPsocket", rb_cUDPSocket); - rb_define_method(rb_cUDPSocket, "initialize", udp_init, -1); - rb_define_method(rb_cUDPSocket, "connect", udp_connect, 2); - rb_define_method(rb_cUDPSocket, "bind", udp_bind, 2); - rb_define_method(rb_cUDPSocket, "send", udp_send, -1); - -#ifdef HAVE_SYS_UN_H - rb_cUNIXSocket = rb_define_class("UNIXSocket", rb_cBasicSocket); - rb_define_global_const("UNIXsocket", rb_cUNIXSocket); - rb_define_method(rb_cUNIXSocket, "initialize", unix_init, 1); - rb_define_method(rb_cUNIXSocket, "path", unix_path, 0); - rb_define_method(rb_cUNIXSocket, "addr", unix_addr, 0); - rb_define_method(rb_cUNIXSocket, "peeraddr", unix_peeraddr, 0); - rb_define_method(rb_cUNIXSocket, "recvfrom", unix_recvfrom, -1); - rb_define_method(rb_cUNIXSocket, "send_io", unix_send_io, 1); - rb_define_method(rb_cUNIXSocket, "recv_io", unix_recv_io, -1); - rb_define_singleton_method(rb_cUNIXSocket, "socketpair", unix_s_socketpair, -1); - rb_define_singleton_method(rb_cUNIXSocket, "pair", unix_s_socketpair, -1); - - rb_cUNIXServer = rb_define_class("UNIXServer", rb_cUNIXSocket); - rb_define_global_const("UNIXserver", rb_cUNIXServer); - rb_define_method(rb_cUNIXServer, "initialize", unix_svr_init, 1); - rb_define_method(rb_cUNIXServer, "accept", unix_accept, 0); - rb_define_method(rb_cUNIXServer, "listen", sock_listen, 1); -#endif - - rb_cSocket = rb_define_class("Socket", rb_cBasicSocket); - - rb_define_method(rb_cSocket, "initialize", sock_init, 3); - rb_define_method(rb_cSocket, "connect", sock_connect, 1); - rb_define_method(rb_cSocket, "bind", sock_bind, 1); - rb_define_method(rb_cSocket, "listen", sock_listen, 1); - rb_define_method(rb_cSocket, "accept", sock_accept, 0); - - rb_define_method(rb_cSocket, "recvfrom", sock_recvfrom, -1); - - rb_define_singleton_method(rb_cSocket, "socketpair", sock_s_socketpair, 3); - rb_define_singleton_method(rb_cSocket, "pair", sock_s_socketpair, 3); - rb_define_singleton_method(rb_cSocket, "gethostname", sock_gethostname, 0); - rb_define_singleton_method(rb_cSocket, "gethostbyname", sock_s_gethostbyname, 1); - rb_define_singleton_method(rb_cSocket, "gethostbyaddr", sock_s_gethostbyaddr, -1); - rb_define_singleton_method(rb_cSocket, "getservbyname", sock_s_getservbyaname, -1); - rb_define_singleton_method(rb_cSocket, "getaddrinfo", sock_s_getaddrinfo, -1); - rb_define_singleton_method(rb_cSocket, "getnameinfo", sock_s_getnameinfo, -1); - rb_define_singleton_method(rb_cSocket, "sockaddr_in", sock_s_pack_sockaddr_in, 2); - rb_define_singleton_method(rb_cSocket, "pack_sockaddr_in", sock_s_pack_sockaddr_in, 2); - rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_in", sock_s_unpack_sockaddr_in, 1); -#ifdef HAVE_SYS_UN_H - rb_define_singleton_method(rb_cSocket, "sockaddr_un", sock_s_pack_sockaddr_un, 1); - rb_define_singleton_method(rb_cSocket, "pack_sockaddr_un", sock_s_pack_sockaddr_un, 1); - rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_un", sock_s_unpack_sockaddr_un, 1); -#endif - - /* constants */ - mConst = rb_define_module_under(rb_cSocket, "Constants"); - sock_define_const("SOCK_STREAM", SOCK_STREAM); - sock_define_const("SOCK_DGRAM", SOCK_DGRAM); -#ifdef SOCK_RAW - sock_define_const("SOCK_RAW", SOCK_RAW); -#endif -#ifdef SOCK_RDM - sock_define_const("SOCK_RDM", SOCK_RDM); -#endif -#ifdef SOCK_SEQPACKET - sock_define_const("SOCK_SEQPACKET", SOCK_SEQPACKET); -#endif -#ifdef SOCK_PACKET - sock_define_const("SOCK_PACKET", SOCK_PACKET); -#endif - - sock_define_const("AF_INET", AF_INET); -#ifdef PF_INET - sock_define_const("PF_INET", PF_INET); -#endif -#ifdef AF_UNIX - sock_define_const("AF_UNIX", AF_UNIX); - sock_define_const("PF_UNIX", PF_UNIX); -#endif -#ifdef AF_AX25 - sock_define_const("AF_AX25", AF_AX25); - sock_define_const("PF_AX25", PF_AX25); -#endif -#ifdef AF_IPX - sock_define_const("AF_IPX", AF_IPX); - sock_define_const("PF_IPX", PF_IPX); -#endif -#ifdef AF_APPLETALK - sock_define_const("AF_APPLETALK", AF_APPLETALK); - sock_define_const("PF_APPLETALK", PF_APPLETALK); -#endif -#ifdef AF_UNSPEC - sock_define_const("AF_UNSPEC", AF_UNSPEC); - sock_define_const("PF_UNSPEC", PF_UNSPEC); -#endif -#ifdef AF_INET6 - sock_define_const("AF_INET6", AF_INET6); -#endif -#ifdef PF_INET6 - sock_define_const("PF_INET6", PF_INET6); -#endif - - sock_define_const("MSG_OOB", MSG_OOB); -#ifdef MSG_PEEK - sock_define_const("MSG_PEEK", MSG_PEEK); -#endif -#ifdef MSG_DONTROUTE - sock_define_const("MSG_DONTROUTE", MSG_DONTROUTE); -#endif - - sock_define_const("SOL_SOCKET", SOL_SOCKET); -#ifdef SOL_IP - sock_define_const("SOL_IP", SOL_IP); -#endif -#ifdef SOL_IPX - sock_define_const("SOL_IPX", SOL_IPX); -#endif -#ifdef SOL_AX25 - sock_define_const("SOL_AX25", SOL_AX25); -#endif -#ifdef SOL_ATALK - sock_define_const("SOL_ATALK", SOL_ATALK); -#endif -#ifdef SOL_TCP - sock_define_const("SOL_TCP", SOL_TCP); -#endif -#ifdef SOL_UDP - sock_define_const("SOL_UDP", SOL_UDP); -#endif - -#ifdef IPPROTO_IP - sock_define_const("IPPROTO_IP", IPPROTO_IP); -#else - sock_define_const("IPPROTO_IP", 0); -#endif -#ifdef IPPROTO_ICMP - sock_define_const("IPPROTO_ICMP", IPPROTO_ICMP); -#else - sock_define_const("IPPROTO_ICMP", 1); -#endif -#ifdef IPPROTO_IGMP - sock_define_const("IPPROTO_IGMP", IPPROTO_IGMP); -#endif -#ifdef IPPROTO_GGP - sock_define_const("IPPROTO_GGP", IPPROTO_GGP); -#endif -#ifdef IPPROTO_TCP - sock_define_const("IPPROTO_TCP", IPPROTO_TCP); -#else - sock_define_const("IPPROTO_TCP", 6); -#endif -#ifdef IPPROTO_EGP - sock_define_const("IPPROTO_EGP", IPPROTO_EGP); -#endif -#ifdef IPPROTO_PUP - sock_define_const("IPPROTO_PUP", IPPROTO_PUP); -#endif -#ifdef IPPROTO_UDP - sock_define_const("IPPROTO_UDP", IPPROTO_UDP); -#else - sock_define_const("IPPROTO_UDP", 17); -#endif -#ifdef IPPROTO_IDP - sock_define_const("IPPROTO_IDP", IPPROTO_IDP); -#endif -#ifdef IPPROTO_HELLO - sock_define_const("IPPROTO_HELLO", IPPROTO_HELLO); -#endif -#ifdef IPPROTO_ND - sock_define_const("IPPROTO_ND", IPPROTO_ND); -#endif -#ifdef IPPROTO_TP - sock_define_const("IPPROTO_TP", IPPROTO_TP); -#endif -#ifdef IPPROTO_XTP - sock_define_const("IPPROTO_XTP", IPPROTO_XTP); -#endif -#ifdef IPPROTO_EON - sock_define_const("IPPROTO_EON", IPPROTO_EON); -#endif -#ifdef IPPROTO_BIP - sock_define_const("IPPROTO_BIP", IPPROTO_BIP); -#endif -/**/ -#ifdef IPPROTO_RAW - sock_define_const("IPPROTO_RAW", IPPROTO_RAW); -#else - sock_define_const("IPPROTO_RAW", 255); -#endif -#ifdef IPPROTO_MAX - sock_define_const("IPPROTO_MAX", IPPROTO_MAX); -#endif - - /* Some port configuration */ -#ifdef IPPORT_RESERVED - sock_define_const("IPPORT_RESERVED", IPPORT_RESERVED); -#else - sock_define_const("IPPORT_RESERVED", 1024); -#endif -#ifdef IPPORT_USERRESERVED - sock_define_const("IPPORT_USERRESERVED", IPPORT_USERRESERVED); -#else - sock_define_const("IPPORT_USERRESERVED", 5000); -#endif - /* Some reserved IP v.4 addresses */ -#ifdef INADDR_ANY - sock_define_const("INADDR_ANY", INADDR_ANY); -#else - sock_define_const("INADDR_ANY", 0x00000000); -#endif -#ifdef INADDR_BROADCAST - sock_define_const("INADDR_BROADCAST", INADDR_BROADCAST); -#else - sock_define_const("INADDR_BROADCAST", 0xffffffff); -#endif -#ifdef INADDR_LOOPBACK - sock_define_const("INADDR_LOOPBACK", INADDR_LOOPBACK); -#else - sock_define_const("INADDR_LOOPBACK", 0x7F000001); -#endif -#ifdef INADDR_UNSPEC_GROUP - sock_define_const("INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); -#else - sock_define_const("INADDR_UNSPEC_GROUP", 0xe0000000); -#endif -#ifdef INADDR_ALLHOSTS_GROUP - sock_define_const("INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP); -#else - sock_define_const("INADDR_ALLHOSTS_GROUP", 0xe0000001); -#endif -#ifdef INADDR_MAX_LOCAL_GROUP - sock_define_const("INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP); -#else - sock_define_const("INADDR_MAX_LOCAL_GROUP", 0xe00000ff); -#endif -#ifdef INADDR_NONE - sock_define_const("INADDR_NONE", INADDR_NONE); -#else - sock_define_const("INADDR_NONE", 0xffffffff); -#endif - /* IP [gs]etsockopt options */ -#ifdef IP_OPTIONS - sock_define_const("IP_OPTIONS", IP_OPTIONS); -#endif -#ifdef IP_HDRINCL - sock_define_const("IP_HDRINCL", IP_HDRINCL); -#endif -#ifdef IP_TOS - sock_define_const("IP_TOS", IP_TOS); -#endif -#ifdef IP_TTL - sock_define_const("IP_TTL", IP_TTL); -#endif -#ifdef IP_RECVOPTS - sock_define_const("IP_RECVOPTS", IP_RECVOPTS); -#endif -#ifdef IP_RECVRETOPTS - sock_define_const("IP_RECVRETOPTS", IP_RECVRETOPTS); -#endif -#ifdef IP_RECVDSTADDR - sock_define_const("IP_RECVDSTADDR", IP_RECVDSTADDR); -#endif -#ifdef IP_RETOPTS - sock_define_const("IP_RETOPTS", IP_RETOPTS); -#endif -#ifdef IP_MULTICAST_IF - sock_define_const("IP_MULTICAST_IF", IP_MULTICAST_IF); -#endif -#ifdef IP_MULTICAST_TTL - sock_define_const("IP_MULTICAST_TTL", IP_MULTICAST_TTL); -#endif -#ifdef IP_MULTICAST_LOOP - sock_define_const("IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); -#endif -#ifdef IP_ADD_MEMBERSHIP - sock_define_const("IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); -#endif -#ifdef IP_DROP_MEMBERSHIP - sock_define_const("IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); -#endif -#ifdef IP_DEFAULT_MULTICAST_TTL - sock_define_const("IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL); -#endif -#ifdef IP_DEFAULT_MULTICAST_LOOP - sock_define_const("IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP); -#endif -#ifdef IP_MAX_MEMBERSHIPS - sock_define_const("IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); -#endif -#ifdef SO_DEBUG - sock_define_const("SO_DEBUG", SO_DEBUG); -#endif - sock_define_const("SO_REUSEADDR", SO_REUSEADDR); -#ifdef SO_TYPE - sock_define_const("SO_TYPE", SO_TYPE); -#endif -#ifdef SO_ERROR - sock_define_const("SO_ERROR", SO_ERROR); -#endif -#ifdef SO_DONTROUTE - sock_define_const("SO_DONTROUTE", SO_DONTROUTE); -#endif -#ifdef SO_BROADCAST - sock_define_const("SO_BROADCAST", SO_BROADCAST); -#endif -#ifdef SO_SNDBUF - sock_define_const("SO_SNDBUF", SO_SNDBUF); -#endif -#ifdef SO_RCVBUF - sock_define_const("SO_RCVBUF", SO_RCVBUF); -#endif -#ifdef SO_KEEPALIVE - sock_define_const("SO_KEEPALIVE", SO_KEEPALIVE); -#endif -#ifdef SO_OOBINLINE - sock_define_const("SO_OOBINLINE", SO_OOBINLINE); -#endif -#ifdef SO_NO_CHECK - sock_define_const("SO_NO_CHECK", SO_NO_CHECK); -#endif -#ifdef SO_PRIORITY - sock_define_const("SO_PRIORITY", SO_PRIORITY); -#endif -#ifdef SO_LINGER - sock_define_const("SO_LINGER", SO_LINGER); -#endif -#ifdef SO_PASSCRED - sock_define_const("SO_PASSCRED", SO_PASSCRED); -#endif -#ifdef SO_PEERCRED - sock_define_const("SO_PEERCRED", SO_PEERCRED); -#endif -#ifdef SO_RCVLOWAT - sock_define_const("SO_RCVLOWAT", SO_RCVLOWAT); -#endif -#ifdef SO_SNDLOWAT - sock_define_const("SO_SNDLOWAT", SO_SNDLOWAT); -#endif -#ifdef SO_RCVTIMEO - sock_define_const("SO_RCVTIMEO", SO_RCVTIMEO); -#endif -#ifdef SO_SNDTIMEO - sock_define_const("SO_SNDTIMEO", SO_SNDTIMEO); -#endif - -#ifdef SO_SECURITY_AUTHENTICATION - sock_define_const("SO_SECURITY_AUTHENTICATION", SO_SECURITY_AUTHENTICATION); -#endif -#ifdef SO_SECURITY_ENCRYPTION_TRANSPORT - sock_define_const("SO_SECURITY_ENCRYPTION_TRANSPORT", SO_SECURITY_ENCRYPTION_TRANSPORT); -#endif -#ifdef SO_SECURITY_ENCRYPTION_NETWORK - sock_define_const("SO_SECURITY_ENCRYPTION_NETWORK", SO_SECURITY_ENCRYPTION_NETWORK); -#endif - -#ifdef SO_BINDTODEVICE - sock_define_const("SO_BINDTODEVICE", SO_BINDTODEVICE); -#endif -#ifdef SO_ATTACH_FILTER - sock_define_const("SO_ATTACH_FILTER", SO_ATTACH_FILTER); -#endif -#ifdef SO_DETACH_FILTER - sock_define_const("SO_DETACH_FILTER", SO_DETACH_FILTER); -#endif -#ifdef SO_PEERNAME - sock_define_const("SO_PEERNAME", SO_PEERNAME); -#endif -#ifdef SO_TIMESTAMP - sock_define_const("SO_TIMESTAMP", SO_TIMESTAMP); -#endif - -#ifdef SOPRI_INTERACTIVE - sock_define_const("SOPRI_INTERACTIVE", SOPRI_INTERACTIVE); -#endif -#ifdef SOPRI_NORMAL - sock_define_const("SOPRI_NORMAL", SOPRI_NORMAL); -#endif -#ifdef SOPRI_BACKGROUND - sock_define_const("SOPRI_BACKGROUND", SOPRI_BACKGROUND); -#endif - -#ifdef IPX_TYPE - sock_define_const("IPX_TYPE", IPX_TYPE); -#endif - -#ifdef TCP_NODELAY - sock_define_const("TCP_NODELAY", TCP_NODELAY); -#endif -#ifdef TCP_MAXSEG - sock_define_const("TCP_MAXSEG", TCP_MAXSEG); -#endif - -#ifdef EAI_ADDRFAMILY - sock_define_const("EAI_ADDRFAMILY", EAI_ADDRFAMILY); -#endif -#ifdef EAI_AGAIN - sock_define_const("EAI_AGAIN", EAI_AGAIN); -#endif -#ifdef EAI_BADFLAGS - sock_define_const("EAI_BADFLAGS", EAI_BADFLAGS); -#endif -#ifdef EAI_FAIL - sock_define_const("EAI_FAIL", EAI_FAIL); -#endif -#ifdef EAI_FAMILY - sock_define_const("EAI_FAMILY", EAI_FAMILY); -#endif -#ifdef EAI_MEMORY - sock_define_const("EAI_MEMORY", EAI_MEMORY); -#endif -#ifdef EAI_NODATA - sock_define_const("EAI_NODATA", EAI_NODATA); -#endif -#ifdef EAI_NONAME - sock_define_const("EAI_NONAME", EAI_NONAME); -#endif -#ifdef EAI_SERVICE - sock_define_const("EAI_SERVICE", EAI_SERVICE); -#endif -#ifdef EAI_SOCKTYPE - sock_define_const("EAI_SOCKTYPE", EAI_SOCKTYPE); -#endif -#ifdef EAI_SYSTEM - sock_define_const("EAI_SYSTEM", EAI_SYSTEM); -#endif -#ifdef EAI_BADHINTS - sock_define_const("EAI_BADHINTS", EAI_BADHINTS); -#endif -#ifdef EAI_PROTOCOL - sock_define_const("EAI_PROTOCOL", EAI_PROTOCOL); -#endif -#ifdef EAI_MAX - sock_define_const("EAI_MAX", EAI_MAX); -#endif -#ifdef AI_PASSIVE - sock_define_const("AI_PASSIVE", AI_PASSIVE); -#endif -#ifdef AI_CANONNAME - sock_define_const("AI_CANONNAME", AI_CANONNAME); -#endif -#ifdef AI_NUMERICHOST - sock_define_const("AI_NUMERICHOST", AI_NUMERICHOST); -#endif -#ifdef AI_MASK - sock_define_const("AI_MASK", AI_MASK); -#endif -#ifdef AI_ALL - sock_define_const("AI_ALL", AI_ALL); -#endif -#ifdef AI_V4MAPPED_CFG - sock_define_const("AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); -#endif -#ifdef AI_ADDRCONFIG - sock_define_const("AI_ADDRCONFIG", AI_ADDRCONFIG); -#endif -#ifdef AI_V4MAPPED - sock_define_const("AI_V4MAPPED", AI_V4MAPPED); -#endif -#ifdef AI_DEFAULT - sock_define_const("AI_DEFAULT", AI_DEFAULT); -#endif -#ifdef NI_MAXHOST - sock_define_const("NI_MAXHOST", NI_MAXHOST); -#endif -#ifdef NI_MAXSERV - sock_define_const("NI_MAXSERV", NI_MAXSERV); -#endif -#ifdef NI_NOFQDN - sock_define_const("NI_NOFQDN", NI_NOFQDN); -#endif -#ifdef NI_NUMERICHOST - sock_define_const("NI_NUMERICHOST", NI_NUMERICHOST); -#endif -#ifdef NI_NAMEREQD - sock_define_const("NI_NAMEREQD", NI_NAMEREQD); -#endif -#ifdef NI_NUMERICSERV - sock_define_const("NI_NUMERICSERV", NI_NUMERICSERV); -#endif -#ifdef NI_DGRAM - sock_define_const("NI_DGRAM", NI_DGRAM); -#endif -} diff --git a/ext/socket/sockport.h b/ext/socket/sockport.h deleted file mode 100644 index e1cddf53f4..0000000000 --- a/ext/socket/sockport.h +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************ - - sockport.h - - - $Author$ - $Date$ - created at: Fri Apr 30 23:19:34 JST 1999 - -************************************************/ - -#ifndef SOCKPORT_H -#define SOCKPORT_H - -#ifndef SA_LEN -# ifdef HAVE_SA_LEN -# define SA_LEN(sa) (sa)->sa_len -# else -# ifdef INET6 -# define SA_LEN(sa) \ - (((sa)->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) \ - : sizeof(struct sockaddr)) -# else - /* by tradition, sizeof(struct sockaddr) covers most of the sockaddrs */ -# define SA_LEN(sa) (sizeof(struct sockaddr)) -# endif -# endif -#endif - -#ifdef HAVE_SA_LEN -# define SET_SA_LEN(sa, len) (sa)->sa_len = (len) -#else -# define SET_SA_LEN(sa, len) (len) -#endif - -#ifdef HAVE_SIN_LEN -# define SIN_LEN(si) (si)->sin_len -# define SET_SIN_LEN(si,len) (si)->sin_len = (len) -#else -# define SIN_LEN(si) sizeof(struct sockaddr_in) -# define SET_SIN_LEN(si,len) -#endif - -#ifndef IN_MULTICAST -# define IN_CLASSD(i) (((long)(i) & 0xf0000000) == 0xe0000000) -# define IN_MULTICAST(i) IN_CLASSD(i) -#endif - -#ifndef IN_EXPERIMENTAL -# define IN_EXPERIMENTAL(i) ((((long)(i)) & 0xe0000000) == 0xe0000000) -#endif - -#ifndef IN_CLASSA_NSHIFT -# define IN_CLASSA_NSHIFT 24 -#endif - -#ifndef IN_LOOPBACKNET -# define IN_LOOPBACKNET 127 -#endif - -#ifndef AF_UNSPEC -# define AF_UNSPEC 0 -#endif - -#ifndef PF_UNSPEC -# define PF_UNSPEC AF_UNSPEC -#endif - -#ifndef PF_INET -# define PF_INET AF_INET -#endif - -#if defined(HOST_NOT_FOUND) && !defined(h_errno) && !defined(__CYGWIN__) -extern int h_errno; -#endif - -#endif diff --git a/ext/stringio/MANIFEST b/ext/stringio/MANIFEST deleted file mode 100644 index 4f3a7dc6d0..0000000000 --- a/ext/stringio/MANIFEST +++ /dev/null @@ -1,4 +0,0 @@ -MANIFEST -README -stringio.c -depend diff --git a/ext/stringio/README b/ext/stringio/README deleted file mode 100644 index c4031f7e97..0000000000 --- a/ext/stringio/README +++ /dev/null @@ -1,19 +0,0 @@ --*- rd -*- -$Author$ -$Date$ - -=begin - -= StringIO -Pseudo (({IO})) class from/to (({String})). - -This library is based on MoonWolf version written in Ruby. Thanks a lot. - -= Differences to (({IO})) - -* not implemented: (({fcntl})), (({reopen})). -* (({fileno})) returns nil. -* (({pos=})) returns new position, not 0. -* (({ungetc})) does nothing at start of the string. - -=end diff --git a/ext/stringio/depend b/ext/stringio/depend deleted file mode 100644 index cc9eae3f55..0000000000 --- a/ext/stringio/depend +++ /dev/null @@ -1,2 +0,0 @@ -stringio.o: stringio.c $(hdrdir)/ruby.h $(topdir)/config.h \ - $(hdrdir)/defines.h $(hdrdir)/intern.h $(hdrdir)/rubyio.h diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c deleted file mode 100644 index 27b8aba8ba..0000000000 --- a/ext/stringio/stringio.c +++ /dev/null @@ -1,920 +0,0 @@ -/********************************************************************** - - stringio.c - - - $Author$ - $Date$ - $RoughId: stringio.c,v 1.13 2002/03/14 03:24:18 nobu Exp $ - created at: Tue Feb 19 04:10:38 JST 2002 - - All the files in this distribution are covered under the Ruby's - license (see the file COPYING). - -**********************************************************************/ - -#include "ruby.h" -#include "rubyio.h" - -#define STRIO_APPEND 4 - -struct StringIO { - VALUE string; - long pos; - long lineno; - int flags; - int count; -}; - -static struct StringIO* strio_alloc _((void)); -static void strio_mark _((struct StringIO *)); -static void strio_free _((struct StringIO *)); -static struct StringIO* check_strio _((VALUE)); -static struct StringIO* get_strio _((VALUE)); -static struct StringIO* readable _((struct StringIO *)); -static struct StringIO* writable _((struct StringIO *)); -static void check_modifiable _((struct StringIO *)); - -#define IS_STRIO(obj) (RDATA(obj)->dmark == (RUBY_DATA_FUNC)strio_mark) -#define error_inval(msg) (errno = EINVAL, rb_sys_fail(msg)) - -static struct StringIO * -strio_alloc() -{ - struct StringIO *ptr = ALLOC(struct StringIO); - ptr->string = Qnil; - ptr->pos = 0; - ptr->lineno = 0; - ptr->flags = 0; - ptr->count = 1; - return ptr; -} - -static void -strio_mark(ptr) - struct StringIO *ptr; -{ - rb_gc_mark(ptr->string); -} - -static void -strio_free(ptr) - struct StringIO *ptr; -{ - if (--ptr->count <= 0) { - xfree(ptr); - } -} - -static struct StringIO* -check_strio(self) - VALUE self; -{ - Check_Type(self, T_DATA); - if (!IS_STRIO(self)) { - rb_raise(rb_eTypeError, "wrong argument type %s (expected String::IO)", - rb_class2name(CLASS_OF(self))); - } - return DATA_PTR(self); -} - -static struct StringIO* -get_strio(self) - VALUE self; -{ - struct StringIO *ptr = check_strio(self); - - if (!ptr) { - rb_raise(rb_eIOError, "uninitialized stream"); - } - return ptr; -} - -#define StringIO(obj) get_strio(obj) - -#define CLOSED(ptr) NIL_P((ptr)->string) -#define READABLE(ptr) (!CLOSED(ptr) && ((ptr)->flags & FMODE_READABLE)) -#define WRITABLE(ptr) (!CLOSED(ptr) && ((ptr)->flags & FMODE_WRITABLE)) - -static struct StringIO* -readable(ptr) - struct StringIO *ptr; -{ - if (!READABLE(ptr)) { - rb_raise(rb_eIOError, "not opened for reading"); - } - return ptr; -} - -static struct StringIO* -writable(ptr) - struct StringIO *ptr; -{ - if (!WRITABLE(ptr)) { - rb_raise(rb_eIOError, "not opened for writing"); - } - if (!OBJ_TAINTED(ptr->string)) { - rb_secure(4); - } - return ptr; -} - -static void -check_modifiable(ptr) - struct StringIO *ptr; -{ - if (OBJ_FROZEN(ptr->string)) { - rb_raise(rb_eIOError, "not modifiable string"); - } - rb_str_modify(ptr->string); -} - -static VALUE strio_s_allocate _((VALUE)); -static VALUE strio_s_open _((int, VALUE *, VALUE)); -static VALUE strio_initialize _((int, VALUE *, VALUE)); -static VALUE strio_finalize _((VALUE)); -static VALUE strio_self _((VALUE)); -static VALUE strio_false _((VALUE)); -static VALUE strio_nil _((VALUE)); -static VALUE strio_0 _((VALUE)); -static VALUE strio_first _((VALUE, VALUE)); -static VALUE strio_unimpl _((int, VALUE *, VALUE)); -static VALUE strio_get_string _((VALUE)); -static VALUE strio_set_string _((VALUE, VALUE)); -static VALUE strio_close _((VALUE)); -static VALUE strio_close_read _((VALUE)); -static VALUE strio_close_write _((VALUE)); -static VALUE strio_closed _((VALUE)); -static VALUE strio_closed_read _((VALUE)); -static VALUE strio_closed_write _((VALUE)); -static VALUE strio_eof _((VALUE)); -static VALUE strio_clone _((VALUE)); -static VALUE strio_get_lineno _((VALUE)); -static VALUE strio_set_lineno _((VALUE, VALUE)); -static VALUE strio_get_pos _((VALUE)); -static VALUE strio_set_pos _((VALUE, VALUE)); -static VALUE strio_rewind _((VALUE)); -static VALUE strio_seek _((int, VALUE *, VALUE)); -static VALUE strio_get_sync _((VALUE)); -static VALUE strio_set_sync _((VALUE, VALUE)); -static VALUE strio_each_byte _((VALUE)); -static VALUE strio_getc _((VALUE)); -static VALUE strio_ungetc _((VALUE, VALUE)); -static VALUE strio_readchar _((VALUE)); -static VALUE strio_gets_internal _((int, VALUE *, struct StringIO *)); -static VALUE strio_gets _((int, VALUE *, VALUE)); -static VALUE strio_readline _((int, VALUE *, VALUE)); -static VALUE strio_each _((int, VALUE *, VALUE)); -static VALUE strio_readlines _((int, VALUE *, VALUE)); -static VALUE strio_write _((VALUE, VALUE)); -static VALUE strio_print _((int, VALUE *, VALUE)); -static VALUE strio_printf _((int, VALUE *, VALUE)); -static VALUE strio_putc _((VALUE, VALUE)); -static VALUE strio_read _((int, VALUE *, VALUE)); -static VALUE strio_size _((VALUE)); -static VALUE strio_truncate _((VALUE, VALUE)); -void Init_stringio _((void)); - -/* Boyer-Moore search: copied from regex.c */ -static void bm_init_skip _((long *, const char *, long)); -static long bm_search _((const char *, long, const char *, long, const long *)); - -static VALUE -strio_s_allocate(klass) - VALUE klass; -{ - struct StringIO *ptr; - return Data_Wrap_Struct(klass, strio_mark, strio_free, 0); -} - -static VALUE -strio_s_open(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = rb_class_new_instance(argc, argv, klass); - if (!rb_block_given_p()) return obj; - return rb_ensure(rb_yield, obj, strio_finalize, obj); -} - -static VALUE -strio_initialize(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - struct StringIO *ptr = check_strio(self); - VALUE string, mode; - - if (!ptr) { - DATA_PTR(self) = ptr = strio_alloc(); - } - rb_call_super(0, 0); - switch (rb_scan_args(argc, argv, "02", &string, &mode)) { - case 2: - StringValue(mode); - StringValue(string); - ptr->flags = rb_io_mode_flags(RSTRING(mode)->ptr); - if (ptr->flags & FMODE_WRITABLE && OBJ_FROZEN(string)) { - errno = EACCES; - rb_sys_fail(0); - } - switch (*RSTRING(mode)->ptr) { - case 'a': - ptr->flags |= STRIO_APPEND; - break; - case 'w': - rb_str_resize(string, 0); - break; - } - break; - case 1: - StringValue(string); - ptr->flags = OBJ_FROZEN(string) ? FMODE_READABLE : FMODE_READWRITE; - break; - case 0: - string = rb_str_new("", 0); - ptr->flags = FMODE_READWRITE; - break; - } - ptr->string = string; - return self; -} - -static VALUE -strio_finalize(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - ptr->string = Qnil; - ptr->flags &= ~FMODE_READWRITE; - return self; -} - -static VALUE -strio_false(self) - VALUE self; -{ - StringIO(self); - return Qfalse; -} - -static VALUE -strio_nil(self) - VALUE self; -{ - StringIO(self); - return Qnil; -} - -static VALUE -strio_self(self) - VALUE self; -{ - StringIO(self); - return self; -} - -static VALUE -strio_0(self) - VALUE self; -{ - StringIO(self); - return INT2FIX(0); -} - -static VALUE -strio_first(self, arg) - VALUE self, arg; -{ - StringIO(self); - return arg; -} - -static VALUE -strio_unimpl(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - StringIO(self); - rb_notimplement(); - return Qnil; /* not reached */ -} - -static VALUE -strio_get_string(self) - VALUE self; -{ - return StringIO(self)->string; -} - -static VALUE -strio_set_string(self, string) - VALUE self, string; -{ - struct StringIO *ptr = StringIO(self); - - if (NIL_P(string)) { - ptr->flags &= ~FMODE_READWRITE; - } - else { - StringValue(string); - ptr->flags |= FMODE_READWRITE; - } - return ptr->string = string; -} - -static VALUE -strio_close(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - if (CLOSED(ptr)) { - rb_raise(rb_eIOError, "closed stream"); - } - ptr->string = Qnil; - ptr->flags &= ~FMODE_READWRITE; - return self; -} - -static VALUE -strio_close_read(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - if (!READABLE(ptr)) { - rb_raise(rb_eIOError, "closing non-duplex IO for reading"); - } - if (!((ptr->flags &= ~FMODE_READABLE) & FMODE_READWRITE)) { - ptr->string = Qnil; - } - return self; -} - -static VALUE -strio_close_write(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - if (!WRITABLE(ptr)) { - rb_raise(rb_eIOError, "closing non-duplex IO for writing"); - } - if (!((ptr->flags &= ~FMODE_WRITABLE) & FMODE_READWRITE)) { - ptr->string = Qnil; - } - return self; -} - -static VALUE -strio_closed(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - if (!CLOSED(ptr)) return Qfalse; - return Qtrue; -} - -static VALUE -strio_closed_read(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - if (READABLE(ptr)) return Qfalse; - return Qtrue; -} - -static VALUE -strio_closed_write(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - if (WRITABLE(ptr)) return Qfalse; - return Qtrue; -} - -static VALUE -strio_eof(self) - VALUE self; -{ - struct StringIO *ptr = readable(StringIO(self)); - if (ptr->pos < RSTRING(ptr->string)->len) return Qfalse; - return Qtrue; -} - -static VALUE -strio_clone(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - VALUE clone = rb_call_super(0, 0); - DATA_PTR(clone) = ptr; - ++ptr->count; - return self; -} - -static VALUE -strio_get_lineno(self) - VALUE self; -{ - return LONG2NUM(StringIO(self)->lineno); -} - -static VALUE -strio_set_lineno(self, lineno) - VALUE self, lineno; -{ - StringIO(self)->lineno = NUM2LONG(lineno); - return lineno; -} - -#define strio_binmode strio_self - -#define strio_reopen strio_unimpl - -#define strio_fcntl strio_unimpl - -#define strio_flush strio_self - -#define strio_fsync strio_0 - -static VALUE -strio_get_pos(self) - VALUE self; -{ - return LONG2NUM(StringIO(self)->pos); -} - -static VALUE -strio_set_pos(self, pos) - VALUE self; - VALUE pos; -{ - struct StringIO *ptr = StringIO(self); - long p = NUM2LONG(pos); - if (p < 0) { - error_inval(0); - } - ptr->pos = p; - return pos; -} - -static VALUE -strio_rewind(self) - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - ptr->pos = 0; - ptr->lineno = 0; - return INT2FIX(0); -} - -static VALUE -strio_seek(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - VALUE whence; - struct StringIO *ptr = StringIO(self); - long offset; - - rb_scan_args(argc, argv, "11", NULL, &whence); - offset = NUM2LONG(argv[0]); - switch (NIL_P(whence) ? 0 : NUM2LONG(whence)) { - case 0: - break; - case 1: - offset += ptr->pos; - break; - case 2: - offset += RSTRING(ptr->string)->len; - break; - default: - rb_raise(rb_eArgError, "invalid whence %ld", NUM2LONG(whence)); - } - if (offset < 0) { - error_inval(0); - } - ptr->pos = offset; - return INT2FIX(0); -} - -static VALUE -strio_get_sync(self) - VALUE self; -{ - StringIO(self); - return Qtrue; -} - -#define strio_set_sync strio_first - -#define strio_tell strio_get_pos - -static VALUE -strio_each_byte(self) - VALUE self; -{ - struct StringIO *ptr = readable(StringIO(self)); - while (ptr->pos < RSTRING(ptr->string)->len) { - char c = RSTRING(ptr->string)->ptr[ptr->pos++]; - rb_yield(CHR2FIX(c)); - } - return Qnil; -} - -static VALUE -strio_getc(self) - VALUE self; -{ - struct StringIO *ptr = readable(StringIO(self)); - int c; - if (ptr->pos >= RSTRING(ptr->string)->len) { - return Qnil; - } - c = RSTRING(ptr->string)->ptr[ptr->pos++]; - return CHR2FIX(c); -} - -static VALUE -strio_ungetc(self, ch) - VALUE self, ch; -{ - struct StringIO *ptr = readable(StringIO(self)); - int cc = NUM2INT(ch); - - if (cc != EOF && ptr->pos > 0) { - if ((unsigned char)RSTRING(ptr->string)->ptr[--ptr->pos] != - (unsigned char)cc) { - check_modifiable(ptr); - RSTRING(ptr->string)->ptr[ptr->pos] = cc; - } - } - return Qnil; -} - -static VALUE -strio_readchar(self) - VALUE self; -{ - VALUE c = strio_getc(self); - if (NIL_P(c)) rb_eof_error(); - return c; -} - -static void -bm_init_skip(skip, pat, m) - long *skip; - const char *pat; - long m; -{ - int c; - - for (c = 0; c < (1 << CHAR_BIT); c++) { - skip[c] = m; - } - while (--m) { - skip[(unsigned char)*pat++] = m; - } -} - -static long -bm_search(little, llen, big, blen, skip) - const char *little; - long llen; - const char *big; - long blen; - const long *skip; -{ - long i, j, k; - - i = llen - 1; - while (i < blen) { - k = i; - j = llen - 1; - while (j >= 0 && big[k] == little[j]) { - k--; - j--; - } - if (j < 0) return k + 1; - i += skip[(unsigned char)big[i]]; - } - return -1; -} - -static VALUE -strio_gets_internal(argc, argv, ptr) - int argc; - VALUE *argv; - struct StringIO *ptr; -{ - const char *s, *e, *p; - long n; - VALUE str; - - if (argc == 0) { - str = rb_rs; - } - else { - rb_scan_args(argc, argv, "1", &str); - if (!NIL_P(str)) StringValue(str); - } - - if (ptr->pos >= (n = RSTRING(ptr->string)->len)) return Qnil; - s = RSTRING(ptr->string)->ptr; - e = s + RSTRING(ptr->string)->len; - s += ptr->pos; - if (NIL_P(str)) { - str = rb_str_substr(ptr->string, ptr->pos, e - s); - } - else if ((n = RSTRING(str)->len) == 0) { - p = s; - while (*p == '\n') { - if (++p == e) return Qnil; - } - s = p; - while (p = memchr(p, '\n', e - p)) { - if (p == e) break; - if (*++p == '\n') { - e = p; - break; - } - } - str = rb_str_substr(ptr->string, s - RSTRING(ptr->string)->ptr, e - s); - } - else if (n == 1) { - if (p = memchr(s, RSTRING(str)->ptr[0], e - s)) { - e = p + 1; - } - str = rb_str_substr(ptr->string, ptr->pos, e - s); - } - else { - if (n < s - e) { - if (s - e < 1024) { - for (p = s; p + n <= e; ++p) { - if (MEMCMP(p, RSTRING(str)->ptr, char, n) == 0) { - e = p + n; - break; - } - } - } - else { - long skip[1 << CHAR_BIT], pos; - p = RSTRING(str)->ptr; - bm_init_skip(skip, p, n); - if ((pos = bm_search(p, n, s, e - s, skip)) >= 0) { - e = s + pos + n; - } - } - } - str = rb_str_substr(ptr->string, ptr->pos, e - s); - } - ptr->pos = e - RSTRING(ptr->string)->ptr; - ptr->lineno++; - rb_lastline_set(str); - return str; -} - -static VALUE -strio_gets(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - return strio_gets_internal(argc, argv, readable(StringIO(self))); -} - -static VALUE -strio_readline(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - VALUE line = strio_gets_internal(argc, argv, readable(StringIO(self))); - if (NIL_P(line)) rb_eof_error(); - return line; -} - -static VALUE -strio_each(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - VALUE line; - - while (!NIL_P(line = strio_gets_internal(argc, argv, readable(ptr)))) { - rb_yield(line); - } - return self; -} - -static VALUE -strio_readlines(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - struct StringIO *ptr = StringIO(self); - VALUE ary = rb_ary_new(), line; - while (!NIL_P(line = strio_gets_internal(argc, argv, readable(ptr)))) { - rb_ary_push(ary, line); - } - return ary; -} - -static VALUE -strio_write(self, str) - VALUE self, str; -{ - struct StringIO *ptr = writable(StringIO(self)); - long len; - - if (TYPE(str) != T_STRING) - str = rb_obj_as_string(str); - len = RSTRING(str)->len; - if (!len) return INT2FIX(0); - check_modifiable(ptr); - if (ptr->flags & STRIO_APPEND) { - ptr->pos = RSTRING(ptr->string)->len; - } - if (ptr->pos + len > RSTRING(ptr->string)->len) { - rb_str_resize(ptr->string, ptr->pos + len); - } - rb_str_update(ptr->string, ptr->pos, len, str); - ptr->pos += len; - return LONG2NUM(len); -} - -#define strio_addstr rb_io_addstr - -#define strio_print rb_io_print - -#define strio_printf rb_io_printf - -static VALUE -strio_putc(self, ch) - VALUE self, ch; -{ - struct StringIO *ptr = writable(StringIO(self)); - int c = NUM2CHR(ch); - - check_modifiable(ptr); - if (ptr->flags & STRIO_APPEND) { - ptr->pos = RSTRING(ptr->string)->len; - } - if (ptr->pos >= RSTRING(ptr->string)->len) { - rb_str_resize(ptr->string, ptr->pos + 1); - } - RSTRING(ptr->string)->ptr[ptr->pos++] = c; - return ch; -} - -#define strio_puts rb_io_puts - -static VALUE -strio_read(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - struct StringIO *ptr = readable(StringIO(self)); - VALUE str; - long len; - - if (ptr->pos >= RSTRING(ptr->string)->len) { - return Qnil; - } - switch (argc) { - case 1: - if (!NIL_P(argv[0])) { - len = NUM2LONG(argv[0]); - break; - } - /* fall through */ - case 0: - len = RSTRING(ptr->string)->len - ptr->pos; - break; - default: - rb_raise(rb_eArgError, "wrong number arguments (%d for 0)", argc); - } - str = rb_str_substr(ptr->string, ptr->pos, len); - ptr->pos += len; - return str; -} - -static VALUE -strio_sysread(argc, argv, self) - int argc; - VALUE *argv; - VALUE self; -{ - VALUE val = strio_read(argc, argv, self); - if (NIL_P(val)) { - rb_eof_error(); - } - return val; -} - -#define strio_syswrite strio_write - -#define strio_path rb_inspect - -#define strio_isatty strio_false - -#define strio_pid strio_nil - -#define strio_fileno strio_nil - -static VALUE -strio_size(self) - VALUE self; -{ - VALUE string = StringIO(self)->string; - if (NIL_P(string)) { - rb_raise(rb_eIOError, "not opened"); - } - return ULONG2NUM(RSTRING(string)->len); -} - -static VALUE -strio_truncate(self, len) - VALUE self, len; -{ - VALUE string = writable(StringIO(self))->string; - long l = NUM2LONG(len); - if (l < 0) { - error_inval("negative legnth"); - } - rb_str_resize(string, l); - return len; -} - -void -Init_stringio() -{ - VALUE StringIO = rb_define_class("StringIO", rb_cData); - rb_define_singleton_method(StringIO, "allocate", strio_s_allocate, 0); - rb_define_singleton_method(StringIO, "open", strio_s_open, -1); - rb_define_method(StringIO, "initialize", strio_initialize, -1); - rb_enable_super(StringIO, "initialize"); - rb_define_method(StringIO, "clone", strio_clone, 0); - rb_enable_super(StringIO, "clone"); - rb_define_method(StringIO, "reopen", strio_reopen, -1); - - rb_define_method(StringIO, "string", strio_get_string, 0); - rb_define_method(StringIO, "string=", strio_set_string, 1); - rb_define_method(StringIO, "lineno", strio_get_lineno, 0); - rb_define_method(StringIO, "lineno=", strio_set_lineno, 1); - - rb_define_method(StringIO, "binmode", strio_binmode, 0); - rb_define_method(StringIO, "close", strio_close, 0); - rb_define_method(StringIO, "close_read", strio_close_read, 0); - rb_define_method(StringIO, "close_write", strio_close_write, 0); - rb_define_method(StringIO, "closed?", strio_closed, 0); - rb_define_method(StringIO, "closed_read?", strio_closed_read, 0); - rb_define_method(StringIO, "closed_write?", strio_closed_write, 0); - rb_define_method(StringIO, "eof", strio_eof, 0); - rb_define_method(StringIO, "eof?", strio_eof, 0); - rb_define_method(StringIO, "fcntl", strio_fcntl, -1); - rb_define_method(StringIO, "flush", strio_flush, 0); - rb_define_method(StringIO, "fsync", strio_fsync, 0); - rb_define_method(StringIO, "pos", strio_get_pos, 0); - rb_define_method(StringIO, "pos=", strio_set_pos, 1); - rb_define_method(StringIO, "rewind", strio_rewind, 0); - rb_define_method(StringIO, "seek", strio_seek, -1); - rb_define_method(StringIO, "sync", strio_get_sync, 0); - rb_define_method(StringIO, "sync=", strio_set_sync, 1); - rb_define_method(StringIO, "tell", strio_tell, 0); - rb_define_method(StringIO, "path", strio_path, 0); - - rb_define_method(StringIO, "each", strio_each, -1); - rb_define_method(StringIO, "each_byte", strio_each_byte, 0); - rb_define_method(StringIO, "each_line", strio_each, -1); - rb_define_method(StringIO, "getc", strio_getc, 0); - rb_define_method(StringIO, "ungetc", strio_ungetc, 1); - rb_define_method(StringIO, "readchar", strio_readchar, 0); - rb_define_method(StringIO, "gets", strio_gets, -1); - rb_define_method(StringIO, "readline", strio_readline, -1); - rb_define_method(StringIO, "readlines", strio_readlines, -1); - rb_define_method(StringIO, "read", strio_read, -1); - rb_define_method(StringIO, "sysread", strio_sysread, -1); - - rb_define_method(StringIO, "write", strio_write, 1); - rb_define_method(StringIO, "<<", strio_addstr, 1); - rb_define_method(StringIO, "print", strio_print, -1); - rb_define_method(StringIO, "printf", strio_printf, -1); - rb_define_method(StringIO, "putc", strio_putc, 1); - rb_define_method(StringIO, "puts", strio_puts, -1); - rb_define_method(StringIO, "syswrite", strio_syswrite, 1); - - rb_define_method(StringIO, "isatty", strio_isatty, 0); - rb_define_method(StringIO, "tty?", strio_isatty, 0); - rb_define_method(StringIO, "pid", strio_pid, 0); - rb_define_method(StringIO, "fileno", strio_fileno, 0); - rb_define_method(StringIO, "size", strio_size, 0); - rb_define_method(StringIO, "length", strio_size, 0); - rb_define_method(StringIO, "truncate", strio_truncate, 1); -} diff --git a/ext/syslog/.cvsignore b/ext/syslog/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/syslog/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/syslog/MANIFEST b/ext/syslog/MANIFEST deleted file mode 100644 index b5306034b7..0000000000 --- a/ext/syslog/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -MANIFEST -extconf.rb -syslog.c -syslog.txt -test.rb -depend diff --git a/ext/syslog/depend b/ext/syslog/depend deleted file mode 100644 index 45cbea293a..0000000000 --- a/ext/syslog/depend +++ /dev/null @@ -1,2 +0,0 @@ -syslog.o: syslog.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h \ - $(hdrdir)/intern.h diff --git a/ext/syslog/extconf.rb b/ext/syslog/extconf.rb deleted file mode 100644 index 0fa0bc339b..0000000000 --- a/ext/syslog/extconf.rb +++ /dev/null @@ -1,10 +0,0 @@ -# $RoughId: extconf.rb,v 1.3 2001/11/24 17:49:26 knu Exp $ -# $Id$ - -require 'mkmf' - -have_header("syslog.h") && - have_func("openlog") && - have_func("setlogmask") && - create_makefile("syslog") - diff --git a/ext/syslog/syslog.c b/ext/syslog/syslog.c deleted file mode 100644 index 22e1e02a87..0000000000 --- a/ext/syslog/syslog.c +++ /dev/null @@ -1,381 +0,0 @@ -/* - * UNIX Syslog extension for Ruby - * Amos Gouaux, University of Texas at Dallas - * - * - * $RoughId: syslog.c,v 1.21 2002/02/25 12:21:17 knu Exp $ - * $Id$ - */ - -#include "ruby.h" -#include - -/* Syslog class */ -static VALUE mSyslog, mSyslogConstants; -static VALUE syslog_ident = Qnil, syslog_options = INT2FIX(-1), - syslog_facility = INT2FIX(-1), syslog_mask = INT2FIX(-1); -static int syslog_opened = 0; - -/* Package helper routines */ -static void syslog_write(int pri, int argc, VALUE *argv) -{ - VALUE str; - - if (argc < 1) { - rb_raise(rb_eArgError, "no log message supplied"); - } - - if (!syslog_opened) { - rb_raise(rb_eRuntimeError, "must open syslog before write"); - } - - str = rb_f_sprintf(argc, argv); - - syslog(pri, "%s", RSTRING(str)->ptr); -} - -/* Syslog module methods */ -static VALUE mSyslog_close(VALUE self) -{ - closelog(); - syslog_opened = 0; - - return Qnil; -} - -static VALUE mSyslog_open(int argc, VALUE *argv, VALUE self) -{ - VALUE ident, opt, fac; - int mask; - - if (syslog_opened) { - rb_raise(rb_eRuntimeError, "syslog already open"); - } - rb_scan_args(argc, argv, "03", &ident, &opt, &fac); - if (NIL_P(ident)) { - ident = rb_gv_get("$0"); - } - if (NIL_P(opt)) { - opt = INT2NUM(LOG_PID | LOG_CONS); - } - if (NIL_P(fac)) { - fac = INT2NUM(LOG_USER); - } - -#ifdef SafeStringValue - SafeStringValue(ident); -#else - Check_SafeStr(ident); -#endif - syslog_ident = ident; - syslog_options = opt; - syslog_facility = fac; - openlog(RSTRING(ident)->ptr, NUM2INT(opt), NUM2INT(fac)); - syslog_opened = 1; - - setlogmask(mask = setlogmask(0)); - syslog_mask = INT2NUM(mask); - - /* be like File.new.open {...} */ - if (rb_block_given_p()) { - rb_ensure(rb_yield, self, mSyslog_close, self); - } - - return self; -} - -static VALUE mSyslog_reopen(int argc, VALUE *argv, VALUE self) -{ - mSyslog_close(self); - - return mSyslog_open(argc, argv, self); -} - -static VALUE mSyslog_isopen(VALUE self) -{ - return syslog_opened ? Qtrue : Qfalse; -} - -static VALUE mSyslog_ident(VALUE self) -{ - return syslog_ident; -} - -static VALUE mSyslog_options(VALUE self) -{ - return syslog_options; -} - -static VALUE mSyslog_facility(VALUE self) -{ - return syslog_facility; -} - -static VALUE mSyslog_get_mask(VALUE self) -{ - return syslog_mask; -} - -static VALUE mSyslog_set_mask(VALUE self, VALUE mask) -{ - if (!syslog_opened) { - rb_raise(rb_eRuntimeError, "must open syslog before setting log mask"); - } - - setlogmask(NUM2INT(mask)); - syslog_mask = mask; - - return mask; -} - -static VALUE mSyslog_log(int argc, VALUE *argv, VALUE self) -{ - VALUE pri; - - if (argc < 2) { - rb_raise(rb_eArgError, "wrong # of arguments(%d for 2+)", argc); - } - - argc--; - pri = *argv++; - - if (!FIXNUM_P(pri)) { - rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(pri))); - } - - syslog_write(FIX2INT(pri), argc, argv); - - return self; -} - -static VALUE mSyslog_inspect(VALUE self) -{ -#define N 7 - int argc = N; - VALUE argv[N]; - const char fmt[] = - "<#%s: opened=%s, ident=\"%s\", options=%d, facility=%d, mask=%d>"; - - argv[0] = rb_str_new(fmt, sizeof(fmt) - 1); - argv[1] = mSyslog; - argv[2] = syslog_opened ? Qtrue : Qfalse; - argv[3] = syslog_ident; - argv[4] = syslog_options; - argv[5] = syslog_facility; - argv[6] = syslog_mask; - - return rb_f_sprintf(argc, argv); -#undef N -} - -static VALUE mSyslog_instance(VALUE self) -{ - return self; -} - -#define define_syslog_shortcut_method(pri, name) \ -static VALUE mSyslog_##name(int argc, VALUE *argv, VALUE self) \ -{ \ - syslog_write(pri, argc, argv); \ -\ - return self; \ -} - -#ifdef LOG_EMERG -define_syslog_shortcut_method(LOG_EMERG, emerg) -#endif -#ifdef LOG_ALERT -define_syslog_shortcut_method(LOG_ALERT, alert) -#endif -#ifdef LOG_CRIT -define_syslog_shortcut_method(LOG_CRIT, crit) -#endif -#ifdef LOG_ERR -define_syslog_shortcut_method(LOG_ERR, err) -#endif -#ifdef LOG_WARNING -define_syslog_shortcut_method(LOG_WARNING, warning) -#endif -#ifdef LOG_NOTICE -define_syslog_shortcut_method(LOG_NOTICE, notice) -#endif -#ifdef LOG_INFO -define_syslog_shortcut_method(LOG_INFO, info) -#endif -#ifdef LOG_DEBUG -define_syslog_shortcut_method(LOG_DEBUG, debug) -#endif - -static VALUE mSyslogConstants_LOG_MASK(VALUE klass, VALUE pri) -{ - return INT2FIX(LOG_MASK(FIX2INT(pri))); -} - -static VALUE mSyslogConstants_LOG_UPTO(VALUE klass, VALUE pri) -{ - return INT2FIX(LOG_UPTO(FIX2INT(pri))); -} - -/* Init for package syslog */ -void Init_syslog() -{ - mSyslog = rb_define_module("Syslog"); - - mSyslogConstants = rb_define_module_under(mSyslog, "Constants"); - - rb_include_module(mSyslog, mSyslogConstants); - - rb_define_module_function(mSyslog, "open", mSyslog_open, -1); - rb_define_module_function(mSyslog, "reopen", mSyslog_reopen, -1); - rb_define_module_function(mSyslog, "open!", mSyslog_reopen, -1); - rb_define_module_function(mSyslog, "opened?", mSyslog_isopen, 0); - - rb_define_module_function(mSyslog, "ident", mSyslog_ident, 0); - rb_define_module_function(mSyslog, "options", mSyslog_options, 0); - rb_define_module_function(mSyslog, "facility", mSyslog_facility, 0); - - rb_define_module_function(mSyslog, "log", mSyslog_log, -1); - rb_define_module_function(mSyslog, "close", mSyslog_close, 0); - rb_define_module_function(mSyslog, "mask", mSyslog_get_mask, 0); - rb_define_module_function(mSyslog, "mask=", mSyslog_set_mask, 1); - - rb_define_module_function(mSyslog, "LOG_MASK", mSyslogConstants_LOG_MASK, 1); - rb_define_module_function(mSyslog, "LOG_UPTO", mSyslogConstants_LOG_UPTO, 1); - - rb_define_module_function(mSyslog, "inspect", mSyslog_inspect, 0); - rb_define_module_function(mSyslog, "instance", mSyslog_instance, 0); - - rb_define_module_function(mSyslogConstants, "LOG_MASK", mSyslogConstants_LOG_MASK, 1); - rb_define_module_function(mSyslogConstants, "LOG_UPTO", mSyslogConstants_LOG_UPTO, 1); - -#define rb_define_syslog_const(id) \ - rb_define_const(mSyslogConstants, #id, INT2NUM(id)) - - /* Various options when opening log */ -#ifdef LOG_PID - rb_define_syslog_const(LOG_PID); -#endif -#ifdef LOG_CONS - rb_define_syslog_const(LOG_CONS); -#endif -#ifdef LOG_ODELAY - rb_define_syslog_const(LOG_ODELAY); /* deprecated */ -#endif -#ifdef LOG_NDELAY - rb_define_syslog_const(LOG_NDELAY); -#endif -#ifdef LOG_NOWAIT - rb_define_syslog_const(LOG_NOWAIT); /* deprecated */ -#endif -#ifdef LOG_PERROR - rb_define_syslog_const(LOG_PERROR); -#endif - - /* Various syslog facilities */ -#ifdef LOG_AUTH - rb_define_syslog_const(LOG_AUTH); -#endif -#ifdef LOG_AUTHPRIV - rb_define_syslog_const(LOG_AUTHPRIV); -#endif -#ifdef LOG_CONSOLE - rb_define_syslog_const(LOG_CONSOLE); -#endif -#ifdef LOG_CRON - rb_define_syslog_const(LOG_CRON); -#endif -#ifdef LOG_DAEMON - rb_define_syslog_const(LOG_DAEMON); -#endif -#ifdef LOG_FTP - rb_define_syslog_const(LOG_FTP); -#endif -#ifdef LOG_KERN - rb_define_syslog_const(LOG_KERN); -#endif -#ifdef LOG_LPR - rb_define_syslog_const(LOG_LPR); -#endif -#ifdef LOG_MAIL - rb_define_syslog_const(LOG_MAIL); -#endif -#ifdef LOG_NEWS - rb_define_syslog_const(LOG_NEWS); -#endif -#ifdef LOG_NTP - rb_define_syslog_const(LOG_NTP); -#endif -#ifdef LOG_SECURITY - rb_define_syslog_const(LOG_SECURITY); -#endif -#ifdef LOG_SYSLOG - rb_define_syslog_const(LOG_SYSLOG); -#endif -#ifdef LOG_USER - rb_define_syslog_const(LOG_USER); -#endif -#ifdef LOG_UUCP - rb_define_syslog_const(LOG_UUCP); -#endif -#ifdef LOG_LOCAL0 - rb_define_syslog_const(LOG_LOCAL0); -#endif -#ifdef LOG_LOCAL1 - rb_define_syslog_const(LOG_LOCAL1); -#endif -#ifdef LOG_LOCAL2 - rb_define_syslog_const(LOG_LOCAL2); -#endif -#ifdef LOG_LOCAL3 - rb_define_syslog_const(LOG_LOCAL3); -#endif -#ifdef LOG_LOCAL4 - rb_define_syslog_const(LOG_LOCAL4); -#endif -#ifdef LOG_LOCAL5 - rb_define_syslog_const(LOG_LOCAL5); -#endif -#ifdef LOG_LOCAL6 - rb_define_syslog_const(LOG_LOCAL6); -#endif -#ifdef LOG_LOCAL7 - rb_define_syslog_const(LOG_LOCAL7); -#endif - -#define rb_define_syslog_shortcut(name) \ - rb_define_module_function(mSyslog, #name, mSyslog_##name, -1) - - /* Various syslog priorities and the shortcut methods */ -#ifdef LOG_EMERG - rb_define_syslog_const(LOG_EMERG); - rb_define_syslog_shortcut(emerg); -#endif -#ifdef LOG_ALERT - rb_define_syslog_const(LOG_ALERT); - rb_define_syslog_shortcut(alert); -#endif -#ifdef LOG_CRIT - rb_define_syslog_const(LOG_CRIT); - rb_define_syslog_shortcut(crit); -#endif -#ifdef LOG_ERR - rb_define_syslog_const(LOG_ERR); - rb_define_syslog_shortcut(err); -#endif -#ifdef LOG_WARNING - rb_define_syslog_const(LOG_WARNING); - rb_define_syslog_shortcut(warning); -#endif -#ifdef LOG_NOTICE - rb_define_syslog_const(LOG_NOTICE); - rb_define_syslog_shortcut(notice); -#endif -#ifdef LOG_INFO - rb_define_syslog_const(LOG_INFO); - rb_define_syslog_shortcut(info); -#endif -#ifdef LOG_DEBUG - rb_define_syslog_const(LOG_DEBUG); - rb_define_syslog_shortcut(debug); -#endif -} diff --git a/ext/syslog/syslog.txt b/ext/syslog/syslog.txt deleted file mode 100644 index 9aed35133d..0000000000 --- a/ext/syslog/syslog.txt +++ /dev/null @@ -1,121 +0,0 @@ -.\" syslog.txt - -*- Indented-Text -*- -$RoughId: syslog.txt,v 1.18 2002/02/25 08:20:14 knu Exp $ -$Id$ - -UNIX Syslog extension for Ruby -Amos Gouaux, University of Texas at Dallas - -& -Akinori MUSHA - - -** Syslog(Module) - -Included Modules: Syslog::Constants - -require 'syslog' - -A Simple wrapper for the UNIX syslog system calls that might be handy -if you're writing a server in Ruby. For the details of the syslog(8) -architecture and constants, see the syslog(3) manual page of your -platform. - -Module Methods: - - open(ident = $0, logopt = Syslog::LOG_PID | Syslog::LOG_CONS, - facility = Syslog::LOG_USER) [{ |syslog| ... }] - - Opens syslog with the given options and returns the module - itself. If a block is given, calls it with an argument of - itself. If syslog is already opened, raises RuntimeError. - - Example: - Syslog.open('ftpd', Syslog::LOG_PID | Syslog::LOG_NDELAY, - Syslog::LOG_FTP) - - open!(ident = $0, logopt = Syslog::LOG_PID | Syslog::LOG_CONS, - facility = Syslog::LOG_USER) - reopen(ident = $0, logopt = Syslog::LOG_PID | Syslog::LOG_CONS, - facility = Syslog::LOG_USER) - - Same as open, but does a close first. - - opened? - - Returns true if syslog opened, otherwise false. - - ident - options - facility - - Returns the parameters given in the last open, respectively. - Every call of Syslog::open resets these values. - - log(pri, message, ...) - - Writes message to syslog. - - Example: - Syslog.log(Syslog::LOG_CRIT, "the sky is falling in %d seconds!", 10) - - crit(message, ...) - emerg(message, ...) - alert(message, ...) - err(message, ...) - warning(message, ...) - notice(message, ...) - info(message, ...) - debug(message, ...) - - These are shortcut methods of Syslog::log(). The lineup may - vary depending on what priorities are defined on your system. - - Example: - Syslog.crit("the sky is falling in %d seconds!", 5) - - mask - mask=(mask) - - Returns or sets the log priority mask. The value of the mask - is persistent and will not be reset by Syslog::open or - Syslog::close. - - Example: - Syslog.mask = Syslog::LOG_UPTO(Syslog::LOG_ERR) - - close - - Closes syslog. - - inspect - - Returns the "inspect" string of the Syslog module. - - instance - - Returns the module itself. (Just for backward compatibility) - - LOG_MASK(pri) - - Creates a mask for one priority. - - LOG_UPTO(pri) - - Creates a mask for all priorities up to pri. - -** Syslog::Constants(Module) - -require 'syslog' -include Syslog::Constants - -This module includes the LOG_* constants available on the system. - -Module Methods: - - LOG_MASK(pri) - - Creates a mask for one priority. - - LOG_UPTO(pri) - - Creates a mask for all priorities up to pri. diff --git a/ext/syslog/test.rb b/ext/syslog/test.rb deleted file mode 100644 index 6cd861b2b2..0000000000 --- a/ext/syslog/test.rb +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env ruby -# $RoughId: test.rb,v 1.9 2002/02/25 08:20:14 knu Exp $ -# $Id$ - -# Please only run this test on machines reasonable for testing. -# If in doubt, ask your admin. - -require 'runit/testcase' -require 'runit/cui/testrunner' - -# Prepend current directory to load path for testing. -$:.unshift('.') - -require 'syslog' - -class TestSyslog < RUNIT::TestCase - def test_new - assert_exception(NameError) { - Syslog.new - } - end - - def test_instance - sl1 = Syslog.instance - sl2 = Syslog.open - sl3 = Syslog.instance - - assert_equal(Syslog, sl1) - assert_equal(Syslog, sl2) - assert_equal(Syslog, sl3) - ensure - Syslog.close - end - - def test_open - # default parameters - Syslog.open - - assert_equal($0, Syslog.ident) - assert_equal(Syslog::LOG_PID | Syslog::LOG_CONS, Syslog.options) - assert_equal(Syslog::LOG_USER, Syslog.facility) - - # open without close - assert_exception(RuntimeError) { - Syslog.open - } - - Syslog.close - - # given parameters - Syslog.open("foo", Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog::LOG_DAEMON) - - assert_equal('foo', Syslog.ident) - assert_equal(Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog.options) - assert_equal(Syslog::LOG_DAEMON, Syslog.facility) - - Syslog.close - - # default parameters again (after close) - Syslog.open - Syslog.close - - assert_equal($0, Syslog.ident) - assert_equal(Syslog::LOG_PID | Syslog::LOG_CONS, Syslog.options) - assert_equal(Syslog::LOG_USER, Syslog.facility) - - # block - param = nil - Syslog.open { |param| } - assert_equal(Syslog, param) - ensure - Syslog.close - end - - def test_opened? - assert_equal(false, Syslog.opened?) - - Syslog.open - assert_equal(true, Syslog.opened?) - - Syslog.close - assert_equal(false, Syslog.opened?) - - Syslog.open { - assert_equal(true, Syslog.opened?) - } - - assert_equal(false, Syslog.opened?) - end - - def test_mask - Syslog.open - - orig = Syslog.mask - - Syslog.mask = Syslog.LOG_UPTO(Syslog::LOG_ERR) - assert_equal(Syslog.LOG_UPTO(Syslog::LOG_ERR), Syslog.mask) - - Syslog.mask = Syslog.LOG_MASK(Syslog::LOG_CRIT) - assert_equal(Syslog.LOG_MASK(Syslog::LOG_CRIT), Syslog.mask) - - Syslog.mask = orig - ensure - Syslog.close - end - - def test_log - stderr = IO::pipe - - pid = fork { - stderr[0].close - STDERR.reopen(stderr[1]) - stderr[1].close - - options = Syslog::LOG_PERROR | Syslog::LOG_NDELAY - - Syslog.open("syslog_test", options) { |sl| - sl.log(Syslog::LOG_NOTICE, "test1 - hello, %s!", "world") - sl.notice("test1 - hello, %s!", "world") - } - - Syslog.open("syslog_test", options | Syslog::LOG_PID) { |sl| - sl.log(Syslog::LOG_CRIT, "test2 - pid") - sl.crit("test2 - pid") - } - exit! - } - - stderr[1].close - Process.waitpid(pid) - - # LOG_PERROR is not yet implemented on Cygwin. - return if RUBY_PLATFORM =~ /cygwin/ - - 2.times { - assert_equal("syslog_test: test1 - hello, world!\n", stderr[0].gets) - } - - 2.times { - assert_equal(format("syslog_test[%d]: test2 - pid\n", pid), stderr[0].gets) - } - end - - def test_inspect - Syslog.open { |sl| - assert_equal(format('<#%s: opened=%s, ident="%s", ' + - 'options=%d, facility=%d, mask=%d>', - Syslog, sl.opened?, sl.ident, - sl.options, sl.facility, sl.mask), - sl.inspect) - } - end -end - -if $0 == __FILE__ - suite = RUNIT::TestSuite.new - - suite.add_test(TestSyslog.suite) - - RUNIT::CUI::TestRunner.run(suite) -end diff --git a/ext/tcltklib/.cvsignore b/ext/tcltklib/.cvsignore deleted file mode 100644 index f3c7a7c5da..0000000000 --- a/ext/tcltklib/.cvsignore +++ /dev/null @@ -1 +0,0 @@ -Makefile diff --git a/ext/tcltklib/MANIFEST b/ext/tcltklib/MANIFEST deleted file mode 100644 index 4e37fb900f..0000000000 --- a/ext/tcltklib/MANIFEST +++ /dev/null @@ -1,16 +0,0 @@ -MANIFEST -README.euc -MANUAL.euc -tcltklib.c -stubs.c -depend -extconf.rb -lib/tcltk.rb -demo/lines1.rb -demo/lines0.tcl -demo/lines2.rb -sample/sample1.rb -sample/sample2.rb -sample/maru.gif -sample/batsu.gif -sample/sample0.rb diff --git a/ext/tcltklib/MANUAL.euc b/ext/tcltklib/MANUAL.euc deleted file mode 100644 index 789e85a9de..0000000000 --- a/ext/tcltklib/MANUAL.euc +++ /dev/null @@ -1,124 +0,0 @@ -(tof) - MANUAL.euc - Sep. 19, 1997 Y. Shigehiro - -°Ê²¼, ¡Ötcl/tk¡×¤È¤¤¤¦É½µ­¤Ï, tclsh ¤ä wish ¤ò¼Â¸½¤·¤Æ¤¤¤ë, °ìÈ̤Ǥ¤¤¦ -¤È¤³¤í¤Î tcl/tk ¤ò»Ø¤·¤Þ¤¹. ¡Ötcltk ¥é¥¤¥Ö¥é¥ê¡×, ¡Ötcltklib ¥é¥¤¥Ö¥é -¥ê¡×¤È¤¤¤¦É½µ­¤Ï, Ëܥѥ屡¼¥¸¤Ë´Þ¤Þ¤ì¤ë ruby ÍѤΥ饤¥Ö¥é¥ê¤ò»Ø¤·¤Þ¤¹. - -<< tcltk ¥é¥¤¥Ö¥é¥ê >> - -tcl/tk ¤Î C ¥é¥¤¥Ö¥é¥ê¤òÍøÍѤ¹¤ë¤¿¤á¤Î¹â(Ãæ?)¿å½à¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤òÄó -¶¡¤·¤Þ¤¹. - -¤³¤Î¥é¥¤¥Ö¥é¥ê¤Ï ruby ¤«¤é tcl/tk ¥é¥¤¥Ö¥é¥ê¤òÍøÍѤ¹¤ë¤¿¤á¤Î¤â¤Î¤Ç, Æâ -Éô¤Ç tcltklib ¥é¥¤¥Ö¥é¥ê¤òÍøÍѤ·¤Æ¤¤¤Þ¤¹. - -[ÀâÌÀ] - -tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤Ç¤Ï, ¥¦¥£¥¸¥§¥Ã¥È¤Ë²¿¤«»Ø¼¨¤òÁ÷¤ë¤Ë¤Ï, ¥¦¥£¥¸¥§¥Ã -¥È̾¤Ë³¤¤¤Æ¥Ñ¥é¥á¡¼¥¿¤ò½ñ¤­¤Þ¤¹. ¤·¤¿¤¬¤Ã¤Æ, ¥¦¥£¥¸¥§¥Ã¥È¤¬¥ª¥Ö¥¸¥§¥¯ -¥È¤Ç¤¢¤ê, ¤½¤ì¤ËÂФ·¤Æ¥á¥½¥Ã¥É¤òÁ÷¤Ã¤Æ¤¤¤ë, ¤È¤ß¤Ê¤¹¤³¤È¤¬¤Ç¤­¤Þ¤¹. ¤µ -¤Æ, tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤Ç¤Ï, ÁȤ߹þ¤ß¥³¥Þ¥ó¥É¤â, Á°½Ò¤Î¥¦¥£¥¸¥§¥Ã¥È¤È -Ʊ¤¸¤è¤¦¤Ê½ñ¼°¤ÎÌ¿Îá¤Ç¼Â¹Ô¤µ¤ì¤Þ¤¹. ¤¹¤Ê¤ï¤Á, ¥³¥Þ¥ó¥É¤â¥ª¥Ö¥¸¥§¥¯¥È¤Ç -¤¢¤ë¤È¹Í¤¨¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹. - -¤³¤Î¤è¤¦¤Ê¹Í¤¨¤Ë´ð¤Å¤­, tcltk ¥é¥¤¥Ö¥é¥ê¤Ç¤Ï, tcl/tk ¤Î¥³¥Þ¥ó¥É¤ä¥¦¥£ -¥¸¥§¥Ã¥È¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤òÀ¸À®¤·¤Þ¤¹. ¥ª¥Ö¥¸¥§¥¯¥È¤ËÂФ¹¤ë¥á¥½¥Ã -¥É¸Æ¤Ó½Ð¤·¤Ï, e() ¥á¥½¥Ã¥É¤Ë¤è¤ê¼Â¹Ô¤µ¤ì¤Þ¤¹. Î㤨¤Ð, tcl/tk ¤Î info -¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë ruby ¤Î¥ª¥Ö¥¸¥§¥¯¥È¤¬ info ¤È¤¤¤¦Ì¾Á°¤Ç¤¢¤ë¤È¤¹¤ë¤È, -tcl/tk ¤Î - info commands -¤È¤¤¤¦Ì¿Îá¤Ï tcltk ¥é¥¤¥Ö¥é¥ê¤Ç¤Ï - info.e("commands") -¤Èµ­½Ò¤µ¤ì¤Þ¤¹. ¤Þ¤¿, ¡Ö.¡×¤È¤¤¤¦¥¦¥£¥¸¥§¥Ã¥È (wish ¼Â¹Ô»þ¤Ë¼«Æ°Åª¤ËÀ¸ -À®¤µ¤ì¤ë¥ë¡¼¥È¥¦¥£¥¸¥§¥Ã¥È) ¤ËÂбþ¤¹¤ë ruby ¤Î¥ª¥Ö¥¸¥§¥¯¥È¤¬ root ¤È¤¤ -¤¦Ì¾Á°¤Ç¤¢¤ë¤È¤¹¤ë¤È, - . configure -height 300 -width 300 -¤È¤¤¤¦ tcl/tk ¤ÎÌ¿Îá¤Ï - root.e("configure -height 300 -width 300") -¤Èµ­½Ò¤µ¤ì¤Þ¤¹. ¤³¤Î¤è¤¦¤Êµ­½Ò¤Ï, ¸«¤¿¤á¤Ë¤ÏÈþ¤·¤¯¤¢¤ê¤Þ¤»¤ó¤¬, ¤½¤·¤Æ, -¥¹¥¯¥ê¥×¥È¤òÆɤà¿Í¤Ë¤Ï¸«¤Å¤é¤¤¤«¤âÃΤì¤Þ¤»¤ó¤¬, ¼ÂºÝ¤Ë¥¹¥¯¥ê¥×¥È¤ò½ñ¤¤ -¤Æ¤ß¤ë¤ÈͽÁÛ³°¤Ë¼ê·Ú¤Ç¤¹. - -[»ÈÍÑË¡] - -1. ¥é¥¤¥Ö¥é¥ê¤òÆɤ߹þ¤à. - require "tcltk" - -2. tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤òÀ¸À®¤¹¤ë. - ip = TclTkInterpreter.new() - -3. tcl/tk ¤Î¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤òÊÑ¿ô¤ËÂåÆþ¤·¤Æ¤ª¤¯. - # ¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤¬Æþ¤Ã¤¿ Hash ¤ò¼è¤ê½Ð¤¹. - c = ip.commands() - # »È¤¤¤¿¤¤¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤ò¸ÄÊ̤ÎÊÑ¿ô¤ËÂåÆþ¤¹¤ë. - bind, button, info, wm = c.indexes("bind", "button", "info", "wm") - -4. ɬÍפʽèÍý¤ò¹Ô¤¦. - ¾Ü¤·¤¯¤Ï, ¥µ¥ó¥×¥ë¤ò»²¾È¤Î¤³¤È. - -5. ½àÈ÷¤¬¤Ç¤­¤¿¤é, ¥¤¥Ù¥ó¥È¥ë¡¼¥×¤ËÆþ¤ë. - TclTk.mainloop() - -(( °Ê²¼, ¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹Åù¤ÎÀâÌÀ¤ò½ñ¤¯Í½Äê.)) - - - -<< tcltklib ¥é¥¤¥Ö¥é¥ê >> - -tcl/tk ¤Î C ¥é¥¤¥Ö¥é¥ê¤òÍøÍѤ¹¤ë¤¿¤á¤ÎÄã¿å½à¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤òÄ󶡤·¤Þ -¤¹. - -¥³¥ó¥Ñ¥¤¥ë/¼Â¹Ô¤Ë¤Ï, tcl/tk ¤Î C ¥é¥¤¥Ö¥é¥ê¤¬É¬ÍפǤ¹. - -[ÀâÌÀ] - -¤³¤Î¥é¥¤¥Ö¥é¥ê¤òÍѤ¤¤ë¤È, ruby ¤«¤é tcl/tk ¤Î C ¥é¥¤¥Ö¥é¥ê¤òÍøÍѤǤ­¤Þ -¤¹. ¶ñÂÎŪ¤Ë¤Ï, ruby ¥¤¥ó¥¿¥×¥ê¥¿¤«¤é tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤ò¸Æ¤Ó½Ð¤¹¤³ -¤È¤¬¤Ç¤­¤Þ¤¹. ¤µ¤é¤Ë, ¤½¤Î(ruby ¥¤¥ó¥¿¥×¥ê¥¿¤«¤é¸Æ¤Ó½Ð¤·¤¿) tcl/tk ¥¤ -¥ó¥¿¥×¥ê¥¿¤«¤é, µÕ¤Ë ruby ¥¤¥ó¥¿¥×¥ê¥¿¤ò¸Æ¤Ó½Ð¤¹¤³¤È¤â¤Ç¤­¤Þ¤¹. - -[»ÈÍÑË¡] - -require "tcltklib" ¤¹¤ë¤È, °Ê²¼¤Î¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹¤¬ÍøÍѲÄǽ¤Ç¤¹. - -¥â¥¸¥å¡¼¥ë TclTkLib - tcl/tk ¥é¥¤¥Ö¥é¥ê¤ò¸Æ¤Ó½Ð¤¹¥á¥½¥Ã¥É¤ò½¸¤á¤¿¥â¥¸¥å¡¼¥ë¤Ç¤¹. ¤¿¤À¤·, - tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿´Ø·¸¤Î¥á¥½¥Ã¥É¤Ï¥¯¥é¥¹ TclTkIp ¤Ë¤¢¤ê¤Þ¤¹. - - ¥â¥¸¥å¡¼¥ë¥á¥½¥Ã¥É mainloop() - Tk_MainLoop ¤ò¼Â¹Ô¤·¤Þ¤¹. Á´¤Æ¤Î tk ¤Î¥¦¥¤¥ó¥É¥¦¤¬Ìµ¤¯¤Ê¤ë¤È½ªÎ» - ¤·¤Þ¤¹(Î㤨¤Ð, tcl/tk ¤Ç½ñ¤¯¤È¤³¤í¤Î "destroy ." ¤ò¤·¤¿¾ì¹çÅù). - °ú¿ô: ̵¤· - Ìá¤êÃÍ: nil - -¥¯¥é¥¹ TclTkIp - ¥¤¥ó¥¹¥¿¥ó¥¹¤¬ tcl/tk ¤Î¥¤¥ó¥¿¥×¥ê¥¿¤ËÂбþ¤·¤Þ¤¹. tcl/tk ¤Î¥é¥¤¥Ö - ¥é¥ê¤Î»ÅÍÍÄ̤ê, ¥¤¥ó¥¹¥¿¥ó¥¹¤òÊ£¿ô¸ÄÀ¸À®¤·¤Æ¤âÀµ¤·¤¯Æ°ºî¤·¤Þ¤¹(¤½ - ¤ó¤Ê¤³¤È¤ò¤¹¤ëɬÍפϤ¢¤Þ¤ê̵¤¤¤Ï¤º¤Ç¤¹¤¬). ¥¤¥ó¥¿¥×¥ê¥¿¤Ï wish ¤Î - tcl/tk ¥³¥Þ¥ó¥É¤ò¼Â¹Ô¤Ç¤­¤Þ¤¹. ¤µ¤é¤Ë, °Ê²¼¤Î¥³¥Þ¥ó¥É¤ò¼Â¹Ô¤Ç¤­¤Þ - ¤¹. - ¥³¥Þ¥ó¥É ruby - °ú¿ô¤ò ruby ¤Ç¼Â¹Ô¤·¤Þ¤¹(ruby_eval_string ¤ò¼Â¹Ô¤·¤Þ¤¹). °ú¿ô - ¤Ï 1 ¤Ä¤Ç¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó. Ìá¤êÃÍ¤Ï ruby ¤Î¼Â¹Ô·ë²Ì¤Ç¤¹. - ruby ¤Î¼Â¹Ô·ë²Ì¤Ï nil ¤« String ¤Ç¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó. - - ¥¯¥é¥¹¥á¥½¥Ã¥É new() - TclTkIp ¥¯¥é¥¹¤Î¥¤¥ó¥¹¥¿¥ó¥¹¤òÀ¸À®¤·¤Þ¤¹ - °ú¿ô: ̵¤· - Ìá¤êÃÍ (TclTkIp): À¸À®¤µ¤ì¤¿¥¤¥ó¥¹¥¿¥ó¥¹ - - ¥á¥½¥Ã¥É _eval(script) - ¥¤¥ó¥¿¥×¥ê¥¿¤Ç script ¤òɾ²Á¤·¤Þ¤¹(Tcl_Eval ¤ò¼Â¹Ô¤·¤Þ¤¹). Á°½Ò - ¤Î¤è¤¦¤Ë, ruby ¥³¥Þ¥ó¥É¤Ë¤è¤ê script Æ⤫¤é ruby ¥¹¥¯¥ê¥×¥È¤ò¼Â - ¹Ô¤Ç¤­¤Þ¤¹. - °ú¿ô: script (String) - ¥¤¥ó¥¿¥×¥ê¥¿¤Çɾ²Á¤¹¤ë¥¹¥¯¥ê¥×¥Èʸ»úÎó - Ìá¤êÃÍ (String): ɾ²Á·ë²Ì ((Tcl_Interp *)->result) - - ¥á¥½¥Ã¥É _return_value() - ľÁ°¤Î Tcl_Eval ¤ÎÌá¤êÃͤòÊÖ¤·¤Þ¤¹. 0(TCL_OK) ¤ÇÀµ¾ï½ªÎ»¤Ç¤¹. - °ú¿ô: ̵¤· - Ìá¤êÃÍ (Fixnum): ľÁ°¤Î Tcl_Eval() ¤¬ÊÖ¤·¤¿ÃÍ. - -(eof) diff --git a/ext/tcltklib/README.euc b/ext/tcltklib/README.euc deleted file mode 100644 index 290ffb0b60..0000000000 --- a/ext/tcltklib/README.euc +++ /dev/null @@ -1,133 +0,0 @@ -(tof) - tcltk ¥é¥¤¥Ö¥é¥ê - tcltklib ¥é¥¤¥Ö¥é¥ê - Sep. 19, 1997 Y. Shigehiro - -°Ê²¼, ¡Ötcl/tk¡×¤È¤¤¤¦É½µ­¤Ï, tclsh ¤ä wish ¤ò¼Â¸½¤·¤Æ¤¤¤ë, °ìÈ̤Ǥ¤¤¦ -¤È¤³¤í¤Î tcl/tk ¤ò»Ø¤·¤Þ¤¹. ¡Ötcltk ¥é¥¤¥Ö¥é¥ê¡×, ¡Ötcltklib ¥é¥¤¥Ö¥é -¥ê¡×¤È¤¤¤¦É½µ­¤Ï, Ëܥѥ屡¼¥¸¤Ë´Þ¤Þ¤ì¤ë ruby ÍѤΥ饤¥Ö¥é¥ê¤ò»Ø¤·¤Þ¤¹. - -[¥Õ¥¡¥¤¥ë¤Ë¤Ä¤¤¤Æ] - -README.euc : ¤³¤Î¥Õ¥¡¥¤¥ë(Ãí°Õ, ÆÃħ, ¥¤¥ó¥¹¥È¡¼¥ë¤ÎÊýË¡). -MANUAL.euc : ¥Þ¥Ë¥å¥¢¥ë. - -lib/, ext/ : ¥é¥¤¥Ö¥é¥ê¤Î¼ÂÂÎ. - -sample/ : ¥Þ¥Ë¥å¥¢¥ëÂå¤ï¤ê¤Î¥µ¥ó¥×¥ë¥×¥í¥°¥é¥à. -sample/sample0.rb : tcltklib ¥é¥¤¥Ö¥é¥ê¤Î¥Æ¥¹¥È. -sample/sample1.rb : tcltk ¥é¥¤¥Ö¥é¥ê¤Î¥Æ¥¹¥È. - tcl/tk (wish) ¤Ç¤Ç¤­¤½¤¦¤Ê¤³¤È¤ò°ìÄ̤ê½ñ¤¤¤Æ¤ß¤Þ¤·¤¿. -sample/sample2.rb : tcltk ¥é¥¤¥Ö¥é¥ê¤Î¥µ¥ó¥×¥ë. - maeda shugo (shugo@po.aianet.ne.jp) »á¤Ë¤è¤ë - (`rb.tk' ¤Ç½ñ¤«¤ì¤Æ¤¤¤¿) ruby ¤Î¥µ¥ó¥×¥ë¥×¥í¥°¥é¥à - http://www.aianet.or.jp/~shugo/ruby/othello.rb.gz - ¤ò tcltk ¥é¥¤¥Ö¥é¥ê¤ò»È¤¦¤è¤¦¤Ë, µ¡³£Åª¤ËÊѹ¹¤·¤Æ¤ß¤Þ¤·¤¿. - -demo/ : 100 ËܤÎÀþ¤ò 100 ²óÉÁ¤¯¥Ç¥â¥×¥í¥°¥é¥à. - ºÇ½é¤Ë¶õ¥ë¡¼¥×¤Î»þ´Ö¤ò¬Äꤷ, ³¤¤¤Æ¼ÂºÝ¤ËÀþ¤ò°ú¤¯»þ´Ö¤ò¬Äꤷ¤Þ¤¹. - tcl/tk ¤Ï(ºÆ)ÉÁ²è¤Î¤È¤­¤Ë backing store ¤ò»È¤ï¤º¤ËΧµÁ¤Ë 10000 ËÜ(?) - Àþ¤ò°ú¤¯¤Î¤Ç, (ºÆ)ÉÁ²è¤ò»Ï¤á¤ë¤È, ¥Þ¥·¥ó¤¬¤«¤Ê¤ê½Å¤¯¤Ê¤ê¤Þ¤¹. -demo/lines0.tcl : wish ÍѤΥ¹¥¯¥ê¥×¥È. -demo/lines1.rb : `tk.rb' ÍѤΥ¹¥¯¥ê¥×¥È. -demo/lines2.rb : tcltk ¥é¥¤¥Ö¥é¥êÍѤΥ¹¥¯¥ê¥×¥È. - -[Ãí°Õ] - -¥³¥ó¥Ñ¥¤¥ë/¼Â¹Ô¤Ë¤Ï, tcl/tk ¤Î C ¥é¥¤¥Ö¥é¥ê¤¬É¬ÍפǤ¹. - -¤³¤Î¥é¥¤¥Ö¥é¥ê¤Ï, - - ruby-1.0-970701, ruby-1.0-970911, ruby-1.0-970919 - FreeBSD 2.2.2-RELEASE - ¤ª¤è¤Ó¤½¤Î¥Ñ¥Ã¥±¡¼¥¸ jp-tcl-7.6.tgz, jp-tk-4.2.tgz - -¤ÇºîÀ®/Æ°ºî³Îǧ¤·¤Þ¤·¤¿. ¾¤Î´Ä¶­¤Ç¤ÏÆ°ºî¤¹¤ë¤«¤É¤¦¤«¤ï¤«¤ê¤Þ¤»¤ó. - -TclTkLib.mainloop ¤ò¼Â¹ÔÃæ¤Ë Control-C ¤¬¸ú¤«¤Ê¤¤¤Î¤ÏÉÔÊؤʤΤÇ, ruby -¤Î¥½¡¼¥¹¤ò»²¹Í¤Ë, #include "sig.h" ¤·¤Æ trap_immediate ¤òÁàºî¤·¤Æ¤¤¤Þ -¤¹¤¬, ruby ¤Î README.EXT ¤Ë¤â½ñ¤¤¤Æ¤Ê¤¤¤Î¤Ë, ¤³¤ó¤Ê¤³¤È¤ò¤·¤ÆÎɤ¤¤Î¤« -¤É¤¦¤«¤ï¤«¤ê¤Þ¤»¤ó. - --d ¥ª¥×¥·¥ç¥ó¤Ç¥Ç¥Ð¥Ã¥°¾ðÊó¤òɽ¼¨¤µ¤»¤ë¤¿¤á¤Ë, ruby ¤Î¥½¡¼¥¹¤ò»²¹Í¤Ë, -debug ¤È¤¤¤¦Âç°èÊÑ¿ô¤ò»²¾È¤·¤Æ¤¤¤Þ¤¹¤¬, ruby ¤Î README.EXT ¤Ë¤â½ñ¤¤¤Æ -¤Ê¤¤¤Î¤Ë, ¤³¤ó¤Ê¤³¤È¤ò¤·¤ÆÎɤ¤¤Î¤«¤É¤¦¤«¤ï¤«¤ê¤Þ¤»¤ó. - -extconf.rb ¤Ï½ñ¤­¤Þ¤·¤¿¤¬, (¤¤¤í¤¤¤í¤Ê°ÕÌ£¤Ç)¤³¤ì¤ÇÎɤ¤¤Î¤«Îɤ¯Ê¬¤«¤ê -¤Þ¤»¤ó. - -[ÆÃħ] - -ruby ¤«¤é tcl/tk ¥é¥¤¥Ö¥é¥ê¤òÍøÍѤǤ­¤Þ¤¹. - -tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤Î¥¹¥¯¥ê¥×¥È¤Ï, µ¡³£Åª¤Ë tcltk ¥é¥¤¥Ö¥é¥êÍѤΠruby -¥¹¥¯¥ê¥×¥È¤ËÊÑ´¹¤Ç¤­¤Þ¤¹. - -(`tk.rb' ¤È¤Î°ã¤¤) - -1. tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤Î¥¹¥¯¥ê¥×¥È¤¬, ¤É¤Î¤è¤¦¤Ë, tcltk ¥é¥¤¥Ö¥é¥êÍѤΠ- ruby ¥¹¥¯¥ê¥×¥È¤ËÊÑ´¹¤µ¤ì¤ë¤«¤¬Íý²ò¤Ç¤­¤ì¤Ð, ¥Þ¥Ë¥å¥¢¥ëÎब̵¤¤¤ËÅù - ¤·¤¤ `tk.rb' ¤È¤Ï°Û¤Ê¤ê - - tcl/tk ¤Î¥Þ¥Ë¥å¥¢¥ë¤ä¥ª¥ó¥é¥¤¥ó¥É¥­¥å¥á¥ó¥È¤òÍѤ¤¤Æ - - ¸úΨÎɤ¯¥×¥í¥°¥é¥ß¥ó¥°¤ò¹Ô¤¦¤³¤È¤¬¤Ç¤­¤Þ¤¹. - µ­½ÒÊýË¡¤¬¤ï¤«¤é¤Ê¤¤, ¥³¥Þ¥ó¥É¤ËÍ¿¤¨¤ë¥Ñ¥é¥á¡¼¥¿¤¬¤ï¤«¤é¤Ê¤¤... - - Canvas.new { ... } ¤È, ¤Ê¤¼¥¤¥Æ¥ì¡¼¥¿¥Ö¥í¥Ã¥¯¤ò½ñ¤±¤ë¤Î?? - - Canvas ¤Î bbox ¤Ï¿ôÃͤΥꥹ¥È¤òÊÖ¤¹¤Î¤Ë, xview ¤Ïʸ»úÎó¤òÊÖ¤¹¤Î?? - ¤È, ¤¤¤Á¤¤¤Á, ¥é¥¤¥Ö¥é¥ê¤Î¥½¡¼¥¹¤òÄɤ¤¤«¤±¤ëɬÍפϤ¢¤ê¤Þ¤»¤ó. - -2. ¸Ä¡¹¤Îµ¡Ç½(¥ª¥×¥·¥ç¥ó)¤ò¸ÄÊ̽èÍý¤Ë¤è¤ê¥µ¥Ý¡¼¥È¤·¤Æ¤ª¤ê, ¤½¤Î¤¿¤á¥µ - ¥Ý¡¼¥È¤·¤Æ¤¤¤Ê¤¤µ¡Ç½¤Ï»È¤¦¤³¤È¤¬¤Ç¤­¤Ê¤¤(ËÜÅö¤Ï»È¤¨¤Ê¤¤¤³¤È¤â¤Ê¤¤¤Î - ¤Ç¤¹¤¬) `tk.rb' ¤È¤Ï°Û¤Ê¤ê, tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤Ç²Äǽ¤Ê¤³¤È¤Ï - - ¤Û¤È¤ó¤É - - ruby ¤«¤é¤â¼Â¹Ô¤Ç¤­¤Þ¤¹. ¸½ºß, ruby ¤«¤é¼Â¹Ô¤Ç¤­¤Ê¤¤¤³¤È¤¬³Îǧ¤µ¤ì - ¤Æ¤¤¤ë¤Î¤Ï, - - bind ¥³¥Þ¥ó¥É¤Ç¥¹¥¯¥ê¥×¥È¤òÄɲ乤빽ʸ - ¡Öbind tag sequence +script¡× - ^ - - ¤Î¤ß¤Ç¤¹. - - `. configure -width' ¤ò¤·¤è¤¦¤È¤·¤Æ, `Tk.root.height()' ¤È½ñ¤¤ - ¤¿¤Î¤Ë, `undefined method `height'' ¤ÈÅܤé¤ì¤Æ¤·¤Þ¤Ã¤¿. tk.rb ¤ò - Æɤó¤Ç¤ß¤Æ, ¥¬¡¼¥ó. ¤Ç¤­¤Ê¤¤¤Î¤«... - ¤È¤¤¤¦¤³¤È¤Ï¤¢¤ê¤Þ¤»¤ó. - -3. wish ¥×¥í¥»¥¹¤òµ¯Æ°¤·¥×¥í¥»¥¹´ÖÄÌ¿®¤Ç wish ¤òÍøÍѤ¹¤ë `tk.rb' ¤È¤Ï - °Û¤Ê¤ê, tcl/tk ¤Î C ¥é¥¤¥Ö¥é¥ê¤ò¥ê¥ó¥¯¤· - - ¤è¤ê¹â®¤Ë (¤È¤¤¤Ã¤Æ¤â, »×¤Ã¤¿Äø¤Ï®¤¯¤Ê¤¤¤Ç¤¹¤¬) - - ½èÍý¤ò¹Ô¤¤¤Þ¤¹. - -4. `tk.rb' ¤Û¤É, ¹â¿å½à¤Ê¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤òÈ÷¤¨¤Æ¤¤¤Ê¤¤¤¿¤á, tcl/tk ¥¤ - ¥ó¥¿¥×¥ê¥¿¤ÎÀ¸À®Åù - - ²¿¤«¤é²¿¤Þ¤Ç¼«Ê¬¤Çµ­½Ò - - ¤·¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó(¤½¤ÎÂå¤ï¤ê, tcl/tk ¥é¥¤¥Ö¥é¥ê¤Î»ÅÍÍÄ̤ê, - tcl/tk ¥¤¥ó¥¿¥×¥ê¥¿¤òÊ£¿ôÀ¸À®¤¹¤ë¤³¤È¤â¤Ç¤­¤Þ¤¹¤¬). - ¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤Ï(¤ª¤½¤é¤¯) ruby ¤Î»×Áۤ˱è¤Ã¤¿¤â¤Î¤Ç¤Ï¤¢¤ê¤Þ¤»¤ó. - ¤Þ¤¿, ¥¹¥¯¥ê¥×¥È¤Îµ­½Ò¤Ï - - ¥À¥µ¥À¥µ - - ¤Ç¤¹. ¥¹¥¯¥ê¥×¥È¤Ï, °ì¸«, ÆɤߤŤ餤¤â¤Î¤È¤Ê¤ê¤Þ¤¹. ¤¬, ½ñ¤¯¿Í¤Ë¤È¤Ã - ¤Æ¤Ï, ¤½¤ì¤Û¤ÉÈѤ路¤¤¤â¤Î¤Ç¤Ï¤Ê¤¤¤È»×¤¤¤Þ¤¹. - -[¥¤¥ó¥¹¥È¡¼¥ë¤ÎÊýË¡] - -0. ruby ¤Î¥½¡¼¥¹¥Õ¥¡¥¤¥ë(ruby-1.0-¤Ê¤ó¤¿¤é.tgz)¤òŸ³«¤·¤Æ¤ª¤­¤Þ¤¹. - -1. ruby-1.0-¤Ê¤ó¤¿¤é/ext ¤Ë ext/tcltklib ¤ò¥³¥Ô¡¼¤·¤Þ¤¹. - cp -r ext/tcltklib ???/ruby-1.0-¤Ê¤ó¤¿¤é/ext/ - -2. ruby ¤Î¥¤¥ó¥¹¥È¡¼¥ëË¡¤Ë½¾¤¤ make Åù¤ò¤·¤Þ¤¹. - -3. ruby ¤Î¥é¥¤¥Ö¥é¥êÃÖ¾ì¤Ë lib/* ¤ò¥³¥Ô¡¼¤·¤Þ¤¹. - cp lib/* /usr/local/lib/ruby/ - -(eof) diff --git a/ext/tcltklib/demo/lines0.tcl b/ext/tcltklib/demo/lines0.tcl deleted file mode 100644 index 8ed3c5e1c1..0000000000 --- a/ext/tcltklib/demo/lines0.tcl +++ /dev/null @@ -1,42 +0,0 @@ -#! /usr/local/bin/wish - -proc drawlines {} { - puts [clock format [clock seconds]] - - for {set j 0} {$j < 100} {incr j} { - puts -nonewline "*" - flush stdout - if {$j & 1} { - set c "blue" - } { - set c "red" - } - for {set i 0} {$i < 100} {incr i} { -# .a create line $i 0 0 [expr 500 - $i] -fill $c - } - } - - puts [clock format [clock seconds]] - - for {set j 0} {$j < 100} {incr j} { - puts -nonewline "*" - flush stdout - if {$j & 1} { - set c "blue" - } { - set c "red" - } - for {set i 0} {$i < 100} {incr i} { - .a create line $i 0 0 [expr 500 - $i] -fill $c - } - } - - puts [clock format [clock seconds]] -# destroy . -} - -canvas .a -height 500 -width 500 -button .b -text draw -command drawlines -pack .a .b -side left - -# eof diff --git a/ext/tcltklib/demo/lines1.rb b/ext/tcltklib/demo/lines1.rb deleted file mode 100644 index e459589f50..0000000000 --- a/ext/tcltklib/demo/lines1.rb +++ /dev/null @@ -1,54 +0,0 @@ -#! /usr/local/bin/ruby - -require "tk" - -def drawlines() - print Time.now, "\n" - - for j in 0 .. 99 - print "*" - $stdout.flush - if (j & 1) != 0 - col = "blue" - else - col = "red" - end - for i in 0 .. 99 -# TkcLine.new($a, i, 0, 0, 500 - i, "-fill", col) - end - end - - print Time.now, "\n" - - for j in 0 .. 99 - print "*" - $stdout.flush - if (j & 1) != 0 - col = "blue" - else - col = "red" - end - for i in 0 .. 99 - TkcLine.new($a, i, 0, 0, 500 - i, "-fill", col) - end - end - - print Time.now, "\n" -# Tk.root.destroy -end - -$a = TkCanvas.new{ - height(500) - width(500) -} - -$b = TkButton.new{ - text("draw") - command(proc{drawlines()}) -} - -TkPack.configure($a, $b, {"side"=>"left"}) - -Tk.mainloop - -# eof diff --git a/ext/tcltklib/demo/lines2.rb b/ext/tcltklib/demo/lines2.rb deleted file mode 100644 index 9f21ae6377..0000000000 --- a/ext/tcltklib/demo/lines2.rb +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/local/bin/ruby - -require "tcltk" - -def drawlines() - print Time.now, "\n" - - for j in 0 .. 99 - print "*" - $stdout.flush - if (j & 1) != 0 - col = "blue" - else - col = "red" - end - for i in 0 .. 99 -# $a.e("create line", i, 0, 0, 500 - i, "-fill", col) - end - end - - print Time.now, "\n" - - for j in 0 .. 99 - print "*" - $stdout.flush - if (j & 1) != 0 - col = "blue" - else - col = "red" - end - for i in 0 .. 99 - $a.e("create line", i, 0, 0, 500 - i, "-fill", col) - end - end - - print Time.now, "\n" -# $ip.commands()["destroy"].e($root) -end - -$ip = TclTkInterpreter.new() -$root = $ip.rootwidget() -$a = TclTkWidget.new($ip, $root, "canvas", "-height 500 -width 500") -$c = TclTkCallback.new($ip, proc{drawlines()}) -$b = TclTkWidget.new($ip, $root, "button", "-text draw -command", $c) - -$ip.commands()["pack"].e($a, $b, "-side left") - -TclTk.mainloop - -# eof diff --git a/ext/tcltklib/depend b/ext/tcltklib/depend deleted file mode 100644 index 2cd9c400f7..0000000000 --- a/ext/tcltklib/depend +++ /dev/null @@ -1,2 +0,0 @@ -tcltklib.o: tcltklib.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h -stubs.o: stubs.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/tcltklib/extconf.rb b/ext/tcltklib/extconf.rb deleted file mode 100644 index fd98b1e7da..0000000000 --- a/ext/tcltklib/extconf.rb +++ /dev/null @@ -1,72 +0,0 @@ -# extconf.rb for tcltklib - -require 'mkmf' - -if RUBY_PLATFORM !~ /mswin32|mingw|cygwin/ - have_library("nsl", "t_open") - have_library("socket", "socket") - have_library("dl", "dlopen") - have_library("m", "log") -end - -dir_config("tk") -dir_config("tcl") -dir_config("X11") - -tklib = with_config("tklib") -tcllib = with_config("tcllib") -stubs = enable_config("tcltk_stubs") || with_config("tcltk_stubs") - -def find_tcl(tcllib, stubs) - paths = ["/usr/local/lib", "/usr/pkg/lib", "/usr/lib"] - func = stubs ? "Tcl_InitStubs" : "Tcl_FindExecutable" - if tcllib - find_library(tcllib, func, *paths) - elsif RUBY_PLATFORM =~ /mswin32|mingw|cygwin/ - find_library("tcl", func, *paths) or - find_library("tcl84", func, *paths) or - find_library("tcl83", func, *paths) or - find_library("tcl82", func, *paths) or - find_library("tcl80", func, *paths) or - find_library("tcl76", func, *paths) - else - find_library("tcl", func, *paths) or - find_library("tcl8.4", func, *paths) or - find_library("tcl8.3", func, *paths) or - find_library("tcl8.2", func, *paths) or - find_library("tcl8.0", func, *paths) or - find_library("tcl7.6", func, *paths) - end -end - -def find_tk(tklib, stubs) - paths = ["/usr/local/lib", "/usr/pkg/lib", "/usr/lib"] - func = stubs ? "Tk_InitStubs" : "Tk_Init" - if tklib - find_library(tklib, func, *paths) - elsif RUBY_PLATFORM =~ /mswin32|mingw|cygwin/ - find_library("tk", func, *paths) or - find_library("tk84", func, *paths) or - find_library("tk83", func, *paths) or - find_library("tk82", func, *paths) or - find_library("tk80", func, *paths) or - find_library("tk42", func, *paths) - else - find_library("tk", func, *paths) or - find_library("tk8.4", func, *paths) or - find_library("tk8.3", func, *paths) or - find_library("tk8.2", func, *paths) or - find_library("tk8.0", func, *paths) or - find_library("tk4.2", func, *paths) - end -end - -if have_header("tcl.h") && have_header("tk.h") && - (/mswin32|mingw|cygwin/ =~ RUBY_PLATFORM || find_library("X11", "XOpenDisplay", - "/usr/X11/lib", "/usr/X11R6/lib", "/usr/openwin/lib")) && - find_tcl(tcllib, stubs) && - find_tk(tklib, stubs) - $CPPFLAGS += ' -DUSE_TCL_STUBS -DUSE_TK_STUBS' if stubs - $CPPFLAGS += ' -D_WIN32' if /cygwin/ =~ RUBY_PLATFORM - create_makefile("tcltklib") -end diff --git a/ext/tcltklib/lib/tcltk.rb b/ext/tcltklib/lib/tcltk.rb deleted file mode 100644 index 54a00e8f3c..0000000000 --- a/ext/tcltklib/lib/tcltk.rb +++ /dev/null @@ -1,367 +0,0 @@ -# tof - -#### tcltk library, more direct manipulation of tcl/tk -#### Sep. 5, 1997 Y. Shigehiro - -require "tcltklib" - -################ - -# module TclTk: collection of tcl/tk utilities (supplies namespace.) -module TclTk - - # initialize Hash to hold unique symbols and such - @namecnt = {} - - # initialize Hash to hold callbacks - @callback = {} -end - -# TclTk.mainloop(): call TclTkLib.mainloop() -def TclTk.mainloop() - print("mainloop: start\n") if $DEBUG - TclTkLib.mainloop() - print("mainloop: end\n") if $DEBUG -end - -# TclTk.deletecallbackkey(ca): remove callback from TclTk module -# this does not remove callbacks from tcl/tk interpreter -# without calling this method, TclTkInterpreter will not be GCed -# ca: callback(TclTkCallback) -def TclTk.deletecallbackkey(ca) - print("deletecallbackkey: ", ca.to_s(), "\n") if $DEBUG - @callback.delete(ca.to_s) -end - -# TclTk.dcb(ca, wid, W): call TclTk.deletecallbackkey() for each callbacks -# in an array. -# this is for callback for top-level -# ca: array of callbacks(TclTkCallback) -# wid: top-level widget(TclTkWidget) -# w: information about window given by %W(String) -def TclTk.dcb(ca, wid, w) - if wid.to_s() == w - ca.each{|i| - TclTk.deletecallbackkey(i) - } - end -end - -# TclTk._addcallback(ca): register callback -# ca: callback(TclTkCallback) -def TclTk._addcallback(ca) - print("_addcallback: ", ca.to_s(), "\n") if $DEBUG - @callback[ca.to_s()] = ca -end - -# TclTk._callcallback(key, arg): invoke registered callback -# key: key to select callback (to_s value of the TclTkCallback) -# arg: parameter from tcl/tk interpreter -def TclTk._callcallback(key, arg) - print("_callcallback: ", @callback[key].inspect, "\n") if $DEBUG - @callback[key]._call(arg) - # throw out callback value - # should return String to satisfy rb_eval_string() - return "" -end - -# TclTk._newname(prefix): generate unique name(String) -# prefix: prefix of the unique name -def TclTk._newname(prefix) - # generated name counter is stored in @namecnt - if !@namecnt.key?(prefix) - # first appearing prefix, initialize - @namecnt[prefix] = 1 - else - # already appeared prefix, generate next name - @namecnt[prefix] += 1 - end - return "#{prefix}#{@namecnt[prefix]}" -end - -################ - -# class TclTkInterpreter: tcl/tk interpreter -class TclTkInterpreter - - # initialize(): - def initialize() - # generate interpreter object - @ip = TclTkIp.new() - - # add ruby_fmt command to tcl interpreter - # ruby_fmt command format arguments by `format' and call `ruby' command - # (notice ruby command receives only one argument) - if $DEBUG - @ip._eval("proc ruby_fmt {fmt args} { puts \"ruby_fmt: $fmt $args\" ; ruby [format $fmt $args] }") - else - @ip._eval("proc ruby_fmt {fmt args} { ruby [format $fmt $args] }") - end - - # @ip._get_eval_string(*args): generate string to evaluate in tcl interpreter - # *args: script which is going to be evaluated under tcl/tk - def @ip._get_eval_string(*args) - argstr = "" - args.each{|arg| - argstr += " " if argstr != "" - # call to_eval if it is defined - if (arg.respond_to?(:to_eval)) - argstr += arg.to_eval() - else - # call to_s unless defined - argstr += arg.to_s() - end - } - return argstr - end - - # @ip._eval_args(*args): evaluate string under tcl/tk interpreter - # returns result string. - # *args: script which is going to be evaluated under tcl/tk - def @ip._eval_args(*args) - # calculate the string to eval in the interpreter - argstr = _get_eval_string(*args) - - # evaluate under the interpreter - print("_eval: \"", argstr, "\"") if $DEBUG - res = _eval(argstr) - if $DEBUG - print(" -> \"", res, "\"\n") - elsif _return_value() != 0 - print(res, "\n") - end - fail(%Q/can't eval "#{argstr}"/) if _return_value() != 0 #' - return res - end - - # generate tcl/tk command object and register in the hash - @commands = {} - # for all commands registered in tcl/tk interpreter: - @ip._eval("info command").split(/ /).each{|comname| - if comname =~ /^[.]/ - # if command is a widget (path), generate TclTkWidget, - # and register it in the hash - @commands[comname] = TclTkWidget.new(@ip, comname) - else - # otherwise, generate TclTkCommand - @commands[comname] = TclTkCommand.new(@ip, comname) - end - } - end - - # commands(): returns hash of the tcl/tk commands - def commands() - return @commands - end - - # rootwidget(): returns root widget(TclTkWidget) - def rootwidget() - return @commands["."] - end - - # _tcltkip(): returns @ip(TclTkIp) - def _tcltkip() - return @ip - end - - # method_missing(id, *args): execute undefined method as tcl/tk command - # id: method symbol - # *args: method arguments - def method_missing(id, *args) - # if command named by id registered, then execute it - if @commands.key?(id.id2name) - return @commands[id.id2name].e(*args) - else - # otherwise, exception - super - end - end -end - -# class TclTkObject: base class of the tcl/tk objects -class TclTkObject - - # initialize(ip, exp): - # ip: interpreter(TclTkIp) - # exp: tcl/tk representation - def initialize(ip, exp) - fail("type is not TclTkIp") if !ip.kind_of?(TclTkIp) - @ip = ip - @exp = exp - end - - # to_s(): returns tcl/tk representation - def to_s() - return @exp - end -end - -# class TclTkCommand: tcl/tk commands -# you should not call TclTkCommand.new() -# commands are created by TclTkInterpreter:initialize() -class TclTkCommand < TclTkObject - - # e(*args): execute command. returns String (e is for exec or eval) - # *args: command arguments - def e(*args) - return @ip._eval_args(to_s(), *args) - end -end - -# class TclTkLibCommand: tcl/tk commands in the library -class TclTkLibCommand < TclTkCommand - - # initialize(ip, name): - # ip: interpreter(TclTkInterpreter) - # name: command name (String) - def initialize(ip, name) - super(ip._tcltkip, name) - end -end - -# class TclTkVariable: tcl/tk variable -class TclTkVariable < TclTkObject - - # initialize(interp, dat): - # interp: interpreter(TclTkInterpreter) - # dat: the value to set(String) - # if nil, not initialize variable - def initialize(interp, dat) - # auto-generate tcl/tk representation (variable name) - exp = TclTk._newname("v_") - # initialize TclTkObject - super(interp._tcltkip(), exp) - # safe this for `set' command - @set = interp.commands()["set"] - # set value - set(dat) if dat - end - - # although you can set/refer variable by using set in tcl/tk, - # we provide the method for accessing variables - - # set(data): set tcl/tk variable using `set' - # data: new value - def set(data) - @set.e(to_s(), data.to_s()) - end - - # get(): read tcl/tk variable(String) using `set' - def get() - return @set.e(to_s()) - end -end - -# class TclTkWidget: tcl/tk widget -class TclTkWidget < TclTkCommand - - # initialize(*args): - # *args: parameters - def initialize(*args) - if args[0].kind_of?(TclTkIp) - # in case the 1st argument is TclTkIp: - - # Wrap tcl/tk widget by TclTkWidget - # (used in TclTkInterpreter#initialize()) - - # need two arguments - fail("illegal # of parameter") if args.size != 2 - - # ip: interpreter(TclTkIp) - # exp: tcl/tk representation - ip, exp = args - - # initialize TclTkObject - super(ip, exp) - elsif args[0].kind_of?(TclTkInterpreter) - # in case 1st parameter is TclTkInterpreter: - - # generate new widget from parent widget - - # interp: interpreter(TclTkInterpreter) - # parent: parent widget - # command: widget generating tk command(label Åù) - # *args: argument to the command - interp, parent, command, *args = args - - # generate widget name - exp = parent.to_s() - exp += "." if exp !~ /[.]$/ - exp += TclTk._newname("w_") - # initialize TclTkObject - super(interp._tcltkip(), exp) - # generate widget - res = @ip._eval_args(command, exp, *args) -# fail("can't create Widget") if res != exp - # for tk_optionMenu, it is legal res != exp - else - fail("first parameter is not TclTkInterpreter") - end - end -end - -# class TclTkCallback: tcl/tk callbacks -class TclTkCallback < TclTkObject - - # initialize(interp, pr, arg): - # interp: interpreter(TclTkInterpreter) - # pr: callback procedure(Proc) - # arg: string to pass as block parameters of pr - # bind command of tcl/tk uses % replacement for parameters - # pr can receive replaced data using block parameter - # its format is specified by arg string - # You should not specify arg for the command like - # scrollbar with -command option, which receives parameters - # without specifying any replacement - def initialize(interp, pr, arg = nil) - # auto-generate tcl/tk representation (variable name) - exp = TclTk._newname("c_") - # initialize TclTkObject - super(interp._tcltkip(), exp) - # save parameters - @pr = pr - @arg = arg - # register in the module - TclTk._addcallback(self) - end - - # to_eval(): retuens string representation for @ip._eval_args - def to_eval() - if @arg - # bind replaces %s before calling ruby_fmt, so %%s is used - s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%%s")} #{@arg}}/ - else - s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%s")}}/ - end - - return s - end - - # _call(arg): invoke callback - # arg: callback parameter - def _call(arg) - @pr.call(arg) - end -end - -# class TclTkImage: tcl/tk images -class TclTkImage < TclTkCommand - - # initialize(interp, t, *args): - # generating image is done by TclTkImage.new() - # destrying is done by image delete (inconsistent, sigh) - # interp: interpreter(TclTkInterpreter) - # t: image type (photo, bitmap, etc.) - # *args: command argument - def initialize(interp, t, *args) - # auto-generate tcl/tk representation - exp = TclTk._newname("i_") - # initialize TclTkObject - super(interp._tcltkip(), exp) - # generate image - res = @ip._eval_args("image create", t, exp, *args) - fail("can't create Image") if res != exp - end -end - -# eof diff --git a/ext/tcltklib/sample/batsu.gif b/ext/tcltklib/sample/batsu.gif deleted file mode 100644 index 880cc73e09..0000000000 Binary files a/ext/tcltklib/sample/batsu.gif and /dev/null differ diff --git a/ext/tcltklib/sample/maru.gif b/ext/tcltklib/sample/maru.gif deleted file mode 100644 index 2c0202892e..0000000000 Binary files a/ext/tcltklib/sample/maru.gif and /dev/null differ diff --git a/ext/tcltklib/sample/sample0.rb b/ext/tcltklib/sample/sample0.rb deleted file mode 100644 index cd4c8069b4..0000000000 --- a/ext/tcltklib/sample/sample0.rb +++ /dev/null @@ -1,39 +0,0 @@ -#! /usr/local/bin/ruby -vd - -# tcltklib ¥é¥¤¥Ö¥é¥ê¤Î¥Æ¥¹¥È - -require "tcltklib" - -def test - # ¥¤¥ó¥¿¥×¥ê¥¿¤òÀ¸À®¤¹¤ë - ip1 = TclTkIp.new() - - # ɾ²Á¤·¤Æ¤ß¤ë - print ip1._return_value().inspect, "\n" - print ip1._eval("puts {abc}").inspect, "\n" - - # ¥Ü¥¿¥ó¤òºî¤Ã¤Æ¤ß¤ë - print ip1._return_value().inspect, "\n" - print ip1._eval("button .lab -text exit -command \"destroy .\"").inspect, - "\n" - print ip1._return_value().inspect, "\n" - print ip1._eval("pack .lab").inspect, "\n" - print ip1._return_value().inspect, "\n" - - # ¥¤¥ó¥¿¥×¥ê¥¿¤«¤é ruby ¥³¥Þ¥ó¥É¤òɾ²Á¤·¤Æ¤ß¤ë -# print ip1._eval(%q/ruby {print "print by ruby\n"}/).inspect, "\n" - print ip1._eval(%q+puts [ruby {print "print by ruby\n"; "puts by tcl/tk"}]+).inspect, "\n" - print ip1._return_value().inspect, "\n" - - # ¤â¤¦°ì¤Ä¥¤¥ó¥¿¥×¥ê¥¿¤òÀ¸À®¤·¤Æ¤ß¤ë - ip2 = TclTkIp.new() - ip2._eval("button .lab -text test -command \"puts test ; destroy .\"") - ip2._eval("pack .lab") - - TclTkLib.mainloop -end - -test -GC.start - -print "exit\n" diff --git a/ext/tcltklib/sample/sample1.rb b/ext/tcltklib/sample/sample1.rb deleted file mode 100644 index 28ba7b547a..0000000000 --- a/ext/tcltklib/sample/sample1.rb +++ /dev/null @@ -1,634 +0,0 @@ -#! /usr/local/bin/ruby -d -#! /usr/local/bin/ruby -# -d ¥ª¥×¥·¥ç¥ó¤òÉÕ¤±¤ë¤È, ¥Ç¥Ð¥Ã¥°¾ðÊó¤òɽ¼¨¤¹¤ë. - -# tcltk ¥é¥¤¥Ö¥é¥ê¤Î¥µ¥ó¥×¥ë - -# ¤Þ¤º, ¥é¥¤¥Ö¥é¥ê¤ò require ¤¹¤ë. -require "tcltk" - -# °Ê²¼¤Ï, Test1 ¤Î¥¤¥ó¥¹¥¿¥ó¥¹¤Î initialize() ¤Ç, -# tcl/tk ¤Ë´Ø¤¹¤ë½èÍý¤ò¹Ô¤¦Îã¤Ç¤¢¤ë. -# ɬ¤º¤·¤â¤½¤Î¤è¤¦¤Ë¤¹¤ëɬÍפÏ̵¤¯, -# (¤â¤·, ¤½¤¦¤·¤¿¤±¤ì¤Ð) class ¤Î³°¤Ç tcl/tk ¤Ë´Ø¤¹¤ë½èÍý¤ò¹Ô¤Ã¤Æ¤âÎɤ¤. - -class Test1 - # ½é´ü²½(¥¤¥ó¥¿¥×¥ê¥¿¤òÀ¸À®¤·¤Æ¥¦¥£¥¸¥§¥Ã¥È¤òÀ¸À®¤¹¤ë). - def initialize() - - #### »È¤¦Á°¤Î¤ª¤Þ¤¸¤Ê¤¤ - - # ¥¤¥ó¥¿¥×¥ê¥¿¤ÎÀ¸À®. - ip = TclTkInterpreter.new() - # ¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤ò c ¤ËÀßÄꤷ¤Æ¤ª¤¯. - c = ip.commands() - # »ÈÍѤ¹¤ë¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤ÏÊÑ¿ô¤ËÆþ¤ì¤Æ¤ª¤¯. - append, bind, button, destroy, incr, info, label, place, set, wm = - c.indexes( - "append", "bind", "button", "destroy", "incr", "info", "label", "place", - "set", "wm") - - #### tcl/tk ¤Î¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È(TclTkCommand)¤ÎÁàºî - - # ¼Â¹Ô¤¹¤ë»þ¤Ï, e() ¥á¥½¥Ã¥É¤ò»È¤¦. - # (°Ê²¼¤Ï, tcl/tk ¤Ë¤ª¤±¤ë info command r* ¤ò¼Â¹Ô.) - print info.e("command", "r*"), "\n" - # °ú¿ô¤Ï, ¤Þ¤È¤á¤¿Ê¸»úÎó¤Ë¤·¤Æ¤âƱ¤¸. - print info.e("command r*"), "\n" - # ÊÑ¿ô¤òÍѤ¤¤Ê¤¯¤È¤â¼Â¹Ô¤Ç¤­¤ë¤¬, ¸«¤¿¤á¤¬°­¤¤. - print c["info"].e("command", "r*"), "\n" - # ¥¤¥ó¥¿¥×¥ê¥¿¤Î¥á¥½¥Ã¥É¤È¤·¤Æ¤â¼Â¹Ô¤Ç¤­¤ë¤¬, ¸úΨ¤¬°­¤¤. - print ip.info("command", "r*"), "\n" - - #### - - # °Ê²¼, À¸À®¤·¤¿¥ª¥Ö¥¸¥§¥¯¥È¤ÏÊÑ¿ô¤ËÂåÆþ¤·¤Æ¤ª¤«¤Ê¤¤¤È - # GC ¤ÎÂоݤˤʤäƤ·¤Þ¤¦. - - #### tcl/tk ¤ÎÊÑ¿ô¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È(TclTkVariable)¤ÎÁàºî - - # À¸À®¤ÈƱ»þ¤ËÃͤòÀßÄꤹ¤ë. - v1 = TclTkVariable.new(ip, "20") - # Æɤ߽Ф·¤Ï get ¥á¥½¥Ã¥É¤ò»È¤¦. - print v1.get(), "\n" - # ÀßÄê¤Ï set ¥á¥½¥Ã¥É¤ò»È¤¦. - v1.set(40) - print v1.get(), "\n" - # set ¥³¥Þ¥ó¥É¤ò»È¤Ã¤ÆÆɤ߽Ф·, ÀßÄê¤Ï²Äǽ¤À¤¬¸«¤¿¤á¤¬°­¤¤. - # e() ¥á¥½¥Ã¥ÉÅù¤Î°ú¿ô¤ËľÀÜ TclTkObject ¤ä¿ôÃͤò½ñ¤¤¤Æ¤âÎɤ¤. - set.e(v1, 30) - print set.e(v1), "\n" - # tcl/tk ¤Î¥³¥Þ¥ó¥É¤ÇÊÑ¿ô¤òÁàºî¤Ç¤­¤ë. - incr.e(v1) - print v1.get(), "\n" - append.e(v1, 10) - print v1.get(), "\n" - - #### tcl/tk ¤Î¥¦¥£¥¸¥§¥Ã¥È¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È(TclTkWidget)¤ÎÁàºî - - # ¥ë¡¼¥È¥¦¥£¥¸¥§¥Ã¥È¤ò¼è¤ê½Ð¤¹. - root = ip.rootwidget() - # ¥¦¥£¥¸¥§¥Ã¥È¤ÎÁàºî. - root.e("configure -height 300 -width 300") - # ¥¿¥¤¥È¥ë¤òÉÕ¤±¤ë¤È¤­¤Ï wm ¤ò»È¤¦. - wm.e("title", root, $0) - # ¿Æ¥¦¥£¥¸¥§¥Ã¥È¤È¥³¥Þ¥ó¥É¤ò»ØÄꤷ¤Æ, ¥¦¥£¥¸¥§¥Ã¥È¤òºî¤ë. - l1 = TclTkWidget.new(ip, root, label, "-text {type `x' to print}") - # place ¤¹¤ë¤Èɽ¼¨¤µ¤ì¤ë. - place.e(l1, "-x 0 -rely 0.0 -relwidth 1 -relheight 0.1") - # ¥³¥Þ¥ó¥É̾¤Ïʸ»úÎó¤Ç»ØÄꤷ¤Æ¤âÎɤ¤¤¬, ¸«¤¿¤á¤¬°­¤¤. - # (¥³¥Þ¥ó¥É̾¤ÏÆÈΩ¤·¤¿°ú¿ô¤Ç¤Ê¤±¤ì¤Ð¤Ê¤é¤Ê¤¤.) - l2 = TclTkWidget.new(ip, root, "label") - # ¥¦¥£¥¸¥§¥Ã¥È¤ÎÁàºî. - l2.e("configure -text {type `q' to exit}") - place.e(l2, "-x 0 -rely 0.1 -relwidth 1 -relheight 0.1") - - #### tcl/tk ¤Î¥³¡¼¥ë¥Ð¥Ã¥¯¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È(TclTkCallback)¤ÎÁàºî - - # ¥³¡¼¥ë¥Ð¥Ã¥¯¤òÀ¸À®¤¹¤ë. - c1 = TclTkCallback.new(ip, proc{sample(ip, root)}) - # ¥³¡¼¥ë¥Ð¥Ã¥¯¤ò»ý¤Ä¥¦¥£¥¸¥§¥Ã¥È¤òÀ¸À®¤¹¤ë. - b1 = TclTkWidget.new(ip, root, button, "-text sample -command", c1) - place.e(b1, "-x 0 -rely 0.2 -relwidth 1 -relheight 0.1") - # ¥¤¥Ù¥ó¥È¥ë¡¼¥×¤òÈ´¤±¤ë¤Ë¤Ï destroy.e(root) ¤¹¤ë. - c2 = TclTkCallback.new(ip, proc{destroy.e(root)}) - b2 = TclTkWidget.new(ip, root, button, "-text exit -command", c2) - place.e(b2, "-x 0 -rely 0.3 -relwidth 1 -relheight 0.1") - - #### ¥¤¥Ù¥ó¥È¤Î¥Ð¥¤¥ó¥É - # script ¤ÎÄɲà (bind tag sequence +script) ¤Ïº£¤Î¤È¤³¤í¤Ç¤­¤Ê¤¤. - # (¥¤¥Æ¥ì¡¼¥¿ÊÑ¿ô¤ÎÀßÄ꤬¤¦¤Þ¤¯¤¤¤«¤Ê¤¤.) - - # ´ðËÜŪ¤Ë¤Ï¥¦¥£¥¸¥§¥Ã¥È¤ËÂФ¹¤ë¥³¡¼¥ë¥Ð¥Ã¥¯¤ÈƱ¤¸. - c3 = TclTkCallback.new(ip, proc{print("q pressed\n"); destroy.e(root)}) - bind.e(root, "q", c3) - # bind ¥³¥Þ¥ó¥É¤Ç % ÃÖ´¹¤Ë¤è¤ê¥Ñ¥é¥á¡¼¥¿¤ò¼õ¤±¼è¤ê¤¿¤¤¤È¤­¤Ï, - # proc{} ¤Î¸å¤í¤Ëʸ»úÎó¤Ç»ØÄꤹ¤ë¤È, - # ÃÖ´¹·ë²Ì¤ò¥¤¥Æ¥ì¡¼¥¿ÊÑ¿ô¤òÄ̤·¤Æ¼õ¤±¼è¤ë¤³¤È¤¬¤Ç¤­¤ë. - # ¤¿¤À¤· proc{} ¤Î¸å¤í¤Îʸ»úÎó¤Ï, - # bind ¥³¥Þ¥ó¥É¤ËÍ¿¤¨¤ë¥³¡¼¥ë¥Ð¥Ã¥¯°Ê³°¤Ç»ØÄꤷ¤Æ¤Ï¤¤¤±¤Ê¤¤. - c4 = TclTkCallback.new(ip, proc{|i| print("#{i} pressed\n")}, "%A") - bind.e(root, "x", c4) - # TclTkCallback ¤ò GC ¤ÎÂоݤˤ·¤¿¤±¤ì¤Ð, - # dcb() (¤Þ¤¿¤Ï deletecallbackkeys()) ¤¹¤ëɬÍפ¬¤¢¤ë. - cb = [c1, c2, c3, c4] - c5 = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, root, w)}, "%W") - bind.e(root, "", c5) - cb.push(c5) - - #### tcl/tk ¤Î¥¤¥á¡¼¥¸¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È(TclTkImage)¤ÎÁàºî - - # ¥Ç¡¼¥¿¤ò»ØÄꤷ¤ÆÀ¸À®¤¹¤ë. - i1 = TclTkImage.new(ip, "photo", "-file maru.gif") - # ¥é¥Ù¥ë¤ËÄ¥¤êÉÕ¤±¤Æ¤ß¤ë. - l3 = TclTkWidget.new(ip, root, label, "-relief raised -image", i1) - place.e(l3, "-x 0 -rely 0.4 -relwidth 0.2 -relheight 0.2") - # ¶õ¤Î¥¤¥á¡¼¥¸¤òÀ¸À®¤·¤Æ¸å¤ÇÁàºî¤¹¤ë. - i2 = TclTkImage.new(ip, "photo") - # ¥¤¥á¡¼¥¸¤òÁàºî¤¹¤ë. - i2.e("copy", i1) - i2.e("configure -gamma 0.5") - l4 = TclTkWidget.new(ip, root, label, "-relief raised -image", i2) - place.e(l4, "-relx 0.2 -rely 0.4 -relwidth 0.2 -relheight 0.2") - - #### - end - - # ¥µ¥ó¥×¥ë¤Î¤¿¤á¤Î¥¦¥£¥¸¥§¥Ã¥È¤òÀ¸À®¤¹¤ë. - def sample(ip, parent) - bind, button, destroy, grid, toplevel, wm = ip.commands().indexes( - "bind", "button", "destroy", "grid", "toplevel", "wm") - - ## toplevel - - # ¿·¤·¤¤¥¦¥¤¥ó¥É¥¦¤ò³«¤¯¤Ë¤Ï, toplevel ¤ò»È¤¦. - t1 = TclTkWidget.new(ip, parent, toplevel) - # ¥¿¥¤¥È¥ë¤òÉÕ¤±¤Æ¤ª¤¯ - wm.e("title", t1, "sample") - - # ¥¦¥£¥¸¥§¥Ã¥È¤¬Ç˲õ¤µ¤ì¤¿¤È¤­, ¥³¡¼¥ë¥Ð¥Ã¥¯¤¬ GC ¤ÎÂоݤˤʤë¤è¤¦¤Ë¤¹¤ë. - cb = [] - cb.push(c = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, t1, w)}, "%W")) - bind.e(t1, "", c) - - # ¥Ü¥¿¥ó¤ÎÀ¸À®. - wid = [] - # toplevel ¥¦¥£¥¸¥§¥Ã¥È¤òÇ˲õ¤¹¤ë¤Ë¤Ï destroy ¤¹¤ë. - cb.push(c = TclTkCallback.new(ip, proc{destroy.e(t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text close -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_label(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text label -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_button(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text button -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_checkbutton(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text checkbutton -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_radiobutton(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text radiobutton -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_scale(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text scale -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_entry(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text entry -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_text(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text text -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_raise(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text raise/lower -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_modal(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text message/modal -command", - c)) - cb.push(c = TclTkCallback.new(ip, proc{test_menu(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text menu -command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_listbox(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text listbox/scrollbar", - "-command", c)) - cb.push(c = TclTkCallback.new(ip, proc{test_canvas(ip, t1)})) - wid.push(TclTkWidget.new(ip, t1, button, "-text canvas -command", c)) - - # grid ¤Çɽ¼¨¤¹¤ë. - ro = co = 0 - wid.each{|w| - grid.e(w, "-row", ro, "-column", co, "-sticky news") - ro += 1 - if ro == 7 - ro = 0 - co += 1 - end - } - end - - # inittoplevel(ip, parent, title) - # °Ê²¼¤Î½èÍý¤ò¤Þ¤È¤á¤Æ¹Ô¤¦. - # 1. toplevel ¥¦¥£¥¸¥§¥Ã¥È¤òºîÀ®¤¹¤ë. - # 2. ¥³¡¼¥ë¥Ð¥Ã¥¯¤òÅÐÏ¿¤¹¤ëÇÛÎó¤òÍÑ°Õ¤·, toplevel ¥¦¥£¥¸¥§¥Ã¥È¤Î - # ¥¤¥Ù¥ó¥È¤Ë¥³¡¼¥ë¥Ð¥Ã¥¯¤òºï½ü¤¹¤ë¼ê³¤­¤òÅÐÏ¿¤¹¤ë. - # 3. ¥¯¥í¡¼¥º¥Ü¥¿¥ó¤òºî¤ë. - # ºîÀ®¤·¤¿ toplevel ¥¦¥£¥¸¥§¥Ã¥È, ¥¯¥í¡¼¥º¥Ü¥¿¥ó, ¥³¡¼¥ë¥Ð¥Ã¥¯ÅÐÏ¿ÍÑÊÑ¿ô - # ¤òÊÖ¤¹. - # ip: ¥¤¥ó¥¿¥×¥ê¥¿ - # parent: ¿Æ¥¦¥£¥¸¥§¥Ã¥È - # title: toplevel ¥¦¥£¥¸¥§¥Ã¥È¤Î¥¦¥¤¥ó¥É¥¦¤Î¥¿¥¤¥È¥ë - def inittoplevel(ip, parent, title) - bind, button, destroy, toplevel, wm = ip.commands().indexes( - "bind", "button", "destroy", "toplevel", "wm") - - # ¿·¤·¤¤¥¦¥¤¥ó¥É¥¦¤ò³«¤¯¤Ë¤Ï, toplevel ¤ò»È¤¦. - t1 = TclTkWidget.new(ip, parent, toplevel) - # ¥¿¥¤¥È¥ë¤òÉÕ¤±¤Æ¤ª¤¯ - wm.e("title", t1, title) - - # ¥¦¥£¥¸¥§¥Ã¥È¤¬Ç˲õ¤µ¤ì¤¿¤È¤­, ¥³¡¼¥ë¥Ð¥Ã¥¯¤¬ GC ¤ÎÂоݤˤʤë¤è¤¦¤Ë¤¹¤ë. - cb = [] - cb.push(c = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, t1, w)}, "%W")) - bind.e(t1, "", c) - # close ¥Ü¥¿¥ó¤òºî¤Ã¤Æ¤ª¤¯. - # toplevel ¥¦¥£¥¸¥§¥Ã¥È¤òÇ˲õ¤¹¤ë¤Ë¤Ï destroy ¤¹¤ë. - cb.push(c = TclTkCallback.new(ip, proc{destroy.e(t1)})) - b1 = TclTkWidget.new(ip, t1, button, "-text close -command", c) - - return t1, b1, cb - end - - # label ¤Î¥µ¥ó¥×¥ë. - def test_label(ip, parent) - button, global, label, pack = ip.commands().indexes( - "button", "global", "label", "pack") - t1, b1, cb = inittoplevel(ip, parent, "label") - - ## label - - # ¤¤¤í¤¤¤í¤Ê·Á¤Î¥é¥Ù¥ë. - l1 = TclTkWidget.new(ip, t1, label, "-text {default(flat)}") - l2 = TclTkWidget.new(ip, t1, label, "-text raised -relief raised") - l3 = TclTkWidget.new(ip, t1, label, "-text sunken -relief sunken") - l4 = TclTkWidget.new(ip, t1, label, "-text groove -relief groove") - l5 = TclTkWidget.new(ip, t1, label, "-text ridge -relief ridge") - l6 = TclTkWidget.new(ip, t1, label, "-bitmap error") - l7 = TclTkWidget.new(ip, t1, label, "-bitmap questhead") - - # pack ¤·¤Æ¤âɽ¼¨¤µ¤ì¤ë. - pack.e(b1, l1, l2, l3, l4, l5, l6, l7, "-pady 3") - - ## -textvariable - - # tcltk ¥é¥¤¥Ö¥é¥ê¤Î¼ÂÁõ¤Ç¤Ï, ¥³¡¼¥ë¥Ð¥Ã¥¯¤Ï tcl/tk ¤Î``¼ê³¤­''¤òÄ̤·¤Æ - # ¸Æ¤Ð¤ì¤ë. ¤·¤¿¤¬¤Ã¤Æ, ¥³¡¼¥ë¥Ð¥Ã¥¯¤ÎÃæ¤Ç(Âç°è)ÊÑ¿ô¤Ë¥¢¥¯¥»¥¹¤¹¤ë¤È¤­¤Ï, - # global ¤¹¤ëɬÍפ¬¤¢¤ë. - # global ¤¹¤ëÁ°¤ËÊÑ¿ô¤ËÃͤòÀßÄꤷ¤Æ¤·¤Þ¤¦¤È¥¨¥é¡¼¤Ë¤Ê¤ë¤Î¤Ç, - # tcl/tk ¤Ë¤ª¤±¤ëɽ¸½·Á¤À¤±À¸À®¤·¤Æ, ¼ÂºÝ¤ËÃͤòÀßÄꤷ¤Ê¤¤¤è¤¦¤Ë, - # 2 ÈÖÌܤΰú¿ô¤Ë¤Ï nil ¤òÍ¿¤¨¤ë. - v1 = TclTkVariable.new(ip, nil) - global.e(v1) - v1.set(100) - # -textvariable ¤ÇÊÑ¿ô¤òÀßÄꤹ¤ë. - l6 = TclTkWidget.new(ip, t1, label, "-textvariable", v1) - # ¥³¡¼¥ë¥Ð¥Ã¥¯¤ÎÃ椫¤éÊÑ¿ô¤òÁàºî¤¹¤ë. - cb.push(c = TclTkCallback.new(ip, proc{ - global.e(v1); v1.set(v1.get().to_i + 10)})) - b2 = TclTkWidget.new(ip, t1, button, "-text +10 -command", c) - cb.push(c = TclTkCallback.new(ip, proc{ - global.e(v1); v1.set(v1.get().to_i - 10)})) - b3 = TclTkWidget.new(ip, t1, button, "-text -10 -command", c) - pack.e(l6, b2, b3) - end - - # button ¤Î¥µ¥ó¥×¥ë. - def test_button(ip, parent) - button, pack = ip.commands().indexes("button", "pack") - t1, b1, cb = inittoplevel(ip, parent, "button") - - ## button - - # ¥³¡¼¥ë¥Ð¥Ã¥¯Æâ¤Ç»²¾È¤¹¤ëÊÑ¿ô¤ÏÀè¤ËÀë¸À¤·¤Æ¤ª¤«¤Ê¤±¤ì¤Ð¤Ê¤é¤Ê¤¤. - b3 = b4 = nil - cb.push(c = TclTkCallback.new(ip, proc{b3.e("flash"); b4.e("flash")})) - b2 = TclTkWidget.new(ip, t1, button, "-text flash -command", c) - cb.push(c = TclTkCallback.new(ip, proc{b2.e("configure -state normal")})) - b3 = TclTkWidget.new(ip, t1, button, "-text normal -command", c) - cb.push(c = TclTkCallback.new(ip, proc{b2.e("configure -state disabled")})) - b4 = TclTkWidget.new(ip, t1, button, "-text disable -command", c) - pack.e(b1, b2, b3, b4) - end - - # checkbutton ¤Î¥µ¥ó¥×¥ë. - def test_checkbutton(ip, parent) - checkbutton, global, pack = ip.commands().indexes( - "checkbutton", "global", "pack") - t1, b1, cb = inittoplevel(ip, parent, "checkbutton") - - ## checkbutton - - v1 = TclTkVariable.new(ip, nil) - global.e(v1) - # -variable ¤ÇÊÑ¿ô¤òÀßÄꤹ¤ë. - ch1 = TclTkWidget.new(ip, t1, checkbutton, "-onvalue on -offvalue off", - "-textvariable", v1, "-variable", v1) - pack.e(b1, ch1) - end - - # radiobutton ¤Î¥µ¥ó¥×¥ë. - def test_radiobutton(ip, parent) - global, label, pack, radiobutton = ip.commands().indexes( - "global", "label", "pack", "radiobutton") - t1, b1, cb = inittoplevel(ip, parent, "radiobutton") - - ## radiobutton - - v1 = TclTkVariable.new(ip, nil) - global.e(v1) - # ¥Ì¥ë¥¹¥È¥ê¥ó¥°¤Ï "{}" ¤Ç»ØÄꤹ¤ë. - v1.set("{}") - l1 = TclTkWidget.new(ip, t1, label, "-textvariable", v1) - # -variable ¤ÇƱ¤¸ÊÑ¿ô¤ò»ØÄꤹ¤ë¤ÈƱ¤¸¥°¥ë¡¼¥×¤Ë¤Ê¤ë. - ra1 = TclTkWidget.new(ip, t1, radiobutton, - "-text radio1 -value r1 -variable", v1) - ra2 = TclTkWidget.new(ip, t1, radiobutton, - "-text radio2 -value r2 -variable", v1) - cb.push(c = TclTkCallback.new(ip, proc{global.e(v1); v1.set("{}")})) - ra3 = TclTkWidget.new(ip, t1, radiobutton, - "-text clear -value r3 -variable", v1, "-command", c) - pack.e(b1, l1, ra1, ra2, ra3) - end - - # scale ¤Î¥µ¥ó¥×¥ë. - def test_scale(ip, parent) - global, pack, scale = ip.commands().indexes( - "global", "pack", "scale") - t1, b1, cb = inittoplevel(ip, parent, "scale") - - ## scale - - v1 = TclTkVariable.new(ip, nil) - global.e(v1) - v1.set(219) - # ¥³¡¼¥ë¥Ð¥Ã¥¯Æâ¤Ç»²¾È¤¹¤ëÊÑ¿ô¤ÏÀè¤ËÀë¸À¤·¤Æ¤ª¤«¤Ê¤±¤ì¤Ð¤Ê¤é¤Ê¤¤. - sca1 = nil - cb.push(c = TclTkCallback.new(ip, proc{global.e(v1); v = v1.get(); - sca1.e("configure -background", format("#%02x%02x%02x", v, v, v))})) - sca1 = TclTkWidget.new(ip, t1, scale, - "-label scale -orient h -from 0 -to 255 -variable", v1, "-command", c) - pack.e(b1, sca1) - end - - # entry ¤Î¥µ¥ó¥×¥ë. - def test_entry(ip, parent) - button, entry, global, pack = ip.commands().indexes( - "button", "entry", "global", "pack") - t1, b1, cb = inittoplevel(ip, parent, "entry") - - ## entry - - v1 = TclTkVariable.new(ip, nil) - global.e(v1) - # ¥Ì¥ë¥¹¥È¥ê¥ó¥°¤Ï "{}" ¤Ç»ØÄꤹ¤ë. - v1.set("{}") - en1 = TclTkWidget.new(ip, t1, entry, "-textvariable", v1) - cb.push(c = TclTkCallback.new(ip, proc{ - global.e(v1); print(v1.get(), "\n"); v1.set("{}")})) - b2 = TclTkWidget.new(ip, t1, button, "-text print -command", c) - pack.e(b1, en1, b2) - end - - # text ¤Î¥µ¥ó¥×¥ë. - def test_text(ip, parent) - button, pack, text = ip.commands().indexes( - "button", "pack", "text") - t1, b1, cb = inittoplevel(ip, parent, "text") - - ## text - - te1 = TclTkWidget.new(ip, t1, text) - cb.push(c = TclTkCallback.new(ip, proc{ - # 1 ¹ÔÌܤΠ0 ʸ»úÌܤ«¤éºÇ¸å¤Þ¤Ç¤òɽ¼¨¤·, ºï½ü¤¹¤ë. - print(te1.e("get 1.0 end")); te1.e("delete 1.0 end")})) - b2 = TclTkWidget.new(ip, t1, button, "-text print -command", c) - pack.e(b1, te1, b2) - end - - # raise/lower ¤Î¥µ¥ó¥×¥ë. - def test_raise(ip, parent) - button, frame, lower, pack, raise = ip.commands().indexes( - "button", "frame", "lower", "pack", "raise") - t1, b1, cb = inittoplevel(ip, parent, "raise/lower") - - ## raise/lower - - # button ¤ò±£¤¹¥Æ¥¹¥È¤Î¤¿¤á¤Ë, frame ¤ò»È¤¦. - f1 = TclTkWidget.new(ip, t1, frame) - # ¥³¡¼¥ë¥Ð¥Ã¥¯Æâ¤Ç»²¾È¤¹¤ëÊÑ¿ô¤ÏÀè¤ËÀë¸À¤·¤Æ¤ª¤«¤Ê¤±¤ì¤Ð¤Ê¤é¤Ê¤¤. - b2 = nil - cb.push(c = TclTkCallback.new(ip, proc{raise.e(f1, b2)})) - b2 = TclTkWidget.new(ip, t1, button, "-text raise -command", c) - cb.push(c = TclTkCallback.new(ip, proc{lower.e(f1, b2)})) - b3 = TclTkWidget.new(ip, t1, button, "-text lower -command", c) - lower.e(f1, b3) - - pack.e(b2, b3, "-in", f1) - pack.e(b1, f1) - end - - # modal ¤Ê¥¦¥£¥¸¥§¥Ã¥È¤Î¥µ¥ó¥×¥ë. - def test_modal(ip, parent) - button, frame, message, pack, tk_chooseColor, tk_getOpenFile, - tk_messageBox = ip.commands().indexes( - "button", "frame", "message", "pack", "tk_chooseColor", - "tk_getOpenFile", "tk_messageBox") - # ºÇ½é¤Ë load ¤µ¤ì¤Æ¤¤¤Ê¤¤¥é¥¤¥Ö¥é¥ê¤Ï ip.commands() ¤Ë¸ºß¤·¤Ê¤¤¤Î¤Ç, - # TclTkLibCommand ¤òÀ¸À®¤¹¤ëɬÍפ¬¤¢¤ë. - tk_dialog = TclTkLibCommand.new(ip, "tk_dialog") - t1, b1, cb = inittoplevel(ip, parent, "message/modal") - - ## message - - mes = "¤³¤ì¤Ï message ¥¦¥£¥¸¥§¥Ã¥È¤Î¥Æ¥¹¥È¤Ç¤¹." - mes += "°Ê²¼¤Ï modal ¤Ê¥¦¥£¥¸¥§¥Ã¥È¤Î¥Æ¥¹¥È¤Ç¤¹." - me1 = TclTkWidget.new(ip, t1, message, "-text {#{mes}}") - - ## modal - - # tk_messageBox - cb.push(c = TclTkCallback.new(ip, proc{ - print tk_messageBox.e("-type yesnocancel -message messageBox", - "-icon error -default cancel -title messageBox"), "\n"})) - b2 = TclTkWidget.new(ip, t1, button, "-text messageBox -command", c) - # tk_dialog - cb.push(c = TclTkCallback.new(ip, proc{ - # ¥¦¥£¥¸¥§¥Ã¥È̾¤òÀ¸À®¤¹¤ë¤¿¤á¤Ë¥À¥ß¡¼¤Î frame ¤òÀ¸À®. - print tk_dialog.e(TclTkWidget.new(ip, t1, frame), - "dialog dialog error 2 yes no cancel"), "\n"})) - b3 = TclTkWidget.new(ip, t1, button, "-text dialog -command", c) - # tk_chooseColor - cb.push(c = TclTkCallback.new(ip, proc{ - print tk_chooseColor.e("-title chooseColor"), "\n"})) - b4 = TclTkWidget.new(ip, t1, button, "-text chooseColor -command", c) - # tk_getOpenFile - cb.push(c = TclTkCallback.new(ip, proc{ - print tk_getOpenFile.e("-defaultextension .rb", - "-filetypes {{{Ruby Script} {.rb}} {{All Files} {*}}}", - "-title getOpenFile"), "\n"})) - b5 = TclTkWidget.new(ip, t1, button, "-text getOpenFile -command", c) - - pack.e(b1, me1, b2, b3, b4, b5) - end - - # menu ¤Î¥µ¥ó¥×¥ë. - def test_menu(ip, parent) - global, menu, menubutton, pack = ip.commands().indexes( - "global", "menu", "menubutton", "pack") - tk_optionMenu = TclTkLibCommand.new(ip, "tk_optionMenu") - t1, b1, cb = inittoplevel(ip, parent, "menu") - - ## menu - - # menubutton ¤òÀ¸À®¤¹¤ë. - mb1 = TclTkWidget.new(ip, t1, menubutton, "-text menu") - # menu ¤òÀ¸À®¤¹¤ë. - me1 = TclTkWidget.new(ip, mb1, menu) - # mb1 ¤«¤é me1 ¤¬µ¯Æ°¤µ¤ì¤ë¤è¤¦¤Ë¤¹¤ë. - mb1.e("configure -menu", me1) - - # cascade ¤Çµ¯Æ°¤µ¤ì¤ë menu ¤òÀ¸À®¤¹¤ë. - me11 = TclTkWidget.new(ip, me1, menu) - # radiobutton ¤Î¥µ¥ó¥×¥ë. - v1 = TclTkVariable.new(ip, nil); global.e(v1); v1.set("r1") - me11.e("add radiobutton -label radio1 -value r1 -variable", v1) - me11.e("add radiobutton -label radio2 -value r2 -variable", v1) - me11.e("add radiobutton -label radio3 -value r3 -variable", v1) - # cascade ¤Ë¤è¤ê mb11 ¤¬µ¯Æ°¤µ¤ì¤ë¤è¤¦¤Ë¤¹¤ë. - me1.e("add cascade -label cascade -menu", me11) - - # checkbutton ¤Î¥µ¥ó¥×¥ë. - v2 = TclTkVariable.new(ip, nil); global.e(v2); v2.set("none") - me1.e("add checkbutton -label check -variable", v2) - # separator ¤Î¥µ¥ó¥×¥ë. - me1.e("add separator") - # command ¤Î¥µ¥ó¥×¥ë. - v3 = nil - cb.push(c = TclTkCallback.new(ip, proc{ - global.e(v1, v2, v3); print "v1: ", v1.get(), ", v2: ", v2.get(), - ", v3: ", v3.get(), "\n"})) - me1.e("add command -label print -command", c) - - ## tk_optionMenu - - v3 = TclTkVariable.new(ip, nil); global.e(v3); v3.set("opt2") - om1 = TclTkWidget.new(ip, t1, tk_optionMenu, v3, "opt1 opt2 opt3 opt4") - - pack.e(b1, mb1, om1, "-side left") - end - - # listbox ¤Î¥µ¥ó¥×¥ë. - def test_listbox(ip, parent) - clipboard, frame, grid, listbox, lower, menu, menubutton, pack, scrollbar, - selection = ip.commands().indexes( - "clipboard", "frame", "grid", "listbox", "lower", "menu", "menubutton", - "pack", "scrollbar", "selection") - t1, b1, cb = inittoplevel(ip, parent, "listbox") - - ## listbox/scrollbar - - f1 = TclTkWidget.new(ip, t1, frame) - # ¥³¡¼¥ë¥Ð¥Ã¥¯Æâ¤Ç»²¾È¤¹¤ëÊÑ¿ô¤ÏÀè¤ËÀë¸À¤·¤Æ¤ª¤«¤Ê¤±¤ì¤Ð¤Ê¤é¤Ê¤¤. - li1 = sc1 = sc2 = nil - # ¼Â¹Ô»þ¤Ë, ¸å¤í¤Ë¥Ñ¥é¥á¡¼¥¿¤¬¤Ä¤¯¥³¡¼¥ë¥Ð¥Ã¥¯¤Ï, - # ¥¤¥Æ¥ì¡¼¥¿ÊÑ¿ô¤Ç¤½¤Î¥Ñ¥é¥á¡¼¥¿¤ò¼õ¤±¼è¤ë¤³¤È¤¬¤Ç¤­¤ë. - # (Ê£¿ô¤Î¥Ñ¥é¥á¡¼¥¿¤Ï¤Ò¤È¤Ä¤Îʸ»úÎó¤Ë¤Þ¤È¤á¤é¤ì¤ë.) - cb.push(c1 = TclTkCallback.new(ip, proc{|i| li1.e("xview", i)})) - cb.push(c2 = TclTkCallback.new(ip, proc{|i| li1.e("yview", i)})) - cb.push(c3 = TclTkCallback.new(ip, proc{|i| sc1.e("set", i)})) - cb.push(c4 = TclTkCallback.new(ip, proc{|i| sc2.e("set", i)})) - # listbox - li1 = TclTkWidget.new(ip, f1, listbox, - "-xscrollcommand", c3, "-yscrollcommand", c4, - "-selectmode extended -exportselection true") - for i in 1..20 - li1.e("insert end {line #{i} line #{i} line #{i} line #{i} line #{i}}") - end - # scrollbar - sc1 = TclTkWidget.new(ip, f1, scrollbar, "-orient horizontal -command", c1) - sc2 = TclTkWidget.new(ip, f1, scrollbar, "-orient vertical -command", c2) - - ## selection/clipboard - - mb1 = TclTkWidget.new(ip, t1, menubutton, "-text edit") - me1 = TclTkWidget.new(ip, mb1, menu) - mb1.e("configure -menu", me1) - cb.push(c = TclTkCallback.new(ip, proc{ - # clipboard ¤ò¥¯¥ê¥¢. - clipboard.e("clear") - # selection ¤«¤éʸ»úÎó¤òÆɤ߹þ¤ß clipboard ¤ËÄɲ乤ë. - clipboard.e("append {#{selection.e(\"get\")}}")})) - me1.e("add command -label {selection -> clipboard} -command",c) - cb.push(c = TclTkCallback.new(ip, proc{ - # li1 ¤ò¥¯¥ê¥¢. - li1.e("delete 0 end") - # clipboard ¤«¤éʸ»úÎó¤ò¼è¤ê½Ð¤·, 1 ¹Ô¤º¤Ä - selection.e("get -selection CLIPBOARD").split(/\n/).each{|line| - # li1 ¤ËÁÞÆþ¤¹¤ë. - li1.e("insert end {#{line}}")}})) - me1.e("add command -label {clipboard -> listbox} -command",c) - - grid.e(li1, "-row 0 -column 0 -sticky news") - grid.e(sc1, "-row 1 -column 0 -sticky ew") - grid.e(sc2, "-row 0 -column 1 -sticky ns") - grid.e("rowconfigure", f1, "0 -weight 100") - grid.e("columnconfigure", f1, "0 -weight 100") - f2 = TclTkWidget.new(ip, t1, frame) - lower.e(f2, b1) - pack.e(b1, mb1, "-in", f2, "-side left") - pack.e(f2, f1) - end - - # canvas ¤Î¥µ¥ó¥×¥ë. - def test_canvas(ip, parent) - canvas, lower, pack = ip.commands().indexes("canvas", "lower", "pack") - t1, b1, cb = inittoplevel(ip, parent, "canvas") - - ## canvas - - ca1 = TclTkWidget.new(ip, t1, canvas, "-width 400 -height 300") - lower.e(ca1, b1) - # rectangle ¤òºî¤ë. - idr = ca1.e("create rectangle 10 10 20 20") - # oval ¤òºî¤ë. - ca1.e("create oval 60 10 100 50") - # polygon ¤òºî¤ë. - ca1.e("create polygon 110 10 110 30 140 10") - # line ¤òºî¤ë. - ca1.e("create line 150 10 150 30 190 10") - # arc ¤òºî¤ë. - ca1.e("create arc 200 10 250 50 -start 0 -extent 90 -style pieslice") - # i1 ¤ÏËÜÅö¤Ï, ¤É¤³¤«¤ÇÇ˲õ¤·¤Ê¤±¤ì¤Ð¤Ê¤é¤Ê¤¤¤¬, ÌÌÅݤʤΤÇÊü¤Ã¤Æ¤¢¤ë. - i1 = TclTkImage.new(ip, "photo", "-file maru.gif") - # image ¤òºî¤ë. - ca1.e("create image 100 100 -image", i1) - # bitmap ¤òºî¤ë. - ca1.e("create bitmap 260 50 -bitmap questhead") - # text ¤òºî¤ë. - ca1.e("create text 320 50 -text {drag rectangle}") - # window ¤òºî¤ë(¥¯¥í¡¼¥º¥Ü¥¿¥ó). - ca1.e("create window 200 200 -window", b1) - - # bind ¤Ë¤è¤ê rectangle ¤ò drag ¤Ç¤­¤ë¤è¤¦¤Ë¤¹¤ë. - cb.push(c = TclTkCallback.new(ip, proc{|i| - # i ¤Ë x ¤È y ¤ò¼õ¤±¼è¤ë¤Î¤Ç, ¼è¤ê½Ð¤¹. - x, y = i.split(/ /); x = x.to_f; y = y.to_f - # ºÂɸ¤òÊѹ¹¤¹¤ë. - ca1.e("coords current #{x - 5} #{y - 5} #{x + 5} #{y + 5}")}, - # x, y ºÂɸ¤ò¶õÇò¤Ç¶èÀڤ俤â¤Î¤ò¥¤¥Æ¥ì¡¼¥¿ÊÑ¿ô¤ØÅϤ¹¤è¤¦¤Ë»ØÄê. - "%x %y")) - # rectangle ¤Ë bind ¤¹¤ë. - ca1.e("bind", idr, "", c) - - pack.e(ca1) - end -end - -# test driver - -if ARGV.size == 0 - print "#{$0} n ¤Ç, n ¸Ä¤Î¥¤¥ó¥¿¥×¥ê¥¿¤òµ¯Æ°¤·¤Þ¤¹.\n" - n = 1 -else - n = ARGV[0].to_i -end - -print "start\n" -ip = [] - -# ¥¤¥ó¥¿¥×¥ê¥¿, ¥¦¥£¥¸¥§¥Ã¥ÈÅù¤ÎÀ¸À®. -for i in 1 .. n - ip.push(Test1.new()) -end - -# ÍÑ°Õ¤¬¤Ç¤­¤¿¤é¥¤¥Ù¥ó¥È¥ë¡¼¥×¤ËÆþ¤ë. -TclTk.mainloop() -print "exit from mainloop\n" - -# ¥¤¥ó¥¿¥×¥ê¥¿¤¬ GC ¤µ¤ì¤ë¤«¤Î¥Æ¥¹¥È. -ip = [] -print "GC.start\n" if $DEBUG -GC.start() if $DEBUG -print "end\n" - -exit - -# end diff --git a/ext/tcltklib/sample/sample2.rb b/ext/tcltklib/sample/sample2.rb deleted file mode 100644 index 969d8de09a..0000000000 --- a/ext/tcltklib/sample/sample2.rb +++ /dev/null @@ -1,449 +0,0 @@ -#!/usr/local/bin/ruby -#----------------------> pretty simple othello game <----------------------- -# othello.rb -# -# version 0.3 -# maeda shugo (shuto@po.aianet.ne.jp) -#--------------------------------------------------------------------------- - -# Sep. 17, 1997 modified by Y. Shigehiro for tcltk library -# maeda shugo (shugo@po.aianet.ne.jp) »á¤Ë¤è¤ë -# (ruby/tk ¤Ç½ñ¤«¤ì¤Æ¤¤¤¿) ruby ¤Î¥µ¥ó¥×¥ë¥×¥í¥°¥é¥à -# http://www.aianet.or.jp/~shugo/ruby/othello.rb.gz -# ¤ò tcltk ¥é¥¤¥Ö¥é¥ê¤ò»È¤¦¤è¤¦¤Ë, µ¡³£Åª¤ËÊѹ¹¤·¤Æ¤ß¤Þ¤·¤¿. -# -# ¤Ê¤ë¤Ù¤¯¥ª¥ê¥¸¥Ê¥ë¤ÈƱ¤¸¤Ë¤Ê¤ë¤è¤¦¤Ë¤·¤Æ¤¢¤ê¤Þ¤¹. - -require "observer" -require "tcltk" -$ip = TclTkInterpreter.new() -$root = $ip.rootwidget() -$button, $canvas, $checkbutton, $frame, $label, $pack, $update, $wm = - $ip.commands().indexes( - "button", "canvas", "checkbutton", "frame", "label", "pack", "update", "wm") - -class Othello - - EMPTY = 0 - BLACK = 1 - WHITE = - BLACK - - attr :in_com_turn - attr :game_over - - class Board - - include Observable - - DIRECTIONS = [ - [-1, -1], [-1, 0], [-1, 1], - [ 0, -1], [ 0, 1], - [ 1, -1], [ 1, 0], [ 1, 1] - ] - - attr :com_disk, TRUE - - def initialize(othello) - @othello = othello - reset - end - - def notify_observers(*arg) - if @observer_peers != nil - super(*arg) - end - end - - def reset - @data = [ - [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY], - [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY], - [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY], - [EMPTY, EMPTY, EMPTY, WHITE, BLACK, EMPTY, EMPTY, EMPTY], - [EMPTY, EMPTY, EMPTY, BLACK, WHITE, EMPTY, EMPTY, EMPTY], - [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY], - [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY], - [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY] - ] - changed - notify_observers - end - - def man_disk - return - @com_disk - end - - def other_disk(disk) - return - disk - end - - def get_disk(row, col) - return @data[row][col] - end - - def reverse_to(row, col, my_disk, dir_y, dir_x) - y = row - x = col - begin - y += dir_y - x += dir_x - if y < 0 || x < 0 || y > 7 || x > 7 || - @data[y][x] == EMPTY - return - end - end until @data[y][x] == my_disk - begin - @data[y][x] = my_disk - changed - notify_observers(y, x) - y -= dir_y - x -= dir_x - end until y == row && x == col - end - - def put_disk(row, col, disk) - @data[row][col] = disk - changed - notify_observers(row, col) - DIRECTIONS.each do |dir| - reverse_to(row, col, disk, *dir) - end - end - - def count_disk(disk) - num = 0 - @data.each do |rows| - rows.each do |d| - if d == disk - num += 1 - end - end - end - return num - end - - def count_point_to(row, col, my_disk, dir_y, dir_x) - return 0 if @data[row][col] != EMPTY - count = 0 - loop do - row += dir_y - col += dir_x - break if row < 0 || col < 0 || row > 7 || col > 7 - case @data[row][col] - when my_disk - return count - when other_disk(my_disk) - count += 1 - when EMPTY - break - end - end - return 0 - end - - def count_point(row, col, my_disk) - count = 0 - DIRECTIONS.each do |dir| - count += count_point_to(row, col, my_disk, *dir) - end - return count - end - - def corner?(row, col) - return (row == 0 && col == 0) || - (row == 0 && col == 7) || - (row == 7 && col == 0) || - (row == 7 && col == 7) - end - - def search(my_disk) - max = 0 - max_row = nil - max_col = nil - for row in 0 .. 7 - for col in 0 .. 7 - buf = count_point(row, col, my_disk) - if (corner?(row, col) && buf > 0) || max < buf - max = buf - max_row = row - max_col = col - end - end - end - return max_row, max_col - end - end #--------------------------> class Board ends here - - class BoardView < TclTkWidget - - BACK_GROUND_COLOR = "DarkGreen" - HILIT_BG_COLOR = "green" - BORDER_COLOR = "black" - BLACK_COLOR = "black" - WHITE_COLOR = "white" - STOP_COLOR = "red" - - attr :left - attr :top - attr :right - attr :bottom - - class Square - - attr :oval, TRUE - attr :row - attr :col - - def initialize(view, row, col) - @view = view - @id = @view.e("create rectangle", *view.tk_rect(view.left + col, - view.top + row, - view.left + col + 1, - view.top + row + 1)) - @row = row - @col = col - @view.e("itemconfigure", @id, - "-width 0.5m -outline #{BORDER_COLOR}") - @view.e("bind", @id, "", TclTkCallback.new($ip, proc{ - if @oval == nil - view.e("itemconfigure", @id, "-fill #{HILIT_BG_COLOR}") - end - })) - @view.e("bind", @id, "", TclTkCallback.new($ip, proc{ - view.e("itemconfigure", @id, "-fill #{BACK_GROUND_COLOR}") - })) - @view.e("bind", @id, "", TclTkCallback.new($ip, - proc{ - view.click_square(self) - })) - end - - def blink(color) - @view.e("itemconfigure", @id, "-fill #{color}") - $update.e() - sleep(0.1) - @view.e("itemconfigure", @id, "-fill #{BACK_GROUND_COLOR}") - end - end #-----------------------> class Square ends here - - def initialize(othello, board) - super($ip, $root, $canvas) - @othello = othello - @board = board - @board.add_observer(self) - - @squares = Array.new(8) - for i in 0 .. 7 - @squares[i] = Array.new(8) - end - @left = 1 - @top = 0.5 - @right = @left + 8 - @bottom = @top + 8 - - i = self.e("create rectangle", *tk_rect(@left, @top, @right, @bottom)) - self.e("itemconfigure", i, - "-width 1m -outline #{BORDER_COLOR} -fill #{BACK_GROUND_COLOR}") - - for row in 0 .. 7 - for col in 0 .. 7 - @squares[row][col] = Square.new(self, row, col) - end - end - - update - end - - def tk_rect(left, top, right, bottom) - return left.to_s + "c", top.to_s + "c", - right.to_s + "c", bottom.to_s + "c" - end - - def clear - each_square do |square| - if square.oval != nil - self.e("delete", square.oval) - square.oval = nil - end - end - end - - def draw_disk(row, col, disk) - if disk == EMPTY - if @squares[row][col].oval != nil - self.e("delete", @squares[row][col].oval) - @squares[row][col].oval = nil - end - return - end - - $update.e() - sleep(0.05) - oval = @squares[row][col].oval - if oval == nil - oval = self.e("create oval", *tk_rect(@left + col + 0.2, - @top + row + 0.2, - @left + col + 0.8, - @top + row + 0.8)) - @squares[row][col].oval = oval - end - case disk - when BLACK - color = BLACK_COLOR - when WHITE - color = WHITE_COLOR - else - fail format("Unknown disk type: %d", disk) - end - self.e("itemconfigure", oval, "-outline #{color} -fill #{color}") - end - - def update(row = nil, col = nil) - if row && col - draw_disk(row, col, @board.get_disk(row, col)) - else - each_square do |square| - draw_disk(square.row, square.col, - @board.get_disk(square.row, square.col)) - end - end - @othello.show_point - end - - def each_square - @squares.each do |rows| - rows.each do |square| - yield(square) - end - end - end - - def click_square(square) - if @othello.in_com_turn || @othello.game_over || - @board.count_point(square.row, - square.col, - @board.man_disk) == 0 - square.blink(STOP_COLOR) - return - end - @board.put_disk(square.row, square.col, @board.man_disk) - @othello.com_turn - end - - private :draw_disk - public :update - end #----------------------> class BoardView ends here - - def initialize - @msg_label = TclTkWidget.new($ip, $root, $label) - $pack.e(@msg_label) - - @board = Board.new(self) - @board_view = BoardView.new(self, @board) - #### added by Y. Shigehiro - ## board_view ¤ÎÂ礭¤µ¤òÀßÄꤹ¤ë. - x1, y1, x2, y2 = @board_view.e("bbox all").split(/ /).collect{|i| i.to_f} - @board_view.e("configure -width", x2 - x1) - @board_view.e("configure -height", y2 - y1) - ## scrollregion ¤òÀßÄꤹ¤ë. - @board_view.e("configure -scrollregion {", @board_view.e("bbox all"), - "}") - #### ¤³¤³¤Þ¤Ç - $pack.e(@board_view, "-fill both -expand true") - - panel = TclTkWidget.new($ip, $root, $frame) - - @play_black = TclTkWidget.new($ip, panel, $checkbutton, - "-text {com is black} -command", TclTkCallback.new($ip, proc{ - switch_side - })) - $pack.e(@play_black, "-side left") - - quit = TclTkWidget.new($ip, panel, $button, "-text Quit -command", - TclTkCallback.new($ip, proc{ - exit - })) - $pack.e(quit, "-side right -fill x") - - reset = TclTkWidget.new($ip, panel, $button, "-text Reset -command", - TclTkCallback.new($ip, proc{ - reset_game - })) - $pack.e(reset, "-side right -fill x") - - $pack.e(panel, "-side bottom -fill x") - -# root = Tk.root - $wm.e("title", $root, "Othello") - $wm.e("iconname", $root, "Othello") - - @board.com_disk = WHITE - @game_over = FALSE - - TclTk.mainloop - end - - def switch_side - if @in_com_turn - @play_black.e("toggle") - else - @board.com_disk = @board.man_disk - com_turn unless @game_over - end - end - - def reset_game - if @board.com_disk == BLACK - @board.com_disk = WHITE - @play_black.e("toggle") - end - @board_view.clear - @board.reset - $wm.e("title", $root, "Othello") - @game_over = FALSE - end - - def com_turn - @in_com_turn = TRUE - $update.e() - sleep(0.5) - begin - com_disk = @board.count_disk(@board.com_disk) - man_disk = @board.count_disk(@board.man_disk) - if @board.count_disk(EMPTY) == 0 - if man_disk == com_disk - $wm.e("title", $root, "{Othello - Draw!}") - elsif man_disk > com_disk - $wm.e("title", $root, "{Othello - You Win!}") - else - $wm.e("title", $root, "{Othello - You Loose!}") - end - @game_over = TRUE - break - elsif com_disk == 0 - $wm.e("title", $root, "{Othello - You Win!}") - @game_over = TRUE - break - elsif man_disk == 0 - $wm.e("title", $root, "{Othello - You Loose!}") - @game_over = TRUE - break - end - row, col = @board.search(@board.com_disk) - break if row == nil || col == nil - @board.put_disk(row, col, @board.com_disk) - end while @board.search(@board.man_disk) == [nil, nil] - @in_com_turn = FALSE - end - - def show_point - black = @board.count_disk(BLACK) - white = @board.count_disk(WHITE) - @msg_label.e("configure -text", - %Q/{#{format("BLACK: %.2d WHITE: %.2d", black, white)}}/) - end -end #----------------------> class Othello ends here - -Othello.new - -#----------------------------------------------> othello.rb ends here diff --git a/ext/tcltklib/stubs.c b/ext/tcltklib/stubs.c deleted file mode 100644 index 69a5d6d3c0..0000000000 --- a/ext/tcltklib/stubs.c +++ /dev/null @@ -1,86 +0,0 @@ -#if defined USE_TCL_STUBS && defined USE_TK_STUBS -#include -#include -#include "ruby.h" - -#if defined _WIN32 || defined __CYGWIN__ -# include - typedef HINSTANCE DL_HANDLE; -# define DL_OPEN LoadLibrary -# define DL_SYM GetProcAddress -# define TCL_INDEX 4 -# define TK_INDEX 3 -# define TCL_NAME "tcl89%s" -# define TK_NAME "tk89%s" -# undef DLEXT -# define DLEXT ".dll" -#elif defined HAVE_DLOPEN -# include - typedef void *DL_HANDLE; -# define DL_OPEN(file) dlopen(file, RTLD_LAZY|RTLD_GLOBAL) -# define DL_SYM dlsym -# define TCL_INDEX 8 -# define TK_INDEX 7 -# define TCL_NAME "libtcl8.9%s" -# define TK_NAME "libtk8.9%s" -#endif - -int -ruby_tcltk_stubs() -{ - DL_HANDLE tcl_dll; - DL_HANDLE tk_dll; - Tcl_Interp *(*p_Tcl_CreateInterp)(); - int (*p_Tk_Init) _((Tcl_Interp *)); - Tcl_Interp *tcl_ip; - int n; - char *ruby_tcl_dll; - char *ruby_tk_dll; - char tcl_name[20]; - char tk_name[20]; - - ruby_tcl_dll = getenv("RUBY_TCL_DLL"); - ruby_tk_dll = getenv("RUBY_TK_DLL"); - if (ruby_tcl_dll && ruby_tk_dll) { - tcl_dll = (DL_HANDLE)DL_OPEN(ruby_tcl_dll); - tk_dll = (DL_HANDLE)DL_OPEN(ruby_tk_dll); - } else { - snprintf(tcl_name, sizeof tcl_name, TCL_NAME, DLEXT); - snprintf(tk_name, sizeof tk_name, TK_NAME, DLEXT); - /* examine from 8.9 to 8.1 */ - for (n = '9'; n > '0'; n--) { - tcl_name[TCL_INDEX] = n; - tk_name[TK_INDEX] = n; - tcl_dll = (DL_HANDLE)DL_OPEN(tcl_name); - tk_dll = (DL_HANDLE)DL_OPEN(tk_name); - if (tcl_dll && tk_dll) - break; - } - } - - if (!tcl_dll || !tk_dll) - return -1; - - p_Tcl_CreateInterp = (Tcl_Interp *(*)())DL_SYM(tcl_dll, "Tcl_CreateInterp"); - if (!p_Tcl_CreateInterp) - return -2; - - tcl_ip = (*p_Tcl_CreateInterp)(); - if (!tcl_ip) - return -3; - - p_Tk_Init = (int (*) _((Tcl_Interp *)))DL_SYM(tk_dll, "Tk_Init"); - if (!p_Tk_Init) - return -4; - (*p_Tk_Init)(tcl_ip); - - if (!Tcl_InitStubs(tcl_ip, "8.1", 0)) - return -5; - if (!Tk_InitStubs(tcl_ip, "8.1", 0)) - return -6; - - Tcl_DeleteInterp(tcl_ip); - - return 0; -} -#endif diff --git a/ext/tcltklib/tcltklib.c b/ext/tcltklib/tcltklib.c deleted file mode 100644 index 7acbacdd94..0000000000 --- a/ext/tcltklib/tcltklib.c +++ /dev/null @@ -1,561 +0,0 @@ -/* - * tcltklib.c - * Aug. 27, 1997 Y. Shigehiro - * Oct. 24, 1997 Y. Matsumoto - */ - -#include "ruby.h" -#include "rubysig.h" -#undef EXTERN /* avoid conflict with tcl.h of tcl8.2 or before */ -#include -#include -#include -#include - -#ifdef __MACOS__ -# include -# include -#endif - -/* for ruby_debug */ - -#define DUMP1(ARG1) if (ruby_debug) { fprintf(stderr, "tcltklib: %s\n", ARG1);} -#define DUMP2(ARG1, ARG2) if (ruby_debug) { fprintf(stderr, "tcltklib: ");\ -fprintf(stderr, ARG1, ARG2); fprintf(stderr, "\n"); } -/* -#define DUMP1(ARG1) -#define DUMP2(ARG1, ARG2) -*/ - -/* for callback break & continue */ -static VALUE eTkCallbackBreak; -static VALUE eTkCallbackContinue; - -static VALUE ip_invoke_real _((int, VALUE*, VALUE)); - -/* from tkAppInit.c */ - -#if !defined __MINGW32__ -/* - * The following variable is a special hack that is needed in order for - * Sun shared libraries to be used for Tcl. - */ - -extern int matherr(); -int *tclDummyMathPtr = (int *) matherr; -#endif - -/*---- module TclTkLib ----*/ - -struct invoke_queue { - int argc; - VALUE *argv; - VALUE obj; - int done; - VALUE result; - VALUE thread; - struct invoke_queue *next; -}; - -static struct invoke_queue *iqueue; -static VALUE main_thread; - -/* Tk_ThreadTimer */ -static Tcl_TimerToken timer_token; - -/* timer callback */ -static void -_timer_for_tcl(clientData) - ClientData clientData; -{ - struct invoke_queue *q, *tmp; - VALUE thread; - - Tk_DeleteTimerHandler(timer_token); - timer_token = Tk_CreateTimerHandler(100, _timer_for_tcl, (ClientData)0); - - CHECK_INTS; - q = iqueue; - while (q) { - tmp = q; - q = q->next; - if (!tmp->done) { - tmp->done = 1; - tmp->result = ip_invoke_real(tmp->argc, tmp->argv, tmp->obj); - thread = tmp->thread; - tmp = tmp->next; - rb_thread_run(thread); - } - } - rb_thread_schedule(); -} - -/* execute Tk_MainLoop */ -static VALUE -lib_mainloop(self) - VALUE self; -{ - timer_token = Tk_CreateTimerHandler(100, _timer_for_tcl, (ClientData)0); - DUMP1("start Tk_Mainloop"); - Tk_MainLoop(); - DUMP1("stop Tk_Mainloop"); - Tk_DeleteTimerHandler(timer_token); - - return Qnil; -} - -/*---- class TclTkIp ----*/ -struct tcltkip { - Tcl_Interp *ip; /* the interpreter */ - int return_value; /* return value */ -}; - -/* Tcl command `ruby' */ -static VALUE -ip_eval_rescue(failed, einfo) - VALUE *failed; - VALUE einfo; -{ - *failed = einfo; - return Qnil; -} - -/* restart Tk */ -static VALUE -lib_restart(self) - VALUE self; -{ - struct tcltkip *ptr; /* tcltkip data struct */ - - /* get the data struct */ - Data_Get_Struct(self, struct tcltkip, ptr); - - /* destroy the root wdiget */ - ptr->return_value = Tcl_Eval(ptr->ip, "destroy ."); - /* ignore ERROR */ - DUMP2("(TCL_Eval result) %d", ptr->return_value); - - /* execute Tk_Init */ - DUMP1("Tk_Init"); - if (Tk_Init(ptr->ip) == TCL_ERROR) { - rb_raise(rb_eRuntimeError, "%s", ptr->ip->result); - } - - return Qnil; -} - -static int -#if TCL_MAJOR_VERSION >= 8 -ip_ruby(clientData, interp, argc, argv) - ClientData clientData; - Tcl_Interp *interp; - int argc; - Tcl_Obj *CONST argv[]; -#else -ip_ruby(clientData, interp, argc, argv) - ClientData clientData; - Tcl_Interp *interp; - int argc; - char *argv[]; -#endif -{ - VALUE res; - int old_trapflg; - VALUE failed = 0; - char *arg; - int dummy; - - /* ruby command has 1 arg. */ - if (argc != 2) { - rb_raise(rb_eArgError, "wrong # of arguments (%d for 1)", argc); - } - - /* get C string from Tcl object */ -#if TCL_MAJOR_VERSION >= 8 - arg = Tcl_GetStringFromObj(argv[1], &dummy); -#else - arg = argv[1]; -#endif - - /* evaluate the argument string by ruby */ - DUMP2("rb_eval_string(%s)", arg); - old_trapflg = rb_trap_immediate; - rb_trap_immediate = 0; - res = rb_rescue2(rb_eval_string, (VALUE)arg, - ip_eval_rescue, (VALUE)&failed, - rb_eStandardError, rb_eScriptError, 0); - rb_trap_immediate = old_trapflg; - - Tcl_ResetResult(interp); - if (failed) { - VALUE eclass = CLASS_OF(failed); - Tcl_AppendResult(interp, StringValuePtr(failed), (char*)NULL); - if (eclass == eTkCallbackBreak) { - return TCL_BREAK; - } else if (eclass == eTkCallbackContinue) { - return TCL_CONTINUE; - } else { - return TCL_ERROR; - } - } - - /* result must be string or nil */ - if (NIL_P(res)) { - DUMP1("(rb_eval_string result) nil"); - return TCL_OK; - } - - /* copy result to the tcl interpreter */ - DUMP2("(rb_eval_string result) %s", StringValuePtr(res)); - DUMP1("Tcl_AppendResult"); - Tcl_AppendResult(interp, StringValuePtr(res), (char *)NULL); - - return TCL_OK; -} - -/* destroy interpreter */ -static void -ip_free(ptr) - struct tcltkip *ptr; -{ - DUMP1("Tcl_DeleteInterp"); - Tcl_DeleteInterp(ptr->ip); - free(ptr); -} - -/* create and initialize interpreter */ -static VALUE -ip_new(self) - VALUE self; -{ - struct tcltkip *ptr; /* tcltkip data struct */ - VALUE obj; /* newly created object */ - - /* create object */ - obj = Data_Make_Struct(self, struct tcltkip, 0, ip_free, ptr); - ptr->return_value = 0; - - /* from Tk_Main() */ - DUMP1("Tcl_CreateInterp"); - ptr->ip = Tcl_CreateInterp(); - - /* from Tcl_AppInit() */ - DUMP1("Tcl_Init"); - if (Tcl_Init(ptr->ip) == TCL_ERROR) { - rb_raise(rb_eRuntimeError, "%s", ptr->ip->result); - } - DUMP1("Tk_Init"); - if (Tk_Init(ptr->ip) == TCL_ERROR) { - rb_raise(rb_eRuntimeError, "%s", ptr->ip->result); - } - DUMP1("Tcl_StaticPackage(\"Tk\")"); - Tcl_StaticPackage(ptr->ip, "Tk", Tk_Init, - (Tcl_PackageInitProc *) NULL); - - /* add ruby command to the interpreter */ -#if TCL_MAJOR_VERSION >= 8 - DUMP1("Tcl_CreateObjCommand(\"ruby\")"); - Tcl_CreateObjCommand(ptr->ip, "ruby", ip_ruby, (ClientData)NULL, - (Tcl_CmdDeleteProc *)NULL); -#else - DUMP1("Tcl_CreateCommand(\"ruby\")"); - Tcl_CreateCommand(ptr->ip, "ruby", ip_ruby, (ClientData)NULL, - (Tcl_CmdDeleteProc *)NULL); -#endif - - return obj; -} - -/* eval string in tcl by Tcl_Eval() */ -static VALUE -ip_eval(self, str) - VALUE self; - VALUE str; -{ - char *s; - char *buf; /* Tcl_Eval requires re-writable string region */ - struct tcltkip *ptr; /* tcltkip data struct */ - - /* get the data struct */ - Data_Get_Struct(self, struct tcltkip, ptr); - - /* call Tcl_Eval() */ - s = StringValuePtr(str); - buf = ALLOCA_N(char, strlen(s)+1); - strcpy(buf, s); - DUMP2("Tcl_Eval(%s)", buf); - ptr->return_value = Tcl_Eval(ptr->ip, buf); - if (ptr->return_value == TCL_ERROR) { - rb_raise(rb_eRuntimeError, "%s", ptr->ip->result); - } - DUMP2("(TCL_Eval result) %d", ptr->return_value); - - /* pass back the result (as string) */ - return(rb_str_new2(ptr->ip->result)); -} - - -static VALUE -ip_toUTF8(self, str, encodename) - VALUE self; - VALUE str; - VALUE encodename; -{ -#ifdef TCL_UTF_MAX - Tcl_Interp *interp; - Tcl_Encoding encoding; - Tcl_DString dstr; - struct tcltkip *ptr; - char *buf; - - Data_Get_Struct(self,struct tcltkip, ptr); - interp = ptr->ip; - - StringValue(encodename); - StringValue(str); - encoding = Tcl_GetEncoding(interp, RSTRING(encodename)->ptr); - buf = ALLOCA_N(char,strlen(RSTRING(str)->ptr)+1); - strcpy(buf, RSTRING(str)->ptr); - - Tcl_DStringInit(&dstr); - Tcl_DStringFree(&dstr); - Tcl_ExternalToUtfDString(encoding,buf,strlen(buf),&dstr); - str = rb_str_new2(Tcl_DStringValue(&dstr)); - - Tcl_FreeEncoding(encoding); - Tcl_DStringFree(&dstr); -#endif - return str; -} - -static VALUE -ip_fromUTF8(self, str, encodename) - VALUE self; - VALUE str; - VALUE encodename; -{ -#ifdef TCL_UTF_MAX - Tcl_Interp *interp; - Tcl_Encoding encoding; - Tcl_DString dstr; - struct tcltkip *ptr; - char *buf; - - Data_Get_Struct(self,struct tcltkip, ptr); - interp = ptr->ip; - - StringValue(encodename); - StringValue(str); - encoding = Tcl_GetEncoding(interp,RSTRING(encodename)->ptr); - buf = ALLOCA_N(char,strlen(RSTRING(str)->ptr)+1); - strcpy(buf,RSTRING(str)->ptr); - - Tcl_DStringInit(&dstr); - Tcl_DStringFree(&dstr); - Tcl_UtfToExternalDString(encoding,buf,strlen(buf),&dstr); - str = rb_str_new2(Tcl_DStringValue(&dstr)); - - Tcl_FreeEncoding(encoding); - Tcl_DStringFree(&dstr); - -#endif - return str; -} - - -static VALUE -ip_invoke_real(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - VALUE v; - struct tcltkip *ptr; /* tcltkip data struct */ - int i; - Tcl_CmdInfo info; - char *cmd, *s; - char **av = (char **)NULL; -#if TCL_MAJOR_VERSION >= 8 - Tcl_Obj **ov = (Tcl_Obj **)NULL; - Tcl_Obj *resultPtr; -#endif - - /* get the data struct */ - Data_Get_Struct(obj, struct tcltkip, ptr); - - /* get the command name string */ - v = argv[0]; - cmd = StringValuePtr(v); - - /* map from the command name to a C procedure */ - if (!Tcl_GetCommandInfo(ptr->ip, cmd, &info)) { - rb_raise(rb_eNameError, "invalid command name `%s'", cmd); - } - - /* memory allocation for arguments of this command */ -#if TCL_MAJOR_VERSION >= 8 - if (info.isNativeObjectProc) { - /* object interface */ - ov = (Tcl_Obj **)ALLOCA_N(Tcl_Obj *, argc+1); - for (i = 0; i < argc; ++i) { - v = argv[i]; - s = StringValuePtr(v); - ov[i] = Tcl_NewStringObj(s, RSTRING(v)->len); - Tcl_IncrRefCount(ov[i]); - } - ov[argc] = (Tcl_Obj *)NULL; - } - else -#endif - { - /* string interface */ - av = (char **)ALLOCA_N(char *, argc+1); - for (i = 0; i < argc; ++i) { - v = argv[i]; - s = StringValuePtr(v); - av[i] = ALLOCA_N(char, strlen(s)+1); - strcpy(av[i], s); - } - av[argc] = (char *)NULL; - } - - Tcl_ResetResult(ptr->ip); - - /* Invoke the C procedure */ -#if TCL_MAJOR_VERSION >= 8 - if (info.isNativeObjectProc) { - int dummy; - ptr->return_value = (*info.objProc)(info.objClientData, - ptr->ip, argc, ov); - - /* get the string value from the result object */ - resultPtr = Tcl_GetObjResult(ptr->ip); - Tcl_SetResult(ptr->ip, Tcl_GetStringFromObj(resultPtr, &dummy), - TCL_VOLATILE); - - for (i=0; ireturn_value = (*info.proc)(info.clientData, - ptr->ip, argc, av); - } - - if (ptr->return_value == TCL_ERROR) { - rb_raise(rb_eRuntimeError, "%s", ptr->ip->result); - } - - /* pass back the result (as string) */ - return rb_str_new2(ptr->ip->result); -} - -static VALUE -ip_invoke(argc, argv, obj) - int argc; - VALUE *argv; - VALUE obj; -{ - struct invoke_queue *tmp, *p; - VALUE result = rb_thread_current(); - - if (result == main_thread) { - return ip_invoke_real(argc, argv, obj); - } - tmp = ALLOC(struct invoke_queue); - tmp->obj = obj; - tmp->argc = argc; - tmp->argv = ALLOC_N(VALUE, argc); - MEMCPY(tmp->argv, argv, VALUE, argc); - tmp->thread = result; - tmp->done = 0; - - tmp->next = iqueue; - iqueue = tmp; - - rb_thread_stop(); - result = tmp->result; - if (iqueue == tmp) { - iqueue = tmp->next; - free(tmp->argv); - free(tmp); - return result; - } - - p = iqueue; - while (p->next) { - if (p->next == tmp) { - p->next = tmp->next; - free(tmp->argv); - free(tmp); - break; - } - p = p->next; - } - return result; -} - -/* get return code from Tcl_Eval() */ -static VALUE -ip_retval(self) - VALUE self; -{ - struct tcltkip *ptr; /* tcltkip data struct */ - - /* get the data strcut */ - Data_Get_Struct(self, struct tcltkip, ptr); - - return (INT2FIX(ptr->return_value)); -} - -#ifdef __MACOS__ -static void -_macinit() -{ - tcl_macQdPtr = &qd; /* setup QuickDraw globals */ - Tcl_MacSetEventProc(TkMacConvertEvent); /* setup event handler */ -} -#endif - -/*---- initialization ----*/ -void -Init_tcltklib() -{ - VALUE lib = rb_define_module("TclTkLib"); - VALUE ip = rb_define_class("TclTkIp", rb_cObject); - -#if defined USE_TCL_STUBS && defined USE_TK_STUBS - extern int ruby_tcltk_stubs(); - int ret = ruby_tcltk_stubs(); - if (ret) - rb_raise(rb_eLoadError, "tcltklib: tcltk_stubs init error(%d)", ret); -#endif - - eTkCallbackBreak = rb_define_class("TkCallbackBreak", rb_eStandardError); - eTkCallbackContinue = rb_define_class("TkCallbackContinue",rb_eStandardError); - - rb_define_module_function(lib, "mainloop", lib_mainloop, 0); - - rb_define_singleton_method(ip, "new", ip_new, 0); - rb_define_method(ip, "_eval", ip_eval, 1); - rb_define_method(ip, "_toUTF8",ip_toUTF8,2); - rb_define_method(ip, "_fromUTF8",ip_fromUTF8,2); - rb_define_method(ip, "_invoke", ip_invoke, -1); - rb_define_method(ip, "_return_value", ip_retval, 0); - rb_define_method(ip, "mainloop", lib_mainloop, 0); - rb_define_method(ip, "restart", lib_restart, 0); - - main_thread = rb_thread_current(); -#ifdef __MACOS__ - _macinit(); -#endif - - /*---- initialize tcl/tk libraries ----*/ - /* from Tk_Main() */ - DUMP1("Tcl_FindExecutable"); - Tcl_FindExecutable(RSTRING(rb_argv0)->ptr); -} - -/* eof */ diff --git a/ext/tk/.cvsignore b/ext/tk/.cvsignore deleted file mode 100644 index fc802ff1c2..0000000000 --- a/ext/tk/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -mkmf.log diff --git a/ext/tk/MANIFEST b/ext/tk/MANIFEST deleted file mode 100644 index 9689186bf0..0000000000 --- a/ext/tk/MANIFEST +++ /dev/null @@ -1,25 +0,0 @@ -MANIFEST -extconf.rb -depend -tkutil.c -lib/tk.rb -lib/tkafter.rb -lib/tkbgerror.rb -lib/tkcanvas.rb -lib/tkclass.rb -lib/tkdialog.rb -lib/tkentry.rb -lib/tkfont.rb -lib/tkmenubar.rb -lib/tkmngfocus.rb -lib/tkpalette.rb -lib/tkscrollbox.rb -lib/tktext.rb -lib/tkvirtevent.rb -sample/tkbiff.rb -sample/tkbrowse.rb -sample/tkdialog.rb -sample/tkfrom.rb -sample/tkhello.rb -sample/tkline.rb -sample/tktimer.rb diff --git a/ext/tk/depend b/ext/tk/depend deleted file mode 100644 index fd63e230f0..0000000000 --- a/ext/tk/depend +++ /dev/null @@ -1 +0,0 @@ -tkutil.o: tkutil.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h diff --git a/ext/tk/extconf.rb b/ext/tk/extconf.rb deleted file mode 100644 index f769b06e30..0000000000 --- a/ext/tk/extconf.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'mkmf' -create_makefile("tkutil") diff --git a/ext/tk/lib/README b/ext/tk/lib/README deleted file mode 100644 index 87b59f4972..0000000000 --- a/ext/tk/lib/README +++ /dev/null @@ -1,15 +0,0 @@ -README this file -tk.rb Tk interface -tkafter.rb handles Tcl after -tkbgerror.rb Tk error module -tkcanvas.rb Tk canvas interface -tkclass.rb provides generic names for Tk classes -tkdialog.rb Tk dialog class -tkentry.rb Tk entry class -tkfont.rb Tk font support -tkmenubar.rb TK menubar utility -tkmngfocus.rb focus manager -tkpalette.rb pallete support -tkscrollbox.rb scroll box, also example of compound widget -tktext.rb text classes -tkvirtevent.rb virtual event support diff --git a/ext/tk/lib/tk.rb b/ext/tk/lib/tk.rb deleted file mode 100644 index bac2ae35f9..0000000000 --- a/ext/tk/lib/tk.rb +++ /dev/null @@ -1,3592 +0,0 @@ -# -# tk.rb - Tk interface module using tcltklib -# $Date$ -# by Yukihiro Matsumoto - -# use Shigehiro's tcltklib -require "tcltklib" -require "tkutil" - -module TkComm - WidgetClassNames = {} - - None = Object.new - def None.to_s - 'None' - end - - Tk_CMDTBL = {} - Tk_WINDOWS = {} - - def error_at - frames = caller() - frames.delete_if do |c| - c =~ %r!/tk(|core|thcore|canvas|text|entry|scrollbox)\.rb:\d+! - end - frames - end - private :error_at - - def _genobj_for_tkwidget(path) - return TkRoot.new if path == '.' - - begin - tk_class = TkCore::INTERP._invoke('winfo', 'class', path) - rescue - return path - end - - ruby_class = WidgetClassNames[tk_class] - gen_class_name = ruby_class.name + 'GeneratedOnTk' - unless Object.const_defined? gen_class_name - eval "class #{gen_class_name}<#{ruby_class.name} - def initialize(path) - @path=path - Tk_WINDOWS[@path] = self - end - end" - end - eval "#{gen_class_name}.new('#{path}')" - end - - def tk_tcl2ruby(val) - if val =~ /^rb_out (c\d+)/ - return Tk_CMDTBL[$1] - end - if val.include? ?\s - return val.split.collect{|v| tk_tcl2ruby(v)} - end - case val - when /^@font/ - TkFont.get_obj(val) - when /^-?\d+$/ - val.to_i - when /^\./ - Tk_WINDOWS[val] ? Tk_WINDOWS[val] : _genobj_for_tkwidget(val) - when / / - val.split.collect{|elt| - tk_tcl2ruby(elt) - } - when /^-?\d+\.\d*$/ - val.to_f - else - val - end - end - - def tk_split_list(str) - return [] if str == "" - idx = str.index('{') - while idx and idx > 0 and str[idx-1] == ?\\ - idx = str.index('{', idx+1) - end - return tk_tcl2ruby(str) unless idx - - list = tk_tcl2ruby(str[0,idx]) - list = [] if list == "" - str = str[idx+1..-1] - i = -1 - brace = 1 - str.each_byte {|c| - i += 1 - brace += 1 if c == ?{ - brace -= 1 if c == ?} - break if brace == 0 - } - if str[0, i] == ' ' - list.push ' ' - else - list.push tk_split_list(str[0, i]) - end - list += tk_split_list(str[i+1..-1]) - list - end - - def tk_split_simplelist(str) - return [] if str == "" - idx = str.index('{') - while idx and idx > 0 and str[idx-1] == ?\\ - idx = str.index('{', idx+1) - end - return str.split unless idx - - list = str[0,idx].split - str = str[idx+1..-1] - i = -1 - brace = 1 - str.each_byte {|c| - i += 1 - brace += 1 if c == ?{ - brace -= 1 if c == ?} - break if brace == 0 - } - if i == 0 - list.push '' - elsif str[0, i] == ' ' - list.push ' ' - else - list.push str[0..i-1] - end - list += tk_split_simplelist(str[i+1..-1]) - list - end - private :tk_tcl2ruby, :tk_split_list, :tk_split_simplelist - - def hash_kv(keys) - conf = [] - if keys and keys != None - for k, v in keys - conf.push("-#{k}") - conf.push(v) - end - end - conf - end - private :hash_kv - - def array2tk_list(ary) - ary.collect{|e| - if e.kind_of? Array - "{#{array2tk_list(e)}}" - elsif e.kind_of? Hash - "{#{e.to_a.collect{|ee| array2tk_list(ee)}.join(' ')}}" - else - s = _get_eval_string(e) - (s.index(/\s/))? "{#{s}}": s - end - }.join(" ") - end - private :array2tk_list - - def bool(val) - case val - when "1", 1, 'yes', 'true' - TRUE - else - FALSE - end - end - def number(val) - case val - when /^-?\d+$/ - val.to_i - when /^-?\d+\.\d*$/ - val.to_f - else - val - end - end - def string(val) - if val == "{}" - '' - elsif val[0] == ?{ - val[1..-2] - else - val - end - end - def list(val) - tk_split_list(val).to_a - end - def window(val) - Tk_WINDOWS[val] - end - def procedure(val) - if val =~ /^rb_out (c\d+)/ - Tk_CMDTBL[$1] - else - nil - end - end - private :bool, :number, :string, :list, :window, :procedure - - def _get_eval_string(str) - return nil if str == None - if str.kind_of?(String) - # do nothing - elsif str.kind_of?(Hash) - str = hash_kv(str).join(" ") - elsif str.kind_of?(Array) - str = array2tk_list(str) - elsif str.kind_of?(Proc) - str = install_cmd(str) - elsif str == nil - str = "" - elsif str == false - str = "0" - elsif str == true - str = "1" - elsif (str.respond_to?(:to_eval)) - str = str.to_eval() - else - str = str.to_s() - end - return str - end - private :_get_eval_string - - def ruby2tcl(v) - if v.kind_of?(Hash) - v = hash_kv(v) - v.flatten! - v.collect{|e|ruby2tcl(e)} - else - _get_eval_string(v) - end - end - private :ruby2tcl - - Tk_IDs = [0, 0] # [0]-cmdid, [1]-winid - def _curr_cmd_id - id = format("c%.4d", Tk_IDs[0]) - end - def _next_cmd_id - id = _curr_cmd_id - Tk_IDs[0] += 1 - id - end - def install_cmd(cmd) - return '' if cmd == '' - id = _next_cmd_id - Tk_CMDTBL[id] = cmd - @cmdtbl = [] unless @cmdtbl - @cmdtbl.push id - return format("rb_out %s", id); - end - def uninstall_cmd(id) - id = $1 if /rb_out (c\d+)/ =~ id - Tk_CMDTBL[id] = nil - end - private :install_cmd, :uninstall_cmd - - def install_win(ppath) - id = format("w%.4d", Tk_IDs[1]) - Tk_IDs[1] += 1 - if !ppath or ppath == "." - @path = format(".%s", id); - else - @path = format("%s.%s", ppath, id) - end - Tk_WINDOWS[@path] = self - end - - def uninstall_win() - Tk_WINDOWS[@path] = nil - end - - class Event - def initialize(seq,a,b,c,d,f,h,k,m,o,p,s,t,w,x,y, - aa,bb,dd,ee,kk,nn,rr,ss,tt,ww,xx,yy) - @serial = seq - @above = a - @num = b - @count = c - @detail = d - @focus = (f == 1) - @height = h - @keycode = k - @mode = m - @override = (o == 1) - @place = p - @state = s - @time = t - @width = w - @x = x - @y = y - @char = aa - @borderwidth = bb - @wheel_delta = dd - @send_event = (ee == 1) - @keysym = kk - @keysym_num = nn - @rootwin_id = rr - @subwindow = ss - @type = tt - @widget = ww - @x_root = xx - @y_root = yy - end - attr :serial - attr :above - attr :num - attr :count - attr :detail - attr :focus - attr :height - attr :keycode - attr :mode - attr :override - attr :place - attr :state - attr :time - attr :width - attr :x - attr :y - attr :char - attr :borderwidth - attr :wheel_delta - attr :send_event - attr :keysym - attr :keysym_num - attr :rootwin_id - attr :subwindow - attr :type - attr :widget - attr :x_root - attr :y_root - end - - def install_bind(cmd, args=nil) - if args - id = install_cmd(proc{|*arg| - TkUtil.eval_cmd cmd, *arg - }) - id + " " + args - else - id = install_cmd(proc{|arg| - TkUtil.eval_cmd cmd, Event.new(*arg) - }) - id + ' %# %a %b %c %d %f %h %k %m %o %p %s %t %w %x %y' + - ' %A %B %D %E %K %N %R %S %T %W %X %Y' - end - end - - def tk_event_sequence(context) - if context.kind_of? TkVirtualEvent - context = context.path - end - if context.kind_of? Array - context = context.collect{|ev| - if ev.kind_of? TkVirtualEvent - ev.path - else - ev - end - }.join("><") - end - if /,/ =~ context - context = context.split(/\s*,\s*/).join("><") - else - context - end - end - - def _bind_core(mode, what, context, cmd, args=nil) - id = install_bind(cmd, args) if cmd - begin - tk_call(*(what + ["<#{tk_event_sequence(context)}>", mode + id])) - rescue - uninstall_cmd(id) if cmd - fail - end - end - - def _bind(what, context, cmd, args=nil) - _bind_core('', what, context, cmd, args) - end - - def _bind_append(what, context, cmd, args=nil) - _bind_core('+', what, context, cmd, args) - end - - def _bind_remove(what, context) - tk_call(*(what + ["<#{tk_event_sequence(context)}>", ''])) - end - - def _bindinfo(what, context=nil) - if context - tk_call(*what+["<#{tk_event_sequence(context)}>"]).collect {|cmdline| - if cmdline =~ /^rb_out (c\d+)\s+(.*)$/ - [Tk_CMDTBL[$1], $2] - else - cmdline - end - } - else - tk_split_simplelist(tk_call(*what)).collect!{|seq| - l = seq.scan(/<*[^<>]+>*/).collect!{|subseq| - case (subseq) - when /^<<[^<>]+>>$/ - TkVirtualEvent.getobj(subseq[1..-2]) - when /^<[^<>]+>$/ - subseq[1..-2] - else - subseq.split('') - end - }.flatten - (l.size == 1) ? l[0] : l - } - end - end - private :install_bind, :tk_event_sequence, - :_bind_core, :_bind, :_bind_append, :_bind_remove, :_bindinfo - - def bind(tagOrClass, context, cmd=Proc.new, args=nil) - _bind(["bind", tagOrClass], context, cmd, args) - end - - def bind_append(tagOrClass, context, cmd=Proc.new, args=nil) - _bind_append(["bind", tagOrClass], context, cmd, args) - end - - def bind_remove(tagOrClass, context) - _bind_remove(['bind', tagOrClass], context) - end - - def bindinfo(tagOrClass, context=nil) - _bindinfo(['bind', tagOrClass], context) - end - - def bind_all(context, cmd=Proc.new, args=nil) - _bind(['bind', 'all'], context, cmd, args) - end - - def bind_append_all(context, cmd=Proc.new, args=nil) - _bind_append(['bind', 'all'], context, cmd, args) - end - - def bindinfo_all(context=nil) - _bindinfo(['bind', 'all'], context) - end - - def pack(*args) - TkPack.configure(*args) - end - - def grid(*args) - TkGrid.configure(*args) - end - - def update(idle=nil) - if idle - tk_call 'update', 'idletasks' - else - tk_call 'update' - end - end - -end - -module TkCore - include TkComm - extend TkComm - - INTERP = TclTkIp.new - - INTERP._invoke("proc", "rb_out", "args", <<-'EOL') - regsub -all {!} $args {\\!} args - regsub -all "{" $args "\\{" args - if {[set st [catch {ruby [format "TkCore.callback %%Q!%s!" $args]} ret]] != 0} { - return -code $st $ret - } { - return $ret - } - EOL - - def callback_break - fail TkCallbackBreak, "Tk callback returns 'break' status" - end - - def callback_continue - fail TkCallbackContinue, "Tk callback returns 'continue' status" - end - - def after(ms, cmd=Proc.new) - myid = _curr_cmd_id - cmdid = install_cmd(cmd) - tk_call("after",ms,cmdid) -# return -# if false #defined? Thread -# Thread.start do -# ms = Float(ms)/1000 -# ms = 10 if ms == 0 -# sleep ms/1000 -# cmd.call -# end -# else -# cmdid = install_cmd(cmd) -# tk_call("after",ms,cmdid) -# end - end - - def after_idle(cmd=Proc.new) - myid = _curr_cmd_id - cmdid = install_cmd(cmd) - tk_call('after','idle',cmdid) - end - - def clock_clicks(ms=nil) - if ms - tk_call('clock','clicks','-milliseconds').to_i - else - tk_call('clock','clicks').to_i - end - end - - def clock_format(clk, form=nil) - if form - tk_call('clock','format',clk,'-format',form).to_i - else - tk_call('clock','format',clk).to_i - end - end - - def clock_formatGMT(clk, form=nil) - if form - tk_call('clock','format',clk,'-format',form,'-gmt','1').to_i - else - tk_call('clock','format',clk,'-gmt','1').to_i - end - end - - def clock_scan(str, base=nil) - if base - tk_call('clock','scan',str,'-base',base).to_i - else - tk_call('clock','scan',str).to_i - end - end - - def clock_scanGMT(str, base=nil) - if base - tk_call('clock','scan',str,'-base',base,'-gmt','1').to_i - else - tk_call('clock','scan',str,'-gmt','1').to_i - end - end - - def clock_seconds - tk_call('clock','seconds').to_i - end - - def TkCore.callback(arg) - arg = Array(tk_split_list(arg)) - _get_eval_string(TkUtil.eval_cmd(Tk_CMDTBL[arg.shift], *arg)) - end - - def scaling(scale=nil) - if scale - tk_call('tk', 'scaling', scale) - else - Float(number(tk_call('tk', 'scaling'))) - end - end - def scaling_displayof(win, scale=nil) - if scale - tk_call('tk', 'scaling', '-displayof', win, scale) - else - Float(number(tk_call('tk', '-displayof', win, 'scaling'))) - end - end - - def appname(name=None) - tk_call('tk', 'appname', name) - end - - def appsend(interp, async, *args) - if async - tk_call('send', '-async', '--', interp, *args) - else - tk_call('send', '--', interp, *args) - end - end - - def rb_appsend(interp, async, *args) - args = args.collect!{|c| _get_eval_string(c).gsub(/[][$"]/, '\\\\\&')} - args.push(').to_s"') - appsend(interp, async, 'ruby "(', *args) - end - - def appsend_displayof(interp, win, async, *args) - win = '.' if win == nil - if async - tk_call('send', '-async', '-displayof', win, '--', interp, *args) - else - tk_call('send', '-displayor', win, '--', interp, *args) - end - end - - def rb_appsend_displayof(interp, win, async, *args) - args = args.collect!{|c| _get_eval_string(c).gsub(/[][$"]/, '\\\\\&')} - args.push(').to_s"') - appsend_displayof(interp, win, async, 'ruby "(', *args) - end - - def info(*args) - tk_call('info', *args) - end - - def mainloop - TclTkLib.mainloop - end - - def restart - TkCore::INTERP.restart - TkComm::Tk_WINDOWS.clear - nil - end - - def event_generate(window, context, keys=nil) - window = window.path if window.kind_of? TkObject - if keys - tk_call('event', 'generate', window, - "<#{tk_event_sequence(context)}>", *hash_kv(keys)) - else - tk_call('event', 'generate', window, "<#{tk_event_sequence(context)}>") - end - end - - def messageBox(keys) - tk_call 'tk_messageBox', *hash_kv(keys) - end - - def getOpenFile(keys = nil) - tk_call 'tk_getOpenFile', *hash_kv(keys) - end - - def getSaveFile(keys = nil) - tk_call 'tk_getSaveFile', *hash_kv(keys) - end - - def chooseColor(keys = nil) - tk_call 'tk_chooseColor', *hash_kv(keys) - end - - def chooseDirectory(keys = nil) - tk_call 'tk_chooseDirectory', *hash_kv(keys) - end - - def tk_call(*args) - puts args.inspect if $DEBUG - args.collect! {|x|ruby2tcl(x)} - args.compact! - args.flatten! - print "=> ", args.join(" ").inspect, "\n" if $DEBUG - begin - res = INTERP._invoke(*args) - rescue NameError - err = $! - begin - args.unshift "unknown" - res = INTERP._invoke(*args) - rescue - fail unless /^invalid command/ =~ $! - fail err - end - end - if INTERP._return_value() != 0 - fail RuntimeError, res, error_at - end - print "==> ", res.inspect, "\n" if $DEBUG - return res - end -end - -module TkPackage - include TkCore - extend TkPackage - - def add_path(path) - Tk::AUTO_PATH.value = Tk::AUTO_PATH.to_a << path - end - - def forget(package) - tk_call('package', 'forget', package) - nil - end - - def names - tk_split_simplelist(tk_call('package', 'names')) - end - - def provide(package, version=nil) - if version - tk_call('package', 'provide', package, version) - nil - else - tk_call('package', 'provide', package) - end - end - - def present(package, version=None) - tk_call('package', 'present', package, version) - end - - def present_exact(package, version) - tk_call('package', 'present', '-exact', package, version) - end - - def require(package, version=None) - tk_call('package', 'require', package, version) - end - - def require_exact(package, version) - tk_call('package', 'require', '-exact', package, version) - end - - def versions(package) - tk_split_simplelist(tk_call('package', 'versions', package)) - end - - def vcompare(version1, version2) - Integer(tk_call('package', 'vcompare', version1, version2)) - end - - def vsatisfies(version1, version2) - bool(tk_call('package', 'vsatisfies', version1, version2)) - end -end - -module Tk - include TkCore - extend Tk - - TCL_VERSION = INTERP._invoke("info", "tclversion") - TK_VERSION = INTERP._invoke("set", "tk_version") - - TCL_PATCHLEVEL = INTERP._invoke("info", "patchlevel") - TK_PATCHLEVEL = INTERP._invoke("set", "tk_patchLevel") - - TCL_LIBRARY = INTERP._invoke("set", "tcl_library") - TK_LIBRARY = INTERP._invoke("set", "tk_library") - LIBRARY = INTERP._invoke("info", "library") - - PLATFORM = Hash[*tk_split_simplelist(INTERP._eval('array get tcl_platform'))] - - JAPANIZED_TK = (INTERP._invoke("info", "commands", "kanji") != "") - - def root - TkRoot.new - end - - def bell - tk_call 'bell' - end - - def Tk.focus(display=nil) - if display == nil - r = tk_call('focus') - else - r = tk_call('focus', '-displayof', display) - end - tk_tcl2ruby(r) - end - - def Tk.focus_lastfor(win) - tk_tcl2ruby(tk_call('focus', '-lastfor', win)) - end - - def Tk.strictMotif(bool=None) - bool(tk_call('set', 'tk_strictMotif', bool)) - end - - def Tk.show_kinsoku(mode='both') - begin - if /^8\.*/ === TK_VERSION && JAPANIZED_TK - tk_split_simplelist(tk_call('kinsoku', 'show', mode)) - end - rescue - end - end - def Tk.add_kinsoku(chars, mode='both') - begin - if /^8\.*/ === TK_VERSION && JAPANIZED_TK - tk_split_simplelist(tk_call('kinsoku', 'add', mode, - *(chars.split('')))) - else - [] - end - rescue - [] - end - end - def Tk.delete_kinsoku(chars, mode='both') - begin - if /^8\.*/ === TK_VERSION && JAPANIZED_TK - tk_split_simplelist(tk_call('kinsoku', 'delete', mode, - *(chars.split('')))) - end - rescue - end - end - - def Tk.toUTF8(str,encoding) - INTERP._toUTF8(str,encoding) - end - - def Tk.fromUTF8(str,encoding) - INTERP._fromUTF8(str,encoding) - end - - module Scrollable - def xscrollcommand(cmd=Proc.new) - configure_cmd 'xscrollcommand', cmd - end - def yscrollcommand(cmd=Proc.new) - configure_cmd 'yscrollcommand', cmd - end - def xview(*index) - v = tk_send('xview', *index) - list(v) if index.size == 0 - end - def yview(*index) - v = tk_send('yview', *index) - list(v) if index.size == 0 - end - def xscrollbar(bar=nil) - if bar - @xscrollbar = bar - @xscrollbar.orient 'horizontal' - self.xscrollcommand {|arg| @xscrollbar.set(*arg)} - @xscrollbar.command {|arg| self.xview(*arg)} - end - @xscrollbar - end - def yscrollbar(bar=nil) - if bar - @yscrollbar = bar - @yscrollbar.orient 'vertical' - self.yscrollcommand {|arg| @yscrollbar.set(*arg)} - @yscrollbar.command {|arg| self.yview(*arg)} - end - @yscrollbar - end - end - - module Wm - include TkComm - def aspect(*args) - w = tk_call('wm', 'aspect', path, *args) - list(w) if args.length == 0 - end - def client(name=None) - tk_call 'wm', 'client', path, name - end - def colormapwindows(*args) - list(tk_call('wm', 'colormapwindows', path, *args)) - end - def wm_command(value=None) - string(tk_call('wm', 'command', path, value)) - end - def deiconify - tk_call 'wm', 'deiconify', path - end - def focusmodel(*args) - tk_call 'wm', 'focusmodel', path, *args - end - def frame - tk_call('wm', 'frame', path) - end - def geometry(*args) - tk_call('wm', 'geometry', path, *args) - end - def grid(*args) - w = tk_call('wm', 'grid', path, *args) - list(w) if args.size == 0 - end - def group(*args) - w = tk_call 'wm', 'group', path, *args - window(w) if args.size == 0 - end - def iconbitmap(*args) - tk_call 'wm', 'iconbitmap', path, *args - end - def iconify - tk_call 'wm', 'iconify', path - end - def iconmask(*args) - tk_call 'wm', 'iconmask', path, *args - end - def iconname(*args) - tk_call 'wm', 'iconname', path, *args - end - def iconposition(*args) - w = tk_call('wm', 'iconposition', path, *args) - list(w) if args.size == 0 - end - def iconwindow(*args) - w = tk_call('wm', 'iconwindow', path, *args) - window(w) if args.size == 0 - end - def maxsize(*args) - w = tk_call('wm', 'maxsize', path, *args) - list(w) if args.size == 0 - end - def minsize(*args) - w = tk_call('wm', 'minsize', path, *args) - list(w) if args.size == 0 - end - def overrideredirect(bool=None) - if bool == None - bool(tk_call('wm', 'overrideredirect', path)) - else - tk_call 'wm', 'overrideredirect', path, bool - end - end - def positionfrom(*args) - tk_call 'wm', 'positionfrom', path, *args - end - def protocol(name=nil, cmd=nil) - if cmd - tk_call('wm', 'protocol', path, name, cmd) - elsif name - result = tk_call('wm', 'protocol', path, name) - (result == "")? nil : tk_tcl2ruby(result) - else - tk_split_simplelist(tk_call('wm', 'protocol', path)) - end - end - def resizable(*args) - w = tk_call('wm', 'resizable', path, *args) - if args.length == 0 - list(w).collect{|e| bool(e)} - end - end - def sizefrom(*args) - tk_call('wm', 'sizefrom', path, *args) - end - def state(state=None) - tk_call 'wm', 'state', path, state - end - def title(*args) - tk_call 'wm', 'title', path, *args - end - def transient(*args) - window(tk_call 'wm', 'transient', path, *args) - end - def withdraw - tk_call 'wm', 'withdraw', path - end - end -end - -########################################### -# convert kanji string to/from utf-8 -########################################### -if /^8\.[1-9]/ =~ Tk::TCL_VERSION && !Tk::JAPANIZED_TK - class TclTkIp - # from tkencoding.rb by ttate@jaist.ac.jp - alias __eval _eval - alias __invoke _invoke - private :__eval - private :__invoke - - attr_accessor :encoding - - def _eval(cmd) - if @encoding - _fromUTF8(__eval(_toUTF8(cmd, @encoding)), @encoding) - else - __eval(cmd) - end - end - - def _invoke(*cmds) - if @encoding - cmds = cmds.collect{|cmd| _toUTF8(cmd, @encoding)} - _fromUTF8(__invoke(*cmds), @encoding) - else - __invoke(*cmds) - end - end - end - - module Tk - def encoding=(name) - INTERP.encoding = name - end - - def encoding - INTERP.encoding - end - - def encoding_names - tk_split_simplelist(tk_call('encoding', 'names')) - end - - def encoding_system - tk_call('encoding', 'system') - end - - def encoding_system=(enc) - tk_call('encoding', 'system', enc) - end - end - - # estimate encoding - case $KCODE - when /^e/i # EUC - Tk.encoding = 'euc-jp' - when /^s/i # SJIS - Tk.encoding = 'shiftjis' - when /^u/i # UTF8 - Tk.encoding = 'utf-8' - else # NONE - begin - Tk.encoding = Tk.encoding_system - rescue StandardError, NameError - Tk.encoding = 'utf-8' - end - end - -else - # dummy methods - module Tk - def encoding=(name) - nil - end - def encoding - nil - end - def encoding_names - nil - end - def encoding_system - nil - end - def encoding_system=(enc) - nil - end - end -end - -module TkBindCore - def bind(context, cmd=Proc.new, args=nil) - Tk.bind(to_eval, context, cmd, args) - end - - def bind_append(context, cmd=Proc.new, args=nil) - Tk.bind_append(to_eval, context, cmd, args) - end - - def bind_remove(context) - Tk.bind_remove(to_eval, context) - end - - def bindinfo(context=nil) - Tk.bindinfo(to_eval, context) - end -end - -class TkBindTag - include TkBindCore - - BTagID_TBL = {} - Tk_BINDTAG_ID = ["btag00000"] - - def TkBindTag.id2obj(id) - BTagID_TBL[id]? BTagID_TBL[id]: id - end - - ALL = self.new - ALL.instance_eval { - @id = 'all' - BTagID_TBL[@id] = self - } - - def initialize(*args) - @id = Tk_BINDTAG_ID[0] - Tk_BINDTAG_ID[0] = Tk_BINDTAG_ID[0].succ - BTagID_TBL[@id] = self - bind(*args) if args != [] - end - - def to_eval - @id - end - - def inspect - format "#", @id - end -end - -class TkBindTagAll", @id - end - - def ==(other) - case other - when TkVariable - self.equal(self) - when String - self.to_s == other - when Integer - self.to_i == other - when Float - self.to_f == other - when Array - self.to_a == other - else - false - end - end - - def to_a - list(value) - end - - def to_eval - @id - end - - def unset(elem=nil) - if elem - INTERP._eval(format('global %s; unset %s(%s)', - @id, @id, tk_tcl2ruby(elem))) - else - INTERP._eval(format('global %s; unset %s', @id, @id)) - end - end - alias remove unset - - def trace_callback(elem, op) - if @trace_var.kind_of? Array - @trace_var.each{|m,e| e.call(self,elem,op) if m.index(op)} - end - if elem.kind_of? String - if @trace_elem[elem].kind_of? Array - @trace_elem[elem].each{|m,e| e.call(self,elem,op) if m.index(op)} - end - end - end - - def trace(opts, cmd) - @trace_var = [] if @trace_var == nil - opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('') - @trace_var.unshift([opts,cmd]) - if @trace_opts == nil - TkVar_CB_TBL[@id] = self - @trace_opts = opts - Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var') - else - newopts = @trace_opts.dup - opts.each_byte{|c| newopts += c.chr unless newopts.index(c)} - if newopts != @trace_opts - Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var') - @trace_opts.replace(newopts) - Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var') - end - end - end - - def trace_element(elem, opts, cmd) - @trace_elem = {} if @trace_elem == nil - @trace_elem[elem] = [] if @trace_elem[elem] == nil - opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('') - @trace_elem[elem].unshift([opts,cmd]) - if @trace_opts == nil - TkVar_CB_TBL[@id] = self - @trace_opts = opts - Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var') - else - newopts = @trace_opts.dup - opts.each_byte{|c| newopts += c.chr unless newopts.index(c)} - if newopts != @trace_opts - Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var') - @trace_opts.replace(newopts) - Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var') - end - end - end - - def trace_vinfo - return [] unless @trace_var - @trace_var.dup - end - def trace_vinfo_for_element(elem) - return [] unless @trace_elem - return [] unless @trace_elem[elem] - @trace_elem[elem].dup - end - - def trace_vdelete(opts,cmd) - return unless @trace_var.kind_of? Array - opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('') - idx = -1 - newopts = '' - @trace_var.each_with_index{|e,i| - if idx < 0 && e[0] == opts && e[1] == cmd - idx = i - next - end - e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)} - } - if idx >= 0 - @trace_var.delete_at(idx) - else - return - end - - @trace_elem.each{|elem| - @trace_elem[elem].each{|e| - e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)} - } - } - - newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('') - if newopts != @trace_opts - Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var') - @trace_opts.replace(newopts) - if @trace_opts != '' - Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var') - end - end - end - - def trace_vdelete_for_element(elem,opts,cmd) - return unless @trace_elem.kind_of? Hash - return unless @trace_elem[elem].kind_of? Array - opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('') - idx = -1 - @trace_elem[elem].each_with_index{|e,i| - if idx < 0 && e[0] == opts && e[1] == cmd - idx = i - next - end - } - if idx >= 0 - @trace_elem[elem].delete_at(idx) - else - return - end - - newopts = '' - @trace_var.each{|e| - e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)} - } - @trace_elem.each{|elem| - @trace_elem[elem].each{|e| - e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)} - } - } - - newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('') - if newopts != @trace_opts - Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var') - @trace_opts.replace(newopts) - if @trace_opts != '' - Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var') - end - end - end -end - -class TkVarAccess= Tk8.4a2 ? - if slot - conf = tk_split_list(tk_call('place', 'configure', - win.epath, "-#{slot}") ) - conf[0] = conf[0][1..-1] - conf - else - tk_split_simplelist(tk_call('place', 'configure', - win.epath)).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - conf - } - end - end - - def forget(win) - tk_call 'place', 'forget', win - end - - def info(win) - ilist = list(tk_call('place', 'info', win.epath)) - info = {} - while key = ilist.shift - info[key[1..-1]] = ilist.shift - end - return info - end - - def slaves(master) - list(tk_call('place', 'slaves', master.epath)) - end - - module_function :configure, :configinfo, :forget, :info, :slaves -end - -module TkOption - include Tk - extend Tk - def add pat, value, pri=None - tk_call 'option', 'add', pat, value, pri - end - def clear - tk_call 'option', 'clear' - end - def get win, name, klass - tk_call 'option', 'get', win ,name, klass - end - def readfile file, pri=None - tk_call 'option', 'readfile', file, pri - end - module_function :add, :clear, :get, :readfile -end - -module TkTreatFont - def font_configinfo - ret = TkFont.used_on(self.path) - if ret == nil - ret = TkFont.init_widget_font(self.path, self.path, 'configure') - end - ret - end - alias fontobj font_configinfo - - def font_configure(slot) - if (fnt = slot.delete('font')) - if fnt.kind_of? TkFont - return fnt.call_font_configure(self.path, self.path,'configure',slot) - else - latinfont_configure(fnt) if fnt - end - end - if (ltn = slot.delete('latinfont')) - latinfont_configure(ltn) if ltn - end - if (ltn = slot.delete('asciifont')) - latinfont_configure(ltn) if ltn - end - if (knj = slot.delete('kanjifont')) - kanjifont_configure(knj) if knj - end - - tk_call(self.path, 'configure', *hash_kv(slot)) if slot != {} - self - end - - def latinfont_configure(ltn, keys=nil) - fobj = fontobj - if ltn.kind_of? TkFont - conf = {} - ltn.latin_configinfo.each{|key,val| conf[key] = val} - if keys - fobj.latin_configure(conf.update(keys)) - else - fobj.latin_configure(conf) - end - else - fobj.latin_replace(ltn) - end - end - alias asciifont_configure latinfont_configure - - def kanjifont_configure(knj, keys=nil) - fobj = fontobj - if knj.kind_of? TkFont - conf = {} - knj.kanji_configinfo.each{|key,val| conf[key] = val} - if keys - fobj.kanji_configure(conf.update(keys)) - else - fobj.kanji_configure(cond) - end - else - fobj.kanji_replace(knj) - end - end - - def font_copy(window, tag=nil) - if tag - window.tagfontobj(tag).configinfo.each{|key,value| - fontobj.configure(key,value) - } - fontobj.replace(window.tagfontobj(tag).latin_font, - window.tagfontobj(tag).kanji_font) - else - window.fontobj.configinfo.each{|key,value| - fontobj.configure(key,value) - } - fontobj.replace(window.fontobj.latin_font, window.fontobj.kanji_font) - end - end - - def latinfont_copy(window, tag=nil) - if tag - fontobj.latin_replace(window.tagfontobj(tag).latin_font) - else - fontobj.latin_replace(window.fontobj.latin_font) - end - end - alias asciifont_copy latinfont_copy - - def kanjifont_copy(window, tag=nil) - if tag - fontobj.kanji_replace(window.tagfontobj(tag).kanji_font) - else - fontobj.kanji_replace(window.fontobj.kanji_font) - end - end -end - -module TkTreatItemFont - def __conf_cmd(idx) - raise NotImplementError, "need to define `__conf_cmd'" - end - def __item_pathname(tagOrId) - raise NotImplementError, "need to define `__item_pathname'" - end - private :__conf_cmd, :__item_pathname - - def tagfont_configinfo(tagOrId) - pathname = __item_pathname(tagOrId) - ret = TkFont.used_on(pathname) - if ret == nil - ret = TkFont.init_widget_font(pathname, self.path, - __conf_cmd(0), __conf_cmd(1), tagOrId) - end - ret - end - alias tagfontobj tagfont_configinfo - - def tagfont_configure(tagOrId, slot) - pathname = __item_pathname(tagOrId) - if (fnt = slot.delete('font')) - if fnt.kind_of? TkFont - return fnt.call_font_configure(pathname, self.path, - __conf_cmd(0), __conf_cmd(1), - tagOrId, slot) - else - latintagfont_configure(tagOrId, fnt) if fnt - end - end - if (ltn = slot.delete('latinfont')) - latintagfont_configure(tagOrId, ltn) if ltn - end - if (ltn = slot.delete('asciifont')) - latintagfont_configure(tagOrId, ltn) if ltn - end - if (knj = slot.delete('kanjifont')) - kanjitagfont_configure(tagOrId, knj) if knj - end - - tk_call(self.path, __conf_cmd(0), __conf_cmd(1), - tagOrId, *hash_kv(slot)) if slot != {} - self - end - - def latintagfont_configure(tagOrId, ltn, keys=nil) - fobj = tagfontobj(tagOrId) - if ltn.kind_of? TkFont - conf = {} - ltn.latin_configinfo.each{|key,val| conf[key] = val if val != []} - if conf == {} - fobj.latin_replace(ltn) - fobj.latin_configure(keys) if keys - elsif keys - fobj.latin_configure(conf.update(keys)) - else - fobj.latin_configure(conf) - end - else - fobj.latin_replace(ltn) - end - end - alias asciitagfont_configure latintagfont_configure - - def kanjitagfont_configure(tagOrId, knj, keys=nil) - fobj = tagfontobj(tagOrId) - if knj.kind_of? TkFont - conf = {} - knj.kanji_configinfo.each{|key,val| conf[key] = val if val != []} - if conf == {} - fobj.kanji_replace(knj) - fobj.kanji_configure(keys) if keys - elsif keys - fobj.kanji_configure(conf.update(keys)) - else - fobj.kanji_configure(conf) - end - else - fobj.kanji_replace(knj) - end - end - - def tagfont_copy(tagOrId, window, wintag=nil) - if wintag - window.tagfontobj(wintag).configinfo.each{|key,value| - tagfontobj(tagOrId).configure(key,value) - } - tagfontobj(tagOrId).replace(window.tagfontobj(wintag).latin_font, - window.tagfontobj(wintag).kanji_font) - else - window.tagfont(wintag).configinfo.each{|key,value| - tagfontobj(tagOrId).configure(key,value) - } - tagfontobj(tagOrId).replace(window.fontobj.latin_font, - window.fontobj.kanji_font) - end - end - - def latintagfont_copy(tagOrId, window, wintag=nil) - if wintag - tagfontobj(tagOrId).latin_replace(window.tagfontobj(wintag).latin_font) - else - tagfontobj(tagOrId).latin_replace(window.fontobj.latin_font) - end - end - alias asciitagfont_copy latintagfont_copy - - def kanjitagfont_copy(tagOrId, window, wintag=nil) - if wintag - tagfontobj(tagOrId).kanji_replace(window.tagfontobj(wintag).kanji_font) - else - tagfontobj(tagOrId).kanji_replace(window.fontobj.kanji_font) - end - end -end - -class TkObjectvalue}) - end - else - tk_call path, 'configure', "-#{slot}", value - end - end - end - - def configure_cmd(slot, value) - configure slot, install_cmd(value) - end - - def configinfo(slot = nil) - if slot == 'font' || slot == 'kanjifont' - fontobj - else - if slot - case slot - when 'text', 'label', 'show', 'data', 'file' - conf = tk_split_simplelist(tk_send('configure', "-#{slot}") ) - else - conf = tk_split_list(tk_send('configure', "-#{slot}") ) - end - conf[0] = conf[0][1..-1] - conf - else - ret = tk_split_simplelist(tk_send('configure') ).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - case conf[0] - when 'text', 'label', 'show', 'data', 'file' - else - if conf[3] - if conf[3].index('{') - conf[3] = tk_split_list(conf[3]) - else - conf[3] = tk_tcl2ruby(conf[3]) - end - end - if conf[4] - if conf[4].index('{') - conf[4] = tk_split_list(conf[4]) - else - conf[4] = tk_tcl2ruby(conf[4]) - end - end - end - conf - } - fontconf = ret.assoc('font') - if fontconf - ret.delete_if{|item| item[0] == 'font' || item[0] == 'kanjifont'} - fontconf[4] = fontobj - ret.push(fontconf) - else - ret - end - end - end - end - - def event_generate(context, keys=nil) - if keys - tk_call('event', 'generate', path, - "<#{tk_event_sequence(context)}>", *hash_kv(keys)) - else - tk_call('event', 'generate', path, "<#{tk_event_sequence(context)}>") - end - end - - def tk_trace_variable(v) - unless v.kind_of?(TkVariable) - fail ArgumentError, format("requires TkVariable given %s", v.type) - end - v - end - private :tk_trace_variable - - def destroy - tk_call 'trace', 'vdelete', @tk_vn, 'w', @var_id if @var_id - end -end - -class TkWindow= Tk8.4a2 ? - if slot - conf = tk_split_list(tk_call('place', 'configure', epath, "-#{slot}") ) - conf[0] = conf[0][1..-1] - conf - else - tk_split_simplelist(tk_call('place', - 'configure', epath)).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - conf - } - end - end - - def place_info() - ilist = list(tk_call('place', 'info', epath)) - info = {} - while key = ilist.shift - info[key[1..-1]] = ilist.shift - end - return info - end - - def place_slaves() - list(tk_call('place', 'slaves', epath)) - end - - def focus(force=false) - if force - tk_call 'focus', '-force', path - else - tk_call 'focus', path - end - self - end - - def grab(*args) - if !args or args.length == 0 - tk_call 'grab', 'set', path - elsif args.length == 1 - case args[0] - when 'global' - return(tk_call 'grab', 'set', '-global', path) - when 'release' - return(tk_call 'grab', 'release', path) - else - val = tk_call('grab', args[0], path) - end - case args[0] - when 'current' - return window(val) - when 'status' - return val - end - else - fail ArgumentError, 'wrong # of args' - end - end - - def lower(below=None) - tk_call 'lower', epath, below - self - end - def raise(above=None) - tk_call 'raise', epath, above - self - end - - def command(cmd=Proc.new) - configure_cmd 'command', cmd - end - - def colormodel model=None - tk_call 'tk', 'colormodel', path, model - self - end - - def destroy - tk_call 'destroy', epath - if @cmdtbl - for id in @cmdtbl - uninstall_cmd id - end - end - uninstall_win - end - - def wait_visibility - tk_call 'tkwait', 'visibility', path - end - alias wait wait_visibility - - def wait_destroy - tk_call 'tkwait', 'window', epath - end - - def bindtags(taglist=nil) - if taglist - fail ArgumentError unless taglist.kind_of? Array - tk_call('bindtags', path, taglist) - else - list(tk_call('bindtags', path)).collect{|tag| - if tag.kind_of?(String) - if cls = WidgetClassNames[tag] - cls - elsif btag = TkBindTag.id2obj(tag) - btag - else - tag - end - else - tag - end - } - end - end -end - -class TkRootval}) - else - tk_call 'itemconfigure', index, "-#{key}", val - end - end - end - - def itemconfiginfo(index, key=nil) - if key - case key - when 'text', 'label', 'show' - conf = tk_split_simplelist(tk_send('itemconfigure',index,"-#{key}")) - else - conf = tk_split_list(tk_send('itemconfigure',index,"-#{key}")) - end - conf[0] = conf[0][1..-1] - conf - else - tk_split_simplelist(tk_send('itemconfigure', index)).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - case conf[0] - when 'text', 'label', 'show' - else - if conf[3] - if conf[3].index('{') - conf[3] = tk_split_list(conf[3]) - else - conf[3] = tk_tcl2ruby(conf[3]) - end - end - if conf[4] - if conf[4].index('{') - conf[4] = tk_split_list(conf[4]) - else - conf[4] = tk_tcl2ruby(conf[4]) - end - end - end - conf - } - end - end -end - -module TkTreatMenuEntryFont - include TkTreatItemFont - - ItemCMD = ['entryconfigure', TkComm::None] - def __conf_cmd(idx) - ItemCMD[idx] - end - - def __item_pathname(tagOrId) - self.path + ';' + tagOrId.to_s - end -end - -class TkMenuval}) - else - tk_call 'entryconfigure', index, "-#{key}", val - end - end - end - - def entryconfiginfo(index, key=nil) - if key - case key - when 'text', 'label', 'show' - conf = tk_split_simplelist(tk_send('entryconfigure',index,"-#{key}")) - else - conf = tk_split_list(tk_send('entryconfigure',index,"-#{key}")) - end - conf[0] = conf[0][1..-1] - conf - else - tk_split_simplelist(tk_send('entryconfigure', index)).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - case conf[0] - when 'text', 'label', 'show' - else - if conf[3] - if conf[3].index('{') - conf[3] = tk_split_list(conf[3]) - else - conf[3] = tk_tcl2ruby(conf[3]) - end - end - if conf[4] - if conf[4].index('{') - conf[4] = tk_split_list(conf[4]) - else - conf[4] = tk_tcl2ruby(conf[4]) - end - end - end - conf - } - end - end -end - -class TkMenuClone@variable, - 'label'=>value, 'value'=>value) - end - def index(index) - @menu.index(index) - end - def invoke(index) - @menu.invoke(index) - end - def insert(index, value) - @menu.add(index, 'radiobutton', 'variable'=>@variable, - 'label'=>value, 'value'=>value) - end - def delete(index, last=None) - @menu.delete(index, last) - end - def yposition(index) - @menu.yposition(index) - end - def menucget(index, key) - @menu.cget(index, key) - end - def menuconfigure(index, key, val=None) - @menu.configure(index, key, val) - end - def menuconfiginfo(index, key=nil) - @menu.configinfo(index, key) - end - def entrycget(index, key) - @menu.entrycget(index, key) - end - def entryconfigure(index, key, val=None) - @menu.entryconfigure(index, key, val) - end - def entryconfiginfo(index, key=nil) - @menu.entryconfiginfo(index, key) - end -end - -module TkComposite - include Tk - extend Tk - - def initialize(parent=nil, *args) - @frame = TkFrame.new(parent) - @path = @epath = @frame.path - initialize_composite(*args) - end - - def epath - @epath - end - - def initialize_composite(*args) end - private :initialize_composite - - def delegate(option, *wins) - unless @delegates - @delegates = {} - @delegates['DEFAULT'] = @frame - end - if @delegates[option].kind_of?(Array) - for i in wins - @delegates[option].push(i) - end - else - @delegates[option] = wins - end - end - - def configure(slot, value=None) - if slot.kind_of? Hash - slot.each{|slot,value| configure slot, value} - else - if @delegates and @delegates[slot] - for i in @delegates[slot] - if not i - i = @delegates['DEFALUT'] - redo - else - last = i.configure(slot, value) - end - end - last - else - super - end - end - end -end - -module TkClipboard - include Tk - extend Tk - - def clear - tk_call 'clipboard', 'clear' - end - def get - begin - tk_call 'selection', 'get', '-selection', 'CLIPBOARD' - rescue - '' - end - end - def set(data) - clear - append(data) - end - def append(data) - tk_call 'clipboard', 'append', data - end - - module_function :clear, :set, :get, :append -end - -autoload :TkCanvas, 'tkcanvas' -autoload :TkImage, 'tkcanvas' -autoload :TkBitmapImage, 'tkcanvas' -autoload :TkPhotoImage, 'tkcanvas' -autoload :TkEntry, 'tkentry' -autoload :TkSpinbox, 'tkentry' -autoload :TkText, 'tktext' -autoload :TkDialog, 'tkdialog' -autoload :TkWarning, 'tkdialog' -autoload :TkMenubar, 'tkmenubar' -autoload :TkAfter, 'tkafter' -autoload :TkPalette, 'tkpalette' -autoload :TkFont, 'tkfont' -autoload :TkVirtualEvent, 'tkvirtevent' -autoload :TkBgError, 'tkbgerror' -autoload :TkManageFocus, 'tkmngfocus' -autoload :TkPalette, 'tkpalette' -autoload :TkWinDDE, 'tkwinpkg' -autoload :TkWinRegistry, 'tkwinpkg' -autoload :TkMacResource, 'tkmacpkg' diff --git a/ext/tk/lib/tkafter.rb b/ext/tk/lib/tkafter.rb deleted file mode 100644 index fe3ee38740..0000000000 --- a/ext/tk/lib/tkafter.rb +++ /dev/null @@ -1,316 +0,0 @@ -# -# tkafter.rb : methods for Tcl/Tk after command -# 2000/08/01 by Hidetoshi Nagai -# -require 'tk' - -class TkAfter - include TkCore - extend TkCore - - Tk_CBID = [0] - Tk_CBTBL = {} - - INTERP._invoke("proc", "rb_after", "args", "ruby [format \"TkAfter.callback %%Q!%s!\" $args]") - - ############################### - # class methods - ############################### - def TkAfter.callback(arg) - @after_id = nil - arg = Array(tk_split_list(arg)) - obj_id = arg.shift - ex_obj = Tk_CBTBL[obj_id] - return nil if ex_obj == nil; # canceled - _get_eval_string(ex_obj.do_callback(*arg)) - end - - def TkAfter.info - tk_call('after', 'info').split(' ').collect!{|id| - ret = Tk_CBTBL.find{|key,val| val.after_id == id} - (ret == nil)? id: ret[1] - } - end - - ############################### - # instance methods - ############################### - def do_callback(*args) - @in_callback = true - begin - ret = @current_proc.call(*args) - rescue StandardError, NameError - if @cancel_on_exception - cancel - return nil - else - fail $! - end - end - if @set_next - set_next_callback(*args) - else - @set_next = true - end - @in_callback = false - ret - end - - def set_callback(sleep, args=nil) - @after_script = "rb_after #{@id} #{_get_eval_string(args)}" - @after_id = tk_call('after', sleep, @after_script) - @current_script = [sleep, @after_script] - end - - def set_next_callback(*args) - if @running == false || @proc_max == 0 || @do_loop == 0 - Tk_CBTBL[@id] = nil ;# for GC - @running = false - return - end - if @current_pos >= @proc_max - if @do_loop < 0 || (@do_loop -= 1) > 0 - @current_pos = 0 - else - Tk_CBTBL[@id] = nil ;# for GC - @running = false - return - end - end - - @current_args = args - - if @sleep_time.kind_of? Proc - sleep = @sleep_time.call(*args) - else - sleep = @sleep_time - end - @current_sleep = sleep - - cmd, *cmd_args = @loop_proc[@current_pos] - @current_pos += 1 - @current_proc = cmd - - if cmd_args[0].kind_of? Proc - #c = cmd_args.shift - #cb_args = c.call(*(cmd_args + args)) - cb_args = cmd_args[0].call(*args) - else - cb_args = cmd_args - end - - set_callback(sleep, cb_args) - end - - def initialize(*args) - @id = format("a%.4d", Tk_CBID[0]) - Tk_CBID[0] += 1 - - @set_next = true - - @init_sleep = 0 - @init_proc = nil - @init_args = [] - - @current_script = [] - @current_proc = nil - @current_args = nil - - @sleep_time = 0 - @current_sleep = 0 - @loop_exec = 0 - @do_loop = 0 - @loop_proc = [] - @proc_max = 0 - @current_pos = 0 - - @after_id = nil - @after_script = nil - - @cancel_on_exception = true - - set_procs(*args) if args != [] - - @running = false - end - - attr :after_id - attr :after_script - attr :current_proc - attr :current_sleep - - attr_accessor :loop_exec - - def get_procs - [@init_sleep, @init_proc, @init_args, @sleep_time, @loop_exec, @loop_proc] - end - - def current_status - [@running, @current_sleep, @current_proc, @current_args, - @do_loop, @cancel_on_exception] - end - - def cancel_on_exception? - @cancel_on_exception - end - - def cancel_on_exception=(mode) - @cancel_on_exception = mode - end - - def running? - @running - end - - def loop_rest - @do_loop - end - - def loop_rest=(rest) - @do_loop = rest - end - - def set_procs(interval, loop_exec, *procs) - if !interval == 'idle' \ - && !interval.kind_of?(Integer) && !interval.kind_of?(Proc) - fail format("%s need to be Integer or Proc", interval.inspect) - end - @sleep_time = interval - - @loop_proc = [] - procs.each{|e| - if e.kind_of? Proc - @loop_proc.push([e]) - else - @loop_proc.push(e) - end - } - @proc_max = @loop_proc.size - @current_pos = 0 - - @do_loop = 0 - if loop_exec - if loop_exec.kind_of?(Integer) && loop_exec < 0 - @loop_exec = -1 - elsif loop_exec == nil || loop_exec == false || loop_exec == 0 - @loop_exec = 1 - else - if not loop_exec.kind_of?(Integer) - fail format("%s need to be Integer", loop_exec.inspect) - end - @loop_exec = loop_exec - end - @do_loop = @loop_exec - end - - self - end - - def add_procs(*procs) - procs.each{|e| - if e.kind_of? Proc - @loop_proc.push([e]) - else - @loop_proc.push(e) - end - } - @proc_max = @loop_proc.size - - self - end - - def set_start_proc(sleep, init_proc, *init_args) - if !sleep == 'idle' && !sleep.kind_of?(Integer) - fail format("%s need to be Integer", sleep.inspect) - end - @init_sleep = sleep - @init_proc = init_proc - @init_args = init_args - self - end - - def start(*init_args) - return nil if @running - - Tk_CBTBL[@id] = self - @do_loop = @loop_exec - @current_pos = 0 - - argc = init_args.size - if argc > 0 - sleep = init_args.shift - if !sleep == 'idle' && !sleep.kind_of?(Integer) - fail format("%s need to be Integer", sleep.inspect) - end - @init_sleep = sleep - end - @init_proc = init_args.shift if argc > 1 - @init_args = init_args if argc > 0 - - @current_sleep = @init_sleep - @running = true - if @init_proc - if not @init_proc.kind_of? Proc - fail format("%s need to be Proc", @init_proc.inspect) - end - @current_proc = @init_proc - set_callback(sleep, @init_args) - @set_next = false if @in_callback - else - set_next_callback(*@init_args) - end - - self - end - - def restart(*restart_args) - cancel if @running - if restart_args == [] - start(@init_sleep, @init_proc, *@init_args) - else - start(*restart_args) - end - end - - def cancel - @running = false - tk_call 'after', 'cancel', @after_id if @after_id - @after_id = nil - Tk_CBTBL[@id] = nil ;# for GC - self - end - alias stop cancel - - def continue(wait=nil) - sleep, cmd = @current_script - return nil if cmd == nil || @running == true - if wait - if not wait.kind_of? Integer - fail format("%s need to be Integer", wait.inspect) - end - sleep = wait - end - Tk_CBTBL[@id] = self - @running = true - @after_id = tk_call('after', sleep, cmd) - self - end - - def skip - return nil if @running == false - cancel - Tk_CBTBL[@id] = self - @running = true - set_next_callback(@current_args) - self - end - - def info - if @after_id - inf = tk_split_list(tk_call('after', 'info', @after_id)) - [Tk_CBTBL[inf[0][1]], inf[1]] - else - nil - end - end -end diff --git a/ext/tk/lib/tkbgerror.rb b/ext/tk/lib/tkbgerror.rb deleted file mode 100644 index 8022077a3f..0000000000 --- a/ext/tk/lib/tkbgerror.rb +++ /dev/null @@ -1,17 +0,0 @@ -# -# tkbgerror -- bgerror ( tkerror ) module -# 1998/07/16 by Hidetoshi Nagai -# -require 'tk' - -module TkBgError - extend Tk - - def bgerror(message) - tk_call 'bgerror', message - end - alias tkerror bgerror - alias show bgerror - - module_function :bgerror, :tkerror, :show -end diff --git a/ext/tk/lib/tkcanvas.rb b/ext/tk/lib/tkcanvas.rb deleted file mode 100644 index 94376072d3..0000000000 --- a/ext/tk/lib/tkcanvas.rb +++ /dev/null @@ -1,863 +0,0 @@ - -# tkcanvas.rb - Tk canvas classes -# $Date$ -# by Yukihiro Matsumoto -# $Date$ -# by Hidetoshi Nagai - -require "tk" -require 'tkfont' - -module TkTreatCItemFont - include TkTreatItemFont - - ItemCMD = ['itemconfigure', TkComm::None] - def __conf_cmd(idx) - ItemCMD[idx] - end - - def __item_pathname(tagOrId) - if tagOrId.kind_of?(TkcItem) || tagOrId.kind_of?(TkcTag) - self.path + ';' + tagOrId.id.to_s - else - self.path + ';' + tagOrId.to_s - end - end -end - -class TkCanvasvalue}) - else - tk_send 'itemconfigure', tagid(tagOrId), "-#{key}", value - end - end - end -# def itemconfigure(tagOrId, key, value=None) -# if key.kind_of? Hash -# tk_send 'itemconfigure', tagid(tagOrId), *hash_kv(key) -# else -# tk_send 'itemconfigure', tagid(tagOrId), "-#{key}", value -# end -# end -# def itemconfigure(tagOrId, keys) -# tk_send 'itemconfigure', tagid(tagOrId), *hash_kv(keys) -# end - - def itemconfiginfo(tagOrId, key=nil) - if key - case key - when 'dash', 'activedash', 'disableddash' - conf = tk_split_simplelist(tk_send 'itemconfigure', - tagid(tagOrId), "-#{key}") - if conf[3] && conf[3] =~ /^[0-9]/ - conf[3] = list(conf[3]) - end - if conf[4] && conf[4] =~ /^[0-9]/ - conf[4] = list(conf[4]) - end - when 'text', 'label', 'show', 'data', 'file', 'maskdata', 'maskfile' - conf = tk_split_simplelist(tk_send 'itemconfigure', - tagid(tagOrId), "-#{key}") - else - conf = tk_split_list(tk_send 'itemconfigure', - tagid(tagOrId), "-#{key}") - end - conf[0] = conf[0][1..-1] - conf - else - tk_split_simplelist(tk_send 'itemconfigure', - tagid(tagOrId)).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - case conf[0] - when 'text', 'label', 'show', 'data', 'file', 'maskdata', 'maskfile' - when 'dash', 'activedash', 'disableddash' - if conf[3] && conf[3] =~ /^[0-9]/ - conf[3] = list(conf[3]) - end - if conf[4] && conf[4] =~ /^[0-9]/ - conf[4] = list(conf[4]) - end - else - if conf[3] - if conf[3].index('{') - conf[3] = tk_split_list(conf[3]) - else - conf[3] = tk_tcl2ruby(conf[3]) - end - end - if conf[4] - if conf[4].index('{') - conf[4] = tk_split_list(conf[4]) - else - conf[4] = tk_tcl2ruby(conf[4]) - end - end - end - conf - } - end - end - - def lower(tag, below=None) - tk_send 'lower', tagid(tag), tagid(below) - end - - def move(tag, x, y) - tk_send 'move', tagid(tag), x, y - end - - def postscript(keys) - tk_send "postscript", *hash_kv(keys) - end - - def raise(tag, above=None) - tk_send 'raise', tagid(tag), tagid(above) - end - - def scale(tag, x, y, xs, ys) - tk_send 'scale', tagid(tag), x, y, xs, ys - end - - def scan_mark(x, y) - tk_send 'scan', 'mark', x, y - end - def scan_dragto(x, y) - tk_send 'scan', 'dragto', x, y - end - - def select(mode, *args) - tk_send 'select', mode, *args - end - def select_adjust(tagOrId, index) - select('adjust', tagid(tagOrId), index) - end - def select_clear - select('clear') - end - def select_from(tagOrId, index) - select('from', tagid(tagOrId), index) - end - def select_item - select('item') - end - def select_to(tagOrId, index) - select('to', tagid(tagOrId), index) - end - - def itemtype(tag) - TkcItem.type2class(tk_send 'type', tagid(tag)) - end -end - -module TkcTagAccess - include TkComm - include TkTreatTagFont - - def addtag(tag) - @c.addtag(tag, 'with', @id) - end - - def bbox - @c.bbox(@id) - end - - def bind(seq, cmd=Proc.new, args=nil) - @c.itembind @id, seq, cmd, args - end - - def bindinfo(seq=nil) - @c.itembindinfo @id, seq - end - - def cget(option) - @c.itemcget @id, option - end - - def configure(key, value=None) - @c.itemconfigure @id, key, value - end -# def configure(keys) -# @c.itemconfigure @id, keys -# end - - def configinfo(key=nil) - @c.itemconfiginfo @id, key - end - - def coords(*args) - @c.coords @id, *args - end - - def dchars(first, last=None) - @c.dchars @id, first, last - end - - def dtag(tag_to_del=None) - @c.dtag @id, tag_to_del - end - - def find - @c.find 'withtag', @id - end - alias list find - - def focus - @c.itemfocus @id - end - - def gettags - @c.gettags @id - end - - def icursor(index) - @c.icursor @id, index - end - - def index(index) - @c.index @id, index - end - - def insert(beforethis, string) - @c.insert @id, beforethis, string - end - - def lower(belowthis=None) - @c.lower @id, belowthis - end - - def move(xamount, yamount) - @c.move @id, xamount, yamount - end - - def raise(abovethis=None) - @c.raise @id, abovethis - end - - def scale(xorigin, yorigin, xscale, yscale) - @c.scale @id, xorigin, yorigin, xscale, yscale - end - - def select_adjust(index) - @c.select('adjust', @id, index) - end - def select_from(index) - @c.select('from', @id, index) - end - def select_to(index) - @c.select('to', @id, index) - end - - def itemtype - @c.itemtype @id - end - - # Followings operators supports logical expressions of canvas tags - # (for Tk8.3+). - # If tag1.path is 't1' and tag2.path is 't2', then - # ltag = tag1 & tag2; ltag.path => "(t1)&&(t2)" - # ltag = tag1 | tag2; ltag.path => "(t1)||(t2)" - # ltag = tag1 ^ tag2; ltag.path => "(t1)^(t2)" - # ltag = - tag1; ltag.path => "!(t1)" - def & (tag) - if tag.kind_of? TkObject - TkcTagString.new(@c, '(' + @id + ')&&(' + tag.path + ')') - else - TkcTagString.new(@c, '(' + @id + ')&&(' + tag.to_s + ')') - end - end - - def | (tag) - if tag.kind_of? TkObject - TkcTagString.new(@c, '(' + @id + ')||(' + tag.path + ')') - else - TkcTagString.new(@c, '(' + @id + ')||(' + tag.to_s + ')') - end - end - - def ^ (tag) - if tag.kind_of? TkObject - TkcTagString.new(@c, '(' + @id + ')^(' + tag.path + ')') - else - TkcTagString.new(@c, '(' + @id + ')^(' + tag.to_s + ')') - end - end - - def -@ - TkcTagString.new(@c, '!(' + @id + ')') - end -end - -class TkcTag - -require "tk" - -TopLevel = TkToplevel -Frame = TkFrame -Label = TkLabel -Button = TkButton -Radiobutton = TkRadioButton -Checkbutton = TkCheckButton -Message = TkMessage -Entry = TkEntry -Text = TkText -Scale = TkScale -Scrollbar = TkScrollbar -Listbox = TkListbox -Menu = TkMenu -Menubutton = TkMenubutton -Canvas = TkCanvas -Arc = TkcArc -Bitmap = TkcBitmap -Line = TkcLine -Oval = TkcOval -Polygon = TkcPolygon -Rectangle = TkcRectangle -TextItem = TkcText -WindowItem = TkcWindow -Selection = TkSelection -Winfo = TkWinfo -Pack = TkPack -Variable = TkVariable - -def Mainloop - Tk.mainloop -end diff --git a/ext/tk/lib/tkdialog.rb b/ext/tk/lib/tkdialog.rb deleted file mode 100644 index 1133db6ae9..0000000000 --- a/ext/tk/lib/tkdialog.rb +++ /dev/null @@ -1,141 +0,0 @@ -require "tk" - -class TkDialog < TkWindow - extend Tk - - # initialize tk_dialog - def initialize(keys = nil) - super() - @var = TkVariable.new - id = @var.id - - @title = title - - @message = message - @message_config = message_config - - @bitmap = bitmap - @bitmap_config = message_config - - @default_button = default_button - - @buttons = buttons - @button_configs = proc{|num| button_configs num} - - if keys.kind_of? Hash - @title = keys['title'] if keys['title'] - @message = keys['message'] if keys['message'] - @bitmap = keys['bitmap'] if keys['bitmap'] - @default_button = keys['default'] if keys['default'] - @buttons = keys['buttons'] if keys['buttons'] - - @command = keys['prev_command'] - - @message_config = keys['message_config'] if keys['message_config'] - @bitmap_config = keys['bitmap_config'] if keys['bitmap_config'] - @button_configs = keys['button_configs'] if keys['button_configs'] - end - - if @title.include? ?\s - @title = '{' + @title + '}' - end - - @buttons = tk_split_list(@buttons) if @buttons.kind_of? String - @buttons = @buttons.collect{|s| - if s.kind_of? Array - s = s.join(' ') - end - if s.include? ?\s - '{' + s + '}' - else - s - end - } - - config = "" - if @message_config.kind_of? Hash - config << format("%s.msg configure %s\n", - @path, hash_kv(@message_config).join(' ')) - end - if @bitmap_config.kind_of? Hash - config << format("%s.msg configure %s\n", - @path, hash_kv(@bitmap_config).join(' ')) - end - if @button_configs.kind_of? Proc - @buttons.each_index{|i| - if (c = @button_configs.call(i)).kind_of? Hash - config << format("%s.button%s configure %s\n", - @path, i, hash_kv(c).join(' ')) - end - } - end - config = 'after idle {' + config + '};' if config != "" - - if @command.kind_of? Proc - @command.call(self) - end - - INTERP._eval('eval {global '+id+';'+config+ - 'set '+id+' [tk_dialog '+ - @path+" "+@title+" {#{@message}} "+@bitmap+" "+ - String(@default_button)+" "+@buttons.join(' ')+']}') - end - def value - return @var.value.to_i - end - ###################################################### - # # - # these methods must be overridden for each dialog # - # # - ###################################################### - def title - return "DIALOG" - end - def message - return "MESSAGE" - end - def message_config - return nil - end - def bitmap - return "info" - end - def bitmap_config - return nil - end - def default_button - return 0 - end - def buttons - #return "BUTTON1 BUTTON2" - return ["BUTTON1", "BUTTON2"] - end - def button_configs(num) - return nil - end -end - -# -# dialog for warning -# -class TkWarning < TkDialog - def initialize(mes) - @mes = mes - super() - end - def message - return @mes - end - def title - return "WARNING"; - end - def bitmap - return "warning"; - end - def default_button - return 0; - end - def buttons - return "OK"; - end -end diff --git a/ext/tk/lib/tkentry.rb b/ext/tk/lib/tkentry.rb deleted file mode 100644 index f301bbdace..0000000000 --- a/ext/tk/lib/tkentry.rb +++ /dev/null @@ -1,221 +0,0 @@ -# -# tkentry.rb - Tk entry classes -# $Date$ -# by Yukihiro Matsumoto - -require 'tk.rb' - -class TkEntry'Helvetica'.freeze, 'size'=>-12} - knj = 'k14' - #knj = '-misc-fixed-medium-r-normal--14-*-*-*-c-*-jisx0208.1983-0' - when 'windows' - ltn = {'family'=>'MS Sans Serif'.freeze, 'size'=>8} - knj = 'mincho' - when 'macintosh' - ltn = 'system' - knj = 'mincho' - else # unknown - ltn = 'Helvetica' - knj = 'mincho' - end - end - rescue - ltn = 'Helvetica' - knj = 'mincho' - end - - else # not JAPANIZED_TK - begin - platform = tk_call('set', 'tcl_platform(platform)') - case platform - when 'unix' - ltn = {'family'=>'Helvetica'.freeze, 'size'=>-12} - knj = 'k14' - #knj = '-misc-fixed-medium-r-normal--14-*-*-*-c-*-jisx0208.1983-0' - when 'windows' - ltn = {'family'=>'MS Sans Serif'.freeze, 'size'=>8} - knj = 'mincho' - when 'macintosh' - ltn = 'system' - knj = 'mincho' - else # unknown - ltn = 'Helvetica' - knj = 'mincho' - end - rescue - ltn = 'Helvetica' - knj = 'mincho' - end - end - - DEFAULT_LATIN_FONT_NAME = ltn.freeze - DEFAULT_KANJI_FONT_NAME = knj.freeze - - else # unknown version - DEFAULT_LATIN_FONT_NAME = 'Helvetica'.freeze - DEFAULT_KANJI_FONT_NAME = 'mincho'.freeze - - end - - if $DEBUG - print "default latin font = "; p DEFAULT_LATIN_FONT_NAME - print "default kanji font = "; p DEFAULT_KANJI_FONT_NAME - end - - ################################### - # class methods - ################################### - def TkFont.families(window=nil) - case (Tk::TK_VERSION) - when /^4\.*/ - ['fixed'] - - when /^8\.*/ - if window - tk_split_simplelist(tk_call('font', 'families', '-displayof', window)) - else - tk_split_simplelist(tk_call('font', 'families')) - end - end - end - - def TkFont.names - case (Tk::TK_VERSION) - when /^4\.*/ - r = ['fixed'] - r += ['a14', 'k14'] if JAPANIZED_TK - Tk_FontNameTBL.each_value{|obj| r.push(obj)} - r | [] - - when /^8\.*/ - tk_split_simplelist(tk_call('font', 'names')) - - end - end - - def TkFont.create_copy(font) - fail 'source-font need to be TkFont' unless font.kind_of? TkFont - keys = {} - font.configinfo.each{|key,value| keys[key] = value } - TkFont.new(font.latin_font, font.kanji_font, keys) - end - - def TkFont.get_obj(name) - if name =~ /^(@font[0-9]+)(|c|l|k)$/ - Tk_FontNameTBL[$1] - else - nil - end - end - - def TkFont.init_widget_font(path, *args) - case (Tk::TK_VERSION) - when /^4\.*/ - conf = tk_split_simplelist(tk_call(*args)). - find_all{|prop| prop[0..5]=='-font ' || prop[0..10]=='-kanjifont '}. - collect{|prop| tk_split_simplelist(prop)} - if font_inf = conf.assoc('-font') - ltn = font_inf[4] - ltn = nil if ltn == [] - else - #ltn = nil - raise RuntimeError, "unknown option '-font'" - end - if font_inf = conf.assoc('-kanjifont') - knj = font_inf[4] - knj = nil if knj == [] - else - knj = nil - end - TkFont.new(ltn, knj).call_font_configure(path, *(args + [{}])) - - when /^8\.*/ - font_prop = tk_split_simplelist(tk_call(*args)).find{|prop| - prop[0..5] == '-font ' - } - unless font_prop - raise RuntimeError, "unknown option '-font'" - end - fnt = tk_split_simplelist(font_prop)[4] - if fnt == "" - TkFont.new(nil, nil).call_font_configure(path, *(args + [{}])) - else - begin - compound = Hash[*tk_split_simplelist(tk_call('font', 'configure', - fnt))].collect{|key,value| - [key[1..-1], value] - }.assoc('compound')[1] - rescue - compound = [] - end - if compound == [] - TkFont.new(fnt, DEFAULT_KANJI_FONT_NAME) \ - .call_font_configure(path, *(args + [{}])) - else - TkFont.new(compound[0], compound[1]) \ - .call_font_configure(path, *(args + [{}])) - end - end - end - end - - def TkFont.used_on(path=nil) - if path - Tk_FontUseTBL[path] - else - Tk_FontUseTBL.values | [] - end - end - - def TkFont.failsafe(font) - begin - if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK - tk_call('font', 'failsafe', font) - end - rescue - end - end - - ################################### - private - ################################### - def initialize(ltn=DEFAULT_LATIN_FONT_NAME, knj=nil, keys=nil) - @id = format("@font%.4d", Tk_FontID[0]) - Tk_FontID[0] += 1 - Tk_FontNameTBL[@id] = self - knj = DEFAULT_KANJI_FONT_NAME if JAPANIZED_TK && !knj - create_compoundfont(ltn, knj, keys) - end - - def _get_font_info_from_hash(font) - foundry = (info = font['foundry'] .to_s)? info: '*' - family = (info = font['family'] .to_s)? info: '*' - weight = (info = font['weight'] .to_s)? info: '*' - slant = (info = font['slant'] .to_s)? info: '*' - swidth = (info = font['swidth'] .to_s)? info: '*' - adstyle = (info = font['adstyle'] .to_s)? info: '*' - pixels = (info = font['pixels'] .to_s)? info: '*' - points = (info = font['points'] .to_s)? info: '*' - resx = (info = font['resx'] .to_s)? info: '*' - resy = (info = font['resy'] .to_s)? info: '*' - space = (info = font['space'] .to_s)? info: '*' - avgWidth = (info = font['avgWidth'].to_s)? info: '*' - charset = (info = font['charset'] .to_s)? info: '*' - encoding = (info = font['encoding'].to_s)? info: '*' - - [foundry, family, weight, slant, swidth, adstyle, - pixels, points, resx, resy, space, avgWidth, charset, encoding] - end - - def create_latinfont_tk4x(font) - if font.kind_of? Hash - @latinfont = '-' + _get_font_info_from_hash(font).join('-') + '-' - - elsif font.kind_of? Array - finfo = {} - finfo['family'] = font[0].to_s - if font[1] - fsize = font[1].to_s - if fsize != '0' && fsize =~ /^(|\+|-)([0-9]+)$/ - if $1 == '-' - finfo['pixels'] = $2 - else - finfo['points'] = $2 - end - else - finfo['points'] = '13' - end - end - font[2..-1].each{|style| - case (style) - when 'normal' - finfo['weight'] = style - when 'bold' - finfo['weight'] = style - when 'roman' - finfo['slant'] = 'r' - when 'italic' - finfo['slant'] = 'i' - end - } - - @latinfont = '-' + _get_font_info_from_hash(finfo).join('-') + '-' - - elsif font.kind_of? TkFont - @latinfont = font.latin_font - - else - if font - @latinfont = font - else - @latinfont = DEFAULT_LATIN_FONT_NAME - end - - end - end - - def create_kanjifont_tk4x(font) - unless JAPANIZED_TK - @kanjifont = "" - return - end - - if font.kind_of? Hash - @kanjifont = '-' + _get_font_info_from_hash(font).join('-') + '-' - - elsif font.kind_of? Array - finfo = {} - finfo['family'] = font[0].to_s - if font[1] - fsize = font[1].to_s - if fsize != '0' && fsize =~ /^(|\+|-)([0-9]+)$/ - if $1 == '-' - finfo['pixels'] = $2 - else - finfo['points'] = $2 - end - else - finfo['points'] = '13' - end - end - font[2..-1].each{|style| - case (style) - when 'normal' - finfo['weight'] = style - when 'bold' - finfo['weight'] = style - when 'roman' - finfo['slant'] = 'r' - when 'italic' - finfo['slant'] = 'i' - end - } - - @kanjifont = '-' + _get_font_info_from_hash(finfo).join('-') + '-' - elsif font.kind_of? TkFont - @kanjifont = font.kanji_font - else - if font - @kanjifont = font - else - @kanjifont = DEFAULT_KANJI_FONT_NAME - end - end - end - - def create_compoundfont_tk4x(ltn, knj, keys) - create_latinfont(ltn) - create_kanjifont(knj) - - if JAPANIZED_TK - @compoundfont = [[@latinfont], [@kanjifont]] - @fontslot = {'font'=>@latinfont, 'kanjifont'=>@kanjifont} - else - @compoundfont = @latinfont - @fontslot = {'font'=>@latinfont} - end - end - - def create_latinfont_tk8x(font) - @latinfont = @id + 'l' - - if JAPANIZED_TK - if font.kind_of? Hash - if font['charset'] - tk_call('font', 'create', @latinfont, *hash_kv(font)) - else - tk_call('font', 'create', @latinfont, - '-charset', 'iso8859', *hash_kv(font)) - end - elsif font.kind_of? Array - tk_call('font', 'create', @latinfont, '-copy', array2tk_list(font)) - tk_call('font', 'configure', @latinfont, '-charset', 'iso8859') - elsif font.kind_of? TkFont - tk_call('font', 'create', @latinfont, '-copy', font.latin_font) - elsif font - tk_call('font', 'create', @latinfont, '-copy', font, - '-charset', 'iso8859') - else - tk_call('font', 'create', @latinfont, '-charset', 'iso8859') - end - else - if font.kind_of? Hash - tk_call('font', 'create', @latinfont, *hash_kv(font)) - else - keys = {} - if font.kind_of? Array - actual_core(array2tk_list(font)).each{|key,val| keys[key] = val} - elsif font.kind_of? TkFont - actual_core(font.latin_font).each{|key,val| keys[key] = val} - elsif font - actual_core(font).each{|key,val| keys[key] = val} - end - tk_call('font', 'create', @latinfont, *hash_kv(keys)) - end - - if font && @compoundfont - keys = {} - actual_core(@latinfont).each{|key,val| keys[key] = val} - tk_call('font', 'configure', @compoundfont, *hash_kv(keys)) - end - end - end - - def create_kanjifont_tk8x(font) - @kanjifont = @id + 'k' - - if JAPANIZED_TK - if font.kind_of? Hash - if font['charset'] - tk_call('font', 'create', @kanjifont, *hash_kv(font)) - else - tk_call('font', 'create', @kanjifont, - '-charset', 'jisx0208.1983', *hash_kv(font)) - end - elsif font.kind_of? Array - tk_call('font', 'create', @kanjifont, '-copy', array2tk_list(font)) - tk_call('font', 'configure', @kanjifont, '-charset', 'jisx0208.1983') - elsif font.kind_of? TkFont - tk_call('font', 'create', @kanjifont, '-copy', font.kanji_font) - elsif font - tk_call('font', 'create', @kanjifont, '-copy', font, - '-charset', 'jisx0208.1983') - else - tk_call('font', 'create', @kanjifont, '-charset', 'jisx0208.1983') - end - # end of JAPANIZED_TK - - else - if font.kind_of? Hash - tk_call('font', 'create', @kanjifont, *hash_kv(font)) - else - keys = {} - if font.kind_of? Array - actual_core(array2tk_list(font)).each{|key,val| keys[key] = val} - elsif font.kind_of? TkFont - actual_core(font.kanji_font).each{|key,val| keys[key] = val} - elsif font - actual_core(font).each{|key,val| keys[key] = val} - end - tk_call('font', 'create', @kanjifont, *hash_kv(keys)) - end - - if font && @compoundfont - keys = {} - actual_core(@kanjifont).each{|key,val| keys[key] = val} - tk_call('font', 'configure', @compoundfont, *hash_kv(keys)) - end - end - end - - def create_compoundfont_tk8x(ltn, knj, keys) - create_latinfont(ltn) - create_kanjifont(knj) - - @compoundfont = @id + 'c' - if JAPANIZED_TK - @fontslot = {'font'=>@compoundfont} - tk_call('font', 'create', @compoundfont, - '-compound', [@latinfont, @kanjifont], *hash_kv(keys)) - else - tk_call('font', 'create', @compoundfont) - - latinkeys = {} - begin - actual_core(@latinfont).each{|key,val| latinkeys[key] = val} - rescue - latinkeys {} - end - if latinkeys != {} - tk_call('font', 'configure', @compoundfont, *hash_kv(latinkeys)) - end - - if knj - kanjikeys = {} - begin - actual_core(@kanjifont).each{|key,val| kanjikeys[key] = val} - rescue - kanjikeys {} - end - if kanjikeys != {} - tk_call('font', 'configure', @compoundfont, *hash_kv(kanjikeys)) - end - end - - @fontslot = {'font'=>@compoundfont} - tk_call('font', 'configure', @compoundfont, *hash_kv(keys)) - end - end - - def actual_core_tk4x(font, window=nil, option=nil) - # dummy - if option - "" - else - [['family',[]], ['size',[]], ['weight',[]], ['slant',[]], - ['underline',[]], ['overstrike',[]], ['charset',[]], - ['pointadjust',[]]] - end - end - - def actual_core_tk8x(font, window=nil, option=nil) - if option == 'compound' - "" - elsif option - if window - tk_call('font', 'actual', font, "-displayof", window, "-#{option}") - else - tk_call('font', 'actual', font, "-#{option}") - end - else - l = tk_split_simplelist(if window - tk_call('font', 'actual', font, - "-displayof", window) - else - tk_call('font', 'actual', font) - end) - r = [] - while key=l.shift - if key == '-compound' - l.shift - else - r.push [key[1..-1], l.shift] - end - end - r - end - end - - def configure_core_tk4x(font, slot, value=None) - "" - end - - def configinfo_core_tk4x(font, option=nil) - # dummy - if option - "" - else - [['family',[]], ['size',[]], ['weight',[]], ['slant',[]], - ['underline',[]], ['overstrike',[]], ['charset',[]], - ['pointadjust',[]]] - end - end - - def configure_core_tk8x(font, slot, value=None) - if slot.kind_of? Hash - tk_call 'font', 'configure', font, *hash_kv(slot) - else - tk_call 'font', 'configure', font, "-#{slot}", value - end - end - - def configinfo_core_tk8x(font, option=nil) - if option == 'compound' - "" - elsif option - tk_call('font', 'configure', font, "-#{option}") - else - l = tk_split_simplelist(tk_call('font', 'configure', font)) - r = [] - while key=l.shift - if key == '-compound' - l.shift - else - r.push [key[1..-1], l.shift] - end - end - r - end - end - - def delete_core_tk4x - Tk_FontNameTBL[@id] = nil - Tk_FontUseTBL.delete_if{|key,value| value == self} - end - - def delete_core_tk8x - begin - tk_call('font', 'delete', @latinfont) - rescue - end - begin - tk_call('font', 'delete', @kanjifont) - rescue - end - begin - tk_call('font', 'delete', @compoundfont) - rescue - end - Tk_FontNameTBL[@id] = nil - Tk_FontUseTBL.delete_if{|key,value| value == self} - end - - def latin_replace_core_tk4x(ltn) - create_latinfont_tk4x(ltn) - @compoundfont[0] = [@latinfont] if JAPANIZED_TK - @fontslot['font'] = @latinfont - Tk_FontUseTBL.dup.each{|w, fobj| - if self == fobj - begin - if w.include?(';') - win, tag = w.split(';') - winobj = tk_tcl2ruby(win) -# winobj.tagfont_configure(tag, {'font'=>@latinfont}) - if winobj.kind_of? TkText - tk_call(win, 'tag', 'configure', tag, '-font', @latinfont) - elsif winobj.kind_of? TkCanvas - tk_call(win, 'itemconfigure', tag, '-font', @latinfont) - elsif winobj.kind_of? TkMenu - tk_call(win, 'entryconfigure', tag, '-font', @latinfont) - else - raise RuntimeError, "unknown widget type" - end - else -# tk_tcl2ruby(w).font_configure('font'=>@latinfont) - tk_call(w, 'configure', '-font', @latinfont) - end - rescue - Tk_FontUseTBL[w] = nil - end - end - } - self - end - - def kanji_replace_core_tk4x(knj) - return self unless JAPANIZED_TK - - create_kanjifont_tk4x(knj) - @compoundfont[1] = [@kanjifont] - @fontslot['kanjifont'] = @kanjifont - Tk_FontUseTBL.dup.each{|w, fobj| - if self == fobj - begin - if w.include?(';') - win, tag = w.split(';') - winobj = tk_tcl2ruby(win) -# winobj.tagfont_configure(tag, {'kanjifont'=>@kanjifont}) - if winobj.kind_of? TkText - tk_call(win, 'tag', 'configure', tag, '-kanjifont', @kanjifont) - elsif winobj.kind_of? TkCanvas - tk_call(win, 'itemconfigure', tag, '-kanjifont', @kanjifont) - elsif winobj.kind_of? TkMenu - tk_call(win, 'entryconfigure', tag, '-kanjifont', @latinfont) - else - raise RuntimeError, "unknown widget type" - end - else -# tk_tcl2ruby(w).font_configure('kanjifont'=>@kanjifont) - tk_call(w, 'configure', '-kanjifont', @kanjifont) - end - rescue - Tk_FontUseTBL[w] = nil - end - end - } - self - end - - def latin_replace_core_tk8x(ltn) - begin - tk_call('font', 'delete', @latinfont) - rescue - end - create_latinfont(ltn) - self - end - - def kanji_replace_core_tk8x(knj) - begin - tk_call('font', 'delete', @kanjifont) - rescue - end - create_kanjifont(knj) - self - end - - def measure_core_tk4x(window, text) - 0 - end - - def measure_core_tk8x(window, text) - if window - number(tk_call('font', 'measure', @compoundfont, - '-displayof', window, text)) - else - number(tk_call('font', 'measure', @compoundfont, text)) - end - end - - def metrics_core_tk4x(font, window, option=nil) - # dummy - if option - "" - else - [['ascent',[]], ['descent',[]], ['linespace',[]], ['fixed',[]]] - end - end - - def metrics_core_tk8x(font, window, option=nil) - if option - if window - number(tk_call('font', 'metrics', font, - "-displayof", window, "-#{option}")) - else - number(tk_call('font', 'metrics', font, "-#{option}")) - end - else - l = tk_split_list(if window - tk_call('font','metrics',font,"-displayof",window) - else - tk_call('font','metrics',font) - end) - r = [] - while key=l.shift - r.push [key[1..-1], l.shift.to_i] - end - r - end - end - - ################################### - # private alias - ################################### - case (Tk::TK_VERSION) - when /^4\.*/ - alias create_latinfont create_latinfont_tk4x - alias create_kanjifont create_kanjifont_tk4x - alias create_compoundfont create_compoundfont_tk4x - alias actual_core actual_core_tk4x - alias configure_core configure_core_tk4x - alias configinfo_core configinfo_core_tk4x - alias delete_core delete_core_tk4x - alias latin_replace_core latin_replace_core_tk4x - alias kanji_replace_core kanji_replace_core_tk4x - alias measure_core measure_core_tk4x - alias metrics_core metrics_core_tk4x - - when /^8\.[0123]/ - alias create_latinfont create_latinfont_tk8x - alias create_kanjifont create_kanjifont_tk8x - alias create_compoundfont create_compoundfont_tk8x - alias actual_core actual_core_tk8x - alias configure_core configure_core_tk8x - alias configinfo_core configinfo_core_tk8x - alias delete_core delete_core_tk8x - alias latin_replace_core latin_replace_core_tk8x - alias kanji_replace_core kanji_replace_core_tk8x - alias measure_core measure_core_tk8x - alias metrics_core metrics_core_tk8x - - when /^8\.*/ - alias create_latinfont create_latinfont_tk8x - alias create_kanjifont create_kanjifont_tk8x - alias create_compoundfont create_compoundfont_tk8x - alias actual_core actual_core_tk8x - alias configure_core configure_core_tk8x - alias configinfo_core configinfo_core_tk8x - alias delete_core delete_core_tk8x - alias latin_replace_core latin_replace_core_tk8x - alias kanji_replace_core kanji_replace_core_tk8x - alias measure_core measure_core_tk8x - alias metrics_core metrics_core_tk8x - - end - - ################################### - public - ################################### - def method_missing(id, *args) - name = id.id2name - case args.length - when 1 - configure name, args[0] - when 0 - begin - configinfo name - rescue - fail NameError, "undefined local variable or method `#{name}' for #{self.to_s}", error_at - end - else - fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at - end - end - - def call_font_configure(path, *args) - args += hash_kv(args.pop.update(@fontslot)) - tk_call(*args) - Tk_FontUseTBL[path] = self - self - end - - def used - ret = [] - Tk_FontUseTBL.each{|key,value| - if key.include?(';') - win, tag = key.split(';') - winobj = tk_tcl2ruby(win) - if winobj.kind_of? TkText - ret.push([winobj, winobj.tagid2obj(tag)]) - elsif winobj.kind_of? TkCanvas - if (tagobj = TkcTag.id2obj(winobj, tag)).kind_of? TkcTag - ret.push([winobj, tagobj]) - elsif (tagobj = TkcItem.id2obj(tag)).kind_of? TkcItem - ret.push([winobj, tagobj]) - else - ret.push([winobj, tag]) - end - elsif winobj.kind_of? TkMenu - ret.push([winobj, tag]) - else - ret.push([win, tag]) - end - else - ret.push(tk_tcl2ruby(key)) if value == self - end - } - ret - end - - def id - @id - end - - def to_eval - font - end - - def font - @compoundfont - end - - def latin_font - @latinfont - end - - def kanji_font - @kanjifont - end - - def actual(option=nil) - actual_core(@compoundfont, nil, option) - end - - def actual_displayof(window, option=nil) - window = '.' unless window - actual_core(@compoundfont, window, option) - end - - def latin_actual(option=nil) - actual_core(@latinfont, nil, option) - end - - def latin_actual_displayof(window, option=nil) - window = '.' unless window - actual_core(@latinfont, window, option) - end - - def kanji_actual(option=nil) - #if JAPANIZED_TK - if @kanjifont != "" - actual_core(@kanjifont, nil, option) - else - actual_core_tk4x(nil, nil, option) - end - end - - def kanji_actual_displayof(window, option=nil) - #if JAPANIZED_TK - if @kanjifont != "" - window = '.' unless window - actual_core(@kanjifont, window, option) - else - actual_core_tk4x(nil, window, option) - end - end - - def [](slot) - configinfo slot - end - - def []=(slot, val) - configure slot, val - end - - def configure(slot, value=None) - configure_core(@compoundfont, slot, value) - end - - def configinfo(slot=nil) - configinfo_core(@compoundfont, slot) - end - - def delete - delete_core - end - - def latin_configure(slot, value=None) - if JAPANIZED_TK - configure_core(@latinfont, slot, value) - else - configure(slot, value) - end - end - - def latin_configinfo(slot=nil) - if JAPANIZED_TK - configinfo_core(@latinfont, slot) - else - configinfo(slot) - end - end - - def kanji_configure(slot, value=None) - #if JAPANIZED_TK - if @kanjifont != "" - configure_core(@kanjifont, slot, value) - configure('size'=>configinfo('size')) # to reflect new configuration - else - #"" - configure(slot, value) - end - end - - def kanji_configinfo(slot=nil) - #if JAPANIZED_TK - if @kanjifont != "" - configinfo_core(@kanjifont, slot) - else - #[] - configinfo(slot) - end - end - - def replace(ltn, knj) - latin_replace(ltn) - kanji_replace(knj) - self - end - - def latin_replace(ltn) - latin_replace_core(ltn) - reset_pointadjust - end - - def kanji_replace(knj) - kanji_replace_core(knj) - reset_pointadjust - end - - def measure(text) - measure_core(nil, text) - end - - def measure_displayof(window, text) - window = '.' unless window - measure_core(window, text) - end - - def metrics(option=nil) - metrics_core(@compoundfont, nil, option) - end - - def metrics_displayof(window, option=nil) - window = '.' unless window - metrics_core(@compoundfont, window, option) - end - - def latin_metrics(option=nil) - metrics_core(@latinfont, nil, option) - end - - def latin_metrics_displayof(window, option=nil) - window = '.' unless window - metrics_core(@latinfont, window, option) - end - - def kanji_metrics(option=nil) - if JAPANIZED_TK - metrics_core(@kanjifont, nil, option) - else - metrics_core_tk4x(nil, nil, option) - end - end - - def kanji_metrics_displayof(window, option=nil) - if JAPANIZED_TK - window = '.' unless window - metrics_core(@kanjifont, window, option) - else - metrics_core_tk4x(nil, window, option) - end - end - - def reset_pointadjust - begin - if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK - configure('pointadjust' => latin_actual.assoc('size')[1].to_f / - kanji_actual.assoc('size')[1].to_f ) - end - rescue - end - self - end - - ################################### - # public alias - ################################### - alias ascii_font latin_font - alias create_asciifont create_latinfont - alias ascii_actual latin_actual - alias ascii_actual_displayof latin_actual_displayof - alias ascii_configure latin_configure - alias ascii_configinfo latin_configinfo - alias ascii_replace latin_replace - alias ascii_metrics latin_metrics - -end - -module TkTreatTagFont - def font_configinfo - @parent.tagfont_configinfo(@id) - end -# alias font font_configinfo - - def font_configure(slot) - @parent.tagfont_configure(@id, slot) - end - - def latinfont_configure(ltn, keys=nil) - @parent.latintagfont_configure(@id, ltn, keys) - end - alias asciifont_configure latinfont_configure - - def kanjifont_configure(knj, keys=nil) - @parent.kanjitagfont_configure(@id, ltn, keys) - end - - def font_copy(window, wintag=nil) - @parent.tagfont_copy(@id, window, wintag) - end - - def latinfont_copy(window, wintag=nil) - @parent.latintagfont_copy(@id, window, wintag) - end - alias asciifont_copy latinfont_copy - - def kanjifont_copy(window, wintag=nil) - @parent.kanjitagfont_copy(@id, window, wintag) - end -end diff --git a/ext/tk/lib/tkmenubar.rb b/ext/tk/lib/tkmenubar.rb deleted file mode 100644 index 441f3f5c03..0000000000 --- a/ext/tk/lib/tkmenubar.rb +++ /dev/null @@ -1,137 +0,0 @@ -# -# tkmenubar.rb -# -# Copyright (C) 1998 maeda shugo. All rights reserved. -# This file can be distributed under the terms of the Ruby. - -# Usage: -# -# menu_spec = [ -# [['File', 0], -# ['Open', proc{puts('Open clicked')}, 0], -# '---', -# ['Quit', proc{exit}, 0]], -# [['Edit', 0], -# ['Cut', proc{puts('Cut clicked')}, 2], -# ['Copy', proc{puts('Copy clicked')}, 0], -# ['Paste', proc{puts('Paste clicked')}, 0]] -# ] -# menubar = TkMenubar.new(nil, menu_spec, -# 'tearoff'=>false, -# 'foreground'=>'grey40', -# 'activeforeground'=>'red', -# 'font'=>'-adobe-helvetica-bold-r-*--12-*-iso8859-1') -# menubar.pack('side'=>'top', 'fill'=>'x') -# -# -# OR -# -# -# menubar = TkMenubar.new -# menubar.add_menu([['File', 0], -# ['Open', proc{puts('Open clicked')}, 0], -# '---', -# ['Quit', proc{exit}, 0]]) -# menubar.add_menu([['Edit', 0], -# ['Cut', proc{puts('Cut clicked')}, 2], -# ['Copy', proc{puts('Copy clicked')}, 0], -# ['Paste', proc{puts('Paste clicked')}, 0]]) -# menubar.configure('tearoff', false) -# menubar.configure('foreground', 'grey40') -# menubar.configure('activeforeground', 'red') -# menubar.configure('font', '-adobe-helvetica-bold-r-*--12-*-iso8859-1') -# menubar.pack('side'=>'top', 'fill'=>'x') - -# The format of the menu_spec is: -# [ -# [ -# [button text, underline, accelerator], -# [menu label, command, underline, accelerator], -# '---', # separator -# ... -# ], -# ... -# ] - -# underline and accelerator are optional parameters. -# Hashes are OK instead of Arrays. - -# To use add_menu, configuration must be done by calling configure after -# adding all menus by add_menu, not by the constructor arguments. - -require "tk" - -class TkMenubar item_info) - end - end - - mbtn.menu(menu) - @menus.push([mbtn, menu]) - delegate('tearoff', menu) - delegate('foreground', mbtn, menu) - delegate('background', mbtn, menu) - delegate('disabledforeground', mbtn, menu) - delegate('activeforeground', mbtn, menu) - delegate('activebackground', mbtn, menu) - delegate('font', mbtn, menu) - delegate('kanjifont', mbtn, menu) - mbtn.pack('side' => 'left') - end - - def [](index) - return @menus[index] - end -end diff --git a/ext/tk/lib/tkmngfocus.rb b/ext/tk/lib/tkmngfocus.rb deleted file mode 100644 index 921fb646e7..0000000000 --- a/ext/tk/lib/tkmngfocus.rb +++ /dev/null @@ -1,27 +0,0 @@ -# -# tkmngfocus.rb : methods for Tcl/Tk standard library 'focus.tcl' -# 1998/07/16 by Hidetoshi Nagai -# -require 'tk' - -module TkManageFocus - extend Tk - - def TkManageFocus.followsMouse - tk_call 'tk_focusFollowsMouse' - end - - def TkManageFocus.next(window) - tk_call 'tk_focusNext', window - end - def focusNext - TkManageFocus.next(self) - end - - def TkManageFocus.prev(window) - tk_call 'tk_focusPrev', window - end - def focusPrev - TkManageFocus.prev(self) - end -end diff --git a/ext/tk/lib/tkpalette.rb b/ext/tk/lib/tkpalette.rb deleted file mode 100644 index a2dc7c87cb..0000000000 --- a/ext/tk/lib/tkpalette.rb +++ /dev/null @@ -1,48 +0,0 @@ -# -# tkpalette.rb : methods for Tcl/Tk standard library 'palette.tcl' -# 1998/06/21 by Hidetoshi Nagai -# -require 'tk' - -module TkPalette - include Tk - extend Tk - - def TkPalette.set(*args) - args = args.to_a.flatten if args.kind_of? Hash - tk_call 'tk_setPalette', *args - end - def TkPalette.setPalette(*args) - TkPalette.set(*args) - end - - def TkPalette.bisque - tk_call 'tk_bisque' - end - - def TkPalette.darken(color, percent) - tk_call 'tkDarken', color, percent - end - - def TkPalette.recolorTree(window, colors) - if not colors.kind_of?(Hash) - fail "2nd arg need to be Hash" - end - - colors.each{|key, value| - begin - if window.cget(key) == tk_call('set', "tkPalette(#{key})") - window[key] = colors[key] - end - rescue - # ignore - end - } - - TkWinfo.children(window).each{|w| TkPalette.recolorTree(w, colors)} - end - - def recolorTree(colors) - TkPalette.recolorTree(self, colors) - end -end diff --git a/ext/tk/lib/tkscrollbox.rb b/ext/tk/lib/tkscrollbox.rb deleted file mode 100644 index 6236430491..0000000000 --- a/ext/tk/lib/tkscrollbox.rb +++ /dev/null @@ -1,29 +0,0 @@ -# -# tkscrollbox.rb - Tk Listbox with Scrollbar -# as an example of Composite Widget -# $Date$ -# by Yukihiro Matsumoto - -require 'tk.rb' - -class TkScrollbox'left','fill'=>'both','expand'=>'yes' - scroll.configure 'command', list.path+" yview" - scroll.pack 'side'=>'right','fill'=>'y' - - delegate('DEFAULT', list) - delegate('foreground', list) - delegate('background', list, scroll) - delegate('borderwidth', @frame) - delegate('relief', @frame) - - configure keys if keys - end -end diff --git a/ext/tk/lib/tktext.rb b/ext/tk/lib/tktext.rb deleted file mode 100644 index 75b28d8477..0000000000 --- a/ext/tk/lib/tktext.rb +++ /dev/null @@ -1,1000 +0,0 @@ -# -# tktext.rb - Tk text classes -# $Date$ -# by Yukihiro Matsumoto - -require 'tk.rb' -require 'tkfont' - -module TkTreatTextTagFont - include TkTreatItemFont - - ItemCMD = ['tag', 'configure'] - def __conf_cmd(idx) - ItemCMD[idx] - end - - def __item_pathname(tagOrId) - if tagOrId.kind_of?(TkTextTag) - self.path + ';' + tagOrId.id - else - self.path + ';' + tagOrId - end - end -end - -class TkTextval}) - else - tk_send 'tag', 'configure', tag, "-#{key}", val - end - end - end - - def tag_configinfo(tag, key=nil) - if key - case key - when 'text', 'label', 'show', 'data', 'file' - conf = tk_split_simplelist(tk_send('tag','configure',tag,"-#{key}")) - else - conf = tk_split_list(tk_send('tag','configure',tag,"-#{key}")) - end - conf[0] = conf[0][1..-1] - conf - else - tk_split_simplelist(tk_send('tag', 'configure', tag)).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - case conf[0] - when 'text', 'label', 'show', 'data', 'file' - else - if conf[3] - if conf[3].index('{') - conf[3] = tk_split_list(conf[3]) - else - conf[3] = tk_tcl2ruby(conf[3]) - end - end - if conf[4] - if conf[4].index('{') - conf[4] = tk_split_list(conf[4]) - else - conf[4] = tk_tcl2ruby(conf[4]) - end - end - end - conf - } - end - end - - def tag_raise(tag, above=None) - tk_send 'tag', 'raise', tag, above - end - - def tag_lower(tag, below=None) - tk_send 'tag', 'lower', tag, below - end - - def tag_remove(tag, *index) - tk_send 'tag', 'remove', tag, *index - end - - def tag_ranges(tag) - l = tk_split_simplelist(tk_send('tag', 'ranges', tag)) - r = [] - while key=l.shift - r.push [key, l.shift] - end - r - end - - def tag_nextrange(tag, first, last=None) - tk_split_simplelist(tk_send('tag', 'nextrange', tag, first, last)) - end - - def tag_prevrange(tag, first, last=None) - tk_split_simplelist(tk_send('tag', 'prevrange', tag, first, last)) - end - - def _ktext_length(txt) - if $KCODE !~ /n/i - return txt.gsub(/[^\Wa-zA-Z_\d]/, ' ').length - end - - # $KCODE == 'NONE' - if JAPANIZED_TK - tk_call('kstring', 'length', txt).to_i - else - begin - tk_call('encoding', 'convertto', 'ascii', txt).length - rescue StandardError, NameError - # sorry, I have no plan - txt.length - end - end - end - private :_ktext_length - - def search_with_length(pat,start,stop=None) - pat = pat.chr if pat.kind_of? Integer - if stop != None - return ["", 0] if compare(start,'>=',stop) - txt = get(start,stop) - if (pos = txt.index(pat)) - match = $& - #pos = txt[0..(pos-1)].split('').length if pos > 0 - pos = _ktext_length(txt[0..(pos-1)]) if pos > 0 - if pat.kind_of? String - #return [index(start + " + #{pos} chars"), pat.split('').length] - return [index(start + " + #{pos} chars"), - _ktext_length(pat), pat.dup] - else - #return [index(start + " + #{pos} chars"), $&.split('').length] - return [index(start + " + #{pos} chars"), - _ktext_length(match), match] - end - else - return ["", 0] - end - else - txt = get(start,'end - 1 char') - if (pos = txt.index(pat)) - match = $& - #pos = txt[0..(pos-1)].split('').length if pos > 0 - pos = _ktext_length(txt[0..(pos-1)]) if pos > 0 - if pat.kind_of? String - #return [index(start + " + #{pos} chars"), pat.split('').length] - return [index(start + " + #{pos} chars"), - _ktext_length(pat), pat.dup] - else - #return [index(start + " + #{pos} chars"), $&.split('').length] - return [index(start + " + #{pos} chars"), - _ktext_length(match), match] - end - else - txt = get('1.0','end - 1 char') - if (pos = txt.index(pat)) - match = $& - #pos = txt[0..(pos-1)].split('').length if pos > 0 - pos = _ktext_length(txt[0..(pos-1)]) if pos > 0 - if pat.kind_of? String - #return [index("1.0 + #{pos} chars"), pat.split('').length] - return [index("1.0 + #{pos} chars"), - _ktext_length(pat), pat.dup] - else - #return [index("1.0 + #{pos} chars"), $&.split('').length] - return [index("1.0 + #{pos} chars"), _ktext_length(match), match] - end - else - return ["", 0] - end - end - end - end - - def search(pat,start,stop=None) - search_with_length(pat,start,stop)[0] - end - - def rsearch_with_length(pat,start,stop=None) - pat = pat.chr if pat.kind_of? Integer - if stop != None - return ["", 0] if compare(start,'<=',stop) - txt = get(stop,start) - if (pos = txt.rindex(pat)) - match = $& - #pos = txt[0..(pos-1)].split('').length if pos > 0 - pos = _ktext_length(txt[0..(pos-1)]) if pos > 0 - if pat.kind_of? String - #return [index(stop + " + #{pos} chars"), pat.split('').length] - return [index(stop + " + #{pos} chars"), _ktext_length(pat), pat.dup] - else - #return [index(stop + " + #{pos} chars"), $&.split('').length] - return [index(stop + " + #{pos} chars"), _ktext_length(match), match] - end - else - return ["", 0] - end - else - txt = get('1.0',start) - if (pos = txt.rindex(pat)) - match = $& - #pos = txt[0..(pos-1)].split('').length if pos > 0 - pos = _ktext_length(txt[0..(pos-1)]) if pos > 0 - if pat.kind_of? String - #return [index("1.0 + #{pos} chars"), pat.split('').length] - return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup] - else - #return [index("1.0 + #{pos} chars"), $&.split('').length] - return [index("1.0 + #{pos} chars"), _ktext_length(match), match] - end - else - txt = get('1.0','end - 1 char') - if (pos = txt.rindex(pat)) - match = $& - #pos = txt[0..(pos-1)].split('').length if pos > 0 - pos = _ktext_length(txt[0..(pos-1)]) if pos > 0 - if pat.kind_of? String - #return [index("1.0 + #{pos} chars"), pat.split('').length] - return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup] - else - #return [index("1.0 + #{pos} chars"), $&.split('').length] - return [index("1.0 + #{pos} chars"), _ktext_length(match), match] - end - else - return ["", 0] - end - end - end - end - - def rsearch(pat,start,stop=None) - rsearch_with_length(pat,start,stop)[0] - end - - def dump(type_info, *index, &block) - args = type_info.collect{|inf| '-' + inf} - args << '-command' << Proc.new(&block) if iterator? - str = tk_send('dump', *(args + index)) - result = [] - sel = nil - i = 0 - while i < str.size - # retrieve key - idx = str.index(/ /, i) - result.push str[i..(idx-1)] - i = idx + 1 - - # retrieve value - case result[-1] - when 'text' - if str[i] == ?{ - # text formed as {...} - val, i = _retrieve_braced_text(str, i) - result.push val - else - # text which may contain backslahes - val, i = _retrieve_backslashed_text(str, i) - result.push val - end - else - idx = str.index(/ /, i) - val = str[i..(idx-1)] - case result[-1] - when 'mark' - case val - when 'insert' - result.push TkTextMarkInsert.new(self) - when 'current' - result.push TkTextMarkCurrent.new(self) - when 'anchor' - result.push TkTextMarkAnchor.new(self) - else - result.push tk_tcl2ruby(val) - end - when 'tagon' - if val == 'sel' - if sel - result.push sel - else - result.push TkTextTagSel.new(self) - end - else - result.push tk_tcl2ruby(val) - end - when 'tagoff' - result.push tk_tcl2ruby(sel) - when 'window' - result.push tk_tcl2ruby(val) - end - i = idx + 1 - end - - # retrieve index - idx = str.index(/ /, i) - if idx - result.push str[i..(idx-1)] - i = idx + 1 - else - result.push str[i..-1] - break - end - end - - kvis = [] - until result.empty? - kvis.push [result.shift, result.shift, result.shift] - end - kvis # result is [[key1, value1, index1], [key2, value2, index2], ...] - end - - def _retrieve_braced_text(str, i) - cnt = 0 - idx = i - while idx < str.size - case str[idx] - when ?{ - cnt += 1 - when ?} - cnt -= 1 - if cnt == 0 - break - end - end - idx += 1 - end - return str[i+1..idx-1], idx + 2 - end - private :_retrieve_braced_text - - def _retrieve_backslashed_text(str, i) - j = i - idx = nil - loop { - idx = str.index(/ /, j) - if str[idx-1] == ?\\ - j += 1 - else - break - end - } - val = str[i..(idx-1)] - val.gsub!(/\\( |\{|\})/, '\1') - return val, idx + 1 - end - private :_retrieve_backslashed_text - - def dump_all(*index, &block) - dump(['all'], *index, &block) - end - def dump_mark(*index, &block) - dump(['mark'], *index, &block) - end - def dump_tag(*index, &block) - dump(['tag'], *index, &block) - end - def dump_text(*index, &block) - dump(['text'], *index, &block) - end - def dump_window(*index, &block) - dump(['window'], *index, &block) - end - def dump_image(*index, &block) - dump(['image'], *index, &block) - end -end - -class TkTextTag 0 - tk_call @t.path, 'window', 'configure', @index, *hash_kv(slot) - end - else - @id = value if slot == 'window' - if slot == 'create' - self.create=value - else - tk_call @t.path, 'window', 'configure', @index, "-#{slot}", value - end - end - end - - def window - @id - end - - def window=(value) - tk_call @t.path, 'window', 'configure', @index, '-window', value - @id = value - end - - def create - @p_create - end - - def create=(value) - @p_create = value - if @p_create.kind_of? Proc - value = install_cmd(proc{@id = @p_create.call}) - end - tk_call @t.path, 'window', 'configure', @index, '-create', value - end - - def configinfo(slot = nil) - if slot - case slot - when 'text', 'label', 'show', 'data', 'file' - conf = tk_split_simplelist(tk_call @t.path, 'window', 'configure', - @index, "-#{slot}") - else - conf = tk_split_list(tk_call @t.path, 'window', 'configure', - @index, "-#{slot}") - end - conf[0] = conf[0][1..-1] - conf - else - tk_split_simplelist(tk_call @t.path, 'window', 'configure', - @index).collect{|conflist| - conf = tk_split_simplelist(conflist) - conf[0] = conf[0][1..-1] - case conf[0] - when 'text', 'label', 'show', 'data', 'file' - else - if conf[3] - if conf[3].index('{') - conf[3] = tk_split_list(conf[3]) - else - conf[3] = tk_tcl2ruby(conf[3]) - end - end - if conf[4] - if conf[4].index('{') - conf[4] = tk_split_list(conf[4]) - else - conf[4] = tk_tcl2ruby(conf[4]) - end - end - end - conf - } - end - end - -end - -class TkTextImage -# -require 'tk' - -class TkVirtualEvent") - PreDefVirtEvent.new(event) - else - fail ArgumentError, "undefined virtual event '<#{event}>'" - end - end - end - - def TkVirtualEvent.info - tk_call('event', 'info').split(/\s+/).collect!{|seq| - TkVirtualEvent.getobj(seq[1..-2]) - } - end - - def initialize(*sequences) - @path = @id = format("", TkVirtualEventID[0]) - TkVirtualEventID[0] += 1 - add(*sequences) - end - - def add(*sequences) - if sequences != [] - tk_call('event', 'add', "<#{@id}>", - *(sequences.collect{|seq| "<#{tk_event_sequence(seq)}>"}) ) - TkVirtualEventTBL[@id] = self - end - self - end - - def delete(*sequences) - if sequences == [] - tk_call('event', 'delete', "<#{@id}>") - TkVirtualEventTBL[@id] = nil - else - tk_call('event', 'delete', "<#{@id}>", - *(sequences.collect{|seq| "<#{tk_event_sequence(seq)}>"}) ) - TkVirtualEventTBL[@id] = nil if info == [] - end - self - end - - def info - tk_call('event', 'info', "<#{@id}>").split(/\s+/).collect!{|seq| - l = seq.scan(/<*[^<>]+>*/).collect!{|subseq| - case (subseq) - when /^<<[^<>]+>>$/ - TkVirtualEvent.getobj(subseq[1..-2]) - when /^<[^<>]+>$/ - subseq[1..-2] - else - subseq.split('') - end - }.flatten - (l.size == 1) ? l[0] : l - } - end -end diff --git a/ext/tk/sample/tkbiff.rb b/ext/tk/sample/tkbiff.rb deleted file mode 100644 index ac27184437..0000000000 --- a/ext/tk/sample/tkbiff.rb +++ /dev/null @@ -1,149 +0,0 @@ -#! /usr/local/bin/ruby - -if ARGV[0] != '-d' - unless $DEBUG - exit if fork - end -else - ARGV.shift -end - -if ARGV.length == 0 - if ENV['MAIL'] - $spool = ENV['MAIL'] - else - $spool = '/usr/spool/mail/' + ENV['USER'] - end -else - $spool = ARGV[0] -end - -require "parsedate" -require "base64" - -include ParseDate - -class Mail - def Mail.new(f) - if !f.kind_of?(IO) - f = open(f, "r") - me = super - f.close - else - me = super - end - return me - end - - def initialize(f) - @header = {} - @body = [] - while line = f.gets() - line.chop! - next if /^From / =~ line # skip From-line - break if /^$/ =~ line # end of header - if /^(\S+):\s*(.*)/ =~ line - @header[attr = $1.capitalize] = $2 - elsif attr - sub(/^\s*/, '') - @header[attr] += "\n" + $_ - end - end - - return unless $_ - - while line = f.gets() - break if /^From / =~ line - @body.push($_) - end - end - - def header - return @header - end - - def body - return @body - end - -end - -require "tkscrollbox" - -$top = TkRoot.new -$top.withdraw -$list = TkScrollbox.new($top) { - relief 'raised' - width 80 - height 8 - setgrid 'yes' - pack -} -TkButton.new($top) { - text 'Dismiss' - command proc {$top.withdraw} - pack('fill'=>'both','expand'=>'yes') -} -$top.bind "Control-c", proc{exit} -$top.bind "Control-q", proc{exit} -$top.bind "space", proc{exit} - -$spool_size = 0 -$check_time = Time.now - -def check - $check_time = Time.now - size = File.size($spool) - if size and size != $spool_size - $spool_size = size - pop_up if size > 0 - end - Tk.after 5000, proc{check} -end - -if defined? Thread - Thread.start do - loop do - sleep 600 - if Time.now - $check_time > 200 - Tk.after 5000, proc{check} - end - end - end -end - -def pop_up - outcount = 0; - $list.delete 0, 'end' - f = open($spool, "r") - while !f.eof? - mail = Mail.new(f) - date, from, subj = mail.header['Date'], mail.header['From'], mail.header['Subject'] - next if !date - y = m = d = 0 - y, m, d = parsedate(date) if date - from = "sombody@somewhere" if ! from - subj = "(nil)" if ! subj - from = decode_b(from) - subj = decode_b(subj) - $list.insert 'end', format('%-02d/%02d/%02d [%-28.28s] %s',y,m,d,from,subj) - outcount += 1 - end - f.close - if outcount == 0 - $list.insert 'end', "You have no mail." - else - $list.see 'end' - end - $top.deiconify - Tk.after 2000, proc{$top.withdraw} -end - -$list.insert 'end', "You have no mail." -check -Tk.after 2000, proc{$top.withdraw} -begin - Tk.mainloop -rescue - `echo #$! > /tmp/tkbiff` -end diff --git a/ext/tk/sample/tkbrowse.rb b/ext/tk/sample/tkbrowse.rb deleted file mode 100644 index 882f0a489b..0000000000 --- a/ext/tk/sample/tkbrowse.rb +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/local/bin/ruby -# -# This script generates a directory browser, which lists the working -# directory and allows you to open files or subdirectories by -# double-clicking. - -# Create a scrollbar on the right side of the main window and a listbox -# on the left side. - -require "tkscrollbox" - -# The procedure below is invoked to open a browser on a given file; if the -# file is a directory then another instance of this program is invoked; if -# the file is a regular file then the Mx editor is invoked to display -# the file. - -$dirlist = {} - -def browsedir (dir) - if $dirlist.key? dir - $dirlist[dir] - else - top = if $dirlist.size > 0 then TkToplevel.new else nil end - list = TkScrollbox.new(top) { - relief 'raised' - width 20 - height 20 - setgrid 'yes' - pack - } - list.insert 'end', *`ls #{dir}`.split - - # Set up bindings for the browser. - - list.focus - list.bind "Control-q", proc{exit} - list.bind "Control-c", proc{exit} - list.bind "Control-p", proc{ - print "selection <", TkSelection.get, ">\n" - } - - list.bind "Double-Button-1", proc{ - for i in TkSelection.get.split - print "clicked ", i, "\n" - browse dir, i - end - } - $dirlist[dir] = list - end -end - -def browse (dir, file) - file="#{dir}/#{file}" - if File.directory? file - browsedir(file) - else - if File.file? file - if ENV['EDITOR'] - system format("%s %s&", ENV['EDITOR'], file) - else - system "xedit #{file}&" - end - else - STDERR.print "\"#{file}\" isn't a directory or regular file" - end - end -end - -# Fill the listbox with a list of all the files in the directory (run -# the "ls" command to get that information). - -if ARGV.length>0 - dir = ARGV[0] -else - dir="." -end - -browsedir(dir) -Tk.mainloop diff --git a/ext/tk/sample/tkdialog.rb b/ext/tk/sample/tkdialog.rb deleted file mode 100644 index e83e16d0a8..0000000000 --- a/ext/tk/sample/tkdialog.rb +++ /dev/null @@ -1,62 +0,0 @@ -#! /usr/local/bin/ruby -require "tk" - -root = TkFrame.new -top = TkFrame.new(root) { - relief 'raised' - border 1 -} -msg = TkMessage.new(top) { - text "File main.c hasn't been saved to disk since \ -it was last modified. What should I do?" - justify 'center' - aspect 200 - font '-Adobe-helvetica-medium-r-normal--*-240*' - pack('padx'=>5, 'pady'=>5, 'expand'=>'yes') -} -top.pack('fill'=>'both') -root.pack - -bot = TkFrame.new(root) { - relief 'raised' - border 1 -} - -TkFrame.new(bot) { |left| - relief 'sunken' - border 1 - pack('side'=>'left', 'expand'=>'yes', 'padx'=>10, 'pady'=> 10) - TkButton.new(left) { - text "Save File" - command "quit 'save'" - pack('expand'=>'yes','padx'=>6,'pady'=> 6) - top.bind "Enter", proc{state 'active'} - msg.bind "Enter", proc{state 'active'} - bot.bind "Enter", proc{state 'active'} - top.bind "Leave", proc{state 'normal'} - msg.bind "Leave", proc{state 'normal'} - bot.bind "Leave", proc{state 'normal'} - Tk.root.bind "ButtonRelease-1", proc{quit 'save'} - Tk.root.bind "Return", proc{quit 'save'} - } -} -TkButton.new(bot) { - text "Quit Anyway" - command "quit 'quit'" - pack('side'=>'left', 'expand'=>'yes', 'padx'=>10) -} -TkButton.new(bot) { - text "Return To Editor" - command "quit 'return'" - pack('side'=>'left', 'expand'=>'yes', 'padx'=>10) -} -bot.pack -root.pack('side'=>'top', 'fill'=>'both', 'expand'=>'yes') - -def quit(button) - print "aaa\n" - print "You pressed the \"#{button}\" button; bye-bye!\n" - exit -end - -Tk.mainloop diff --git a/ext/tk/sample/tkfrom.rb b/ext/tk/sample/tkfrom.rb deleted file mode 100644 index 8c3efb8137..0000000000 --- a/ext/tk/sample/tkfrom.rb +++ /dev/null @@ -1,132 +0,0 @@ -#! /usr/local/bin/ruby - -require "parsedate" -require "base64" - -include ParseDate - -class Mail - def Mail.new(f) - if !f.kind_of?(IO) - f = open(f, "r") - me = super(f) - f.close - else - me = super - end - return me - end - - def initialize(f) - @header = {} - @body = [] - while line = f.gets() - $_.chop! - next if /^From / =~ line # skip From-line - break if /^$/ =~ line # end of header - if /^(\S+):\s*(.*)/ =~ line - @header[attr = $1.capitalize] = $2 - elsif attr - sub(/^\s*/, '') - @header[attr] += "\n" + $_ - end - end - - return unless $_ - - while line = f.gets() - break if /^From / =~ line - @body.push($_) - end - end - - def header - return @header - end - - def body - return @body - end - -end - -if ARGV.length == 0 - if ENV['MAIL'] - ARGV[0] = ENV['MAIL'] - elsif ENV['USER'] - ARGV[0] = '/usr/spool/mail/' + ENV['USER'] - elsif ENV['LOGNAME'] - ARGV[0] = '/usr/spool/mail/' + ENV['LOGNAME'] - end -end - -require "tk" -list = scroll = nil -TkFrame.new{|f| - list = TkListbox.new(f) { - yscroll proc{|idx| - scroll.set *idx - } - relief 'raised' -# geometry "80x5" - width 80 - height 5 - setgrid 'yes' - pack('side'=>'left','fill'=>'both','expand'=>'yes') - } - scroll = TkScrollbar.new(f) { - command proc{|idx| - list.yview *idx - } - pack('side'=>'right','fill'=>'y') - } - pack -} -root = Tk.root -TkButton.new(root) { - text 'Dismiss' - command proc {exit} - pack('fill'=>'both','expand'=>'yes') -} -root.bind "Control-c", proc{exit} -root.bind "Control-q", proc{exit} -root.bind "space", proc{exit} - -$outcount = 0; -for file in ARGV - next if File.exist?(file) - atime = File.atime(file) - mtime = File.mtime(file) - f = open(file, "r") - begin - until f.eof - mail = Mail.new(f) - date = mail.header['Date'] - next unless date - from = mail.header['From'] - subj = mail.header['Subject'] - y = m = d = 0 - y, m, d = parsedate(date) if date - from = "sombody@somewhere" unless from - subj = "(nil)" unless subj - from = decode_b(from) - subj = decode_b(subj) - list.insert 'end', format('%-02d/%02d/%02d [%-28.28s] %s',y,m,d,from,subj) - $outcount += 1 - end - ensure - f.close - File.utime(atime, mtime, file) - list.see 'end' - end -end - -limit = 10000 -if $outcount == 0 - list.insert 'end', "You have no mail." - limit = 2000 -end -Tk.after limit, proc{ - exit -} -Tk.mainloop diff --git a/ext/tk/sample/tkhello.rb b/ext/tk/sample/tkhello.rb deleted file mode 100644 index 5188fe1c8c..0000000000 --- a/ext/tk/sample/tkhello.rb +++ /dev/null @@ -1,10 +0,0 @@ -require "tk" - -TkButton.new(nil, - 'text' => 'hello', - 'command' => proc{print "hello\n"}).pack('fill'=>'x') -TkButton.new(nil, - 'text' => 'quit', - 'command' => 'exit').pack('fill'=>'x') - -Tk.mainloop diff --git a/ext/tk/sample/tkline.rb b/ext/tk/sample/tkline.rb deleted file mode 100644 index 2406b0749f..0000000000 --- a/ext/tk/sample/tkline.rb +++ /dev/null @@ -1,45 +0,0 @@ - -require "tkclass" - -$tkline_init = FALSE -def start_random - return if $tkline_init - $tkline_init = TRUE - if defined? Thread - Thread.start do - loop do - sleep 2 - Line.new($c, rand(400), rand(200), rand(400), rand(200)) - end - end - end -end - -$c = Canvas.new -$c.pack -$start_x = start_y = 0 - -def do_press(x, y) - $start_x = x - $start_y = y - $current_line = Line.new($c, x, y, x, y) - start_random -end -def do_motion(x, y) - if $current_line - $current_line.coords $start_x, $start_y, x, y - end -end - -def do_release(x, y) - if $current_line - $current_line.coords $start_x, $start_y, x, y - $current_line.fill 'black' - $current_line = nil - end -end - -$c.bind("1", proc{|e| do_press e.x, e.y}) -$c.bind("B1-Motion", proc{|x, y| do_motion x, y}, "%x %y") -$c.bind("ButtonRelease-1", proc{|x, y| do_release x, y}, "%x %y") -Tk.mainloop diff --git a/ext/tk/sample/tktimer.rb b/ext/tk/sample/tktimer.rb deleted file mode 100644 index 34377e2f39..0000000000 --- a/ext/tk/sample/tktimer.rb +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/local/bin/ruby -# This script generates a counter with start and stop buttons. - -require "tk" -$label = TkLabel.new { - text '0.00' - relief 'raised' - width 10 - pack('side'=>'bottom', 'fill'=>'both') -} - -TkButton.new { - text 'Start' - command proc { - if $stopped - $stopped = FALSE - tick - end - } - pack('side'=>'left','fill'=>'both','expand'=>'yes') -} -TkButton.new { - text 'Stop' - command proc{ - exit if $stopped - $stopped = TRUE - } - pack('side'=>'right','fill'=>'both','expand'=>'yes') -} - -$seconds=0 -$hundredths=0 -$stopped=TRUE - -def tick - if $stopped then return end - Tk.after 50, proc{tick} - $hundredths+=5 - if $hundredths >= 100 - $hundredths=0 - $seconds+=1 - end - $label.text format("%d.%02d", $seconds, $hundredths) -end - -root = Tk.root -root.bind "Control-c", proc{root.destroy} -root.bind "Control-q", proc{root.destroy} -Tk.root.focus -Tk.mainloop diff --git a/ext/tk/tkutil.c b/ext/tk/tkutil.c deleted file mode 100644 index b42069e234..0000000000 --- a/ext/tk/tkutil.c +++ /dev/null @@ -1,45 +0,0 @@ -/************************************************ - - tk.c - - - $Author$ - $Date$ - created at: Fri Nov 3 00:47:54 JST 1995 - -************************************************/ - -#include "ruby.h" - -static VALUE -tk_eval_cmd(argc, argv) - int argc; - VALUE argv[]; -{ - VALUE cmd, rest; - - rb_scan_args(argc, argv, "1*", &cmd, &rest); - return rb_eval_cmd(cmd, rest, 0); -} - -static VALUE -tk_s_new(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE obj = rb_class_new_instance(argc, argv, klass); - - if (rb_block_given_p()) rb_obj_instance_eval(0, 0, obj); - return obj; -} - -void -Init_tkutil() -{ - VALUE mTK = rb_define_module("TkUtil"); - VALUE cTK = rb_define_class("TkKernel", rb_cObject); - - rb_define_singleton_method(mTK, "eval_cmd", tk_eval_cmd, -1); - - rb_define_singleton_method(cTK, "new", tk_s_new, -1); -} -- cgit v1.2.3