00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 #include "db_config.h"
00011
00012 #ifndef NO_SYSTEM_INCLUDES
00013 #include <sys/types.h>
00014
00015 #include <fcntl.h>
00016 #include <stdlib.h>
00017 #include <string.h>
00018 #include <tcl.h>
00019 #endif
00020
00021 #include "db_int.h"
00022 #include "dbinc/tcl_db.h"
00023
00024
00025
00026
00027
00028
00029
00030 int
00031 bdb_RandCommand(interp, objc, objv)
00032 Tcl_Interp *interp;
00033 int objc;
00034 Tcl_Obj *CONST objv[];
00035 {
00036 static const char *rcmds[] = {
00037 "rand", "random_int", "srand",
00038 NULL
00039 };
00040 enum rcmds {
00041 RRAND, RRAND_INT, RSRAND
00042 };
00043 Tcl_Obj *res;
00044 int cmdindex, hi, lo, result, ret;
00045
00046 result = TCL_OK;
00047
00048
00049
00050
00051
00052 if (Tcl_GetIndexFromObj(interp,
00053 objv[1], rcmds, "command", TCL_EXACT, &cmdindex) != TCL_OK)
00054 return (IS_HELP(objv[1]));
00055
00056 res = NULL;
00057 switch ((enum rcmds)cmdindex) {
00058 case RRAND:
00059
00060
00061
00062 if (objc != 2) {
00063 Tcl_WrongNumArgs(interp, 2, objv, NULL);
00064 return (TCL_ERROR);
00065 }
00066 ret = rand();
00067 res = Tcl_NewIntObj(ret);
00068 break;
00069 case RRAND_INT:
00070
00071
00072
00073 if (objc != 4) {
00074 Tcl_WrongNumArgs(interp, 2, objv, "lo hi");
00075 return (TCL_ERROR);
00076 }
00077 if ((result =
00078 Tcl_GetIntFromObj(interp, objv[2], &lo)) != TCL_OK)
00079 return (result);
00080 if ((result =
00081 Tcl_GetIntFromObj(interp, objv[3], &hi)) != TCL_OK)
00082 return (result);
00083 if (lo < 0 || hi < 0) {
00084 Tcl_SetResult(interp,
00085 "Range value less than 0", TCL_STATIC);
00086 return (TCL_ERROR);
00087 }
00088
00089 _debug_check();
00090 ret = lo + rand() % ((hi - lo) + 1);
00091 res = Tcl_NewIntObj(ret);
00092 break;
00093 case RSRAND:
00094
00095
00096
00097 if (objc != 3) {
00098 Tcl_WrongNumArgs(interp, 2, objv, "seed");
00099 return (TCL_ERROR);
00100 }
00101 if ((result =
00102 Tcl_GetIntFromObj(interp, objv[2], &lo)) == TCL_OK) {
00103 srand((u_int)lo);
00104 res = Tcl_NewIntObj(0);
00105 }
00106 break;
00107 }
00108
00109
00110
00111
00112
00113 if (result == TCL_OK && res)
00114 Tcl_SetObjResult(interp, res);
00115 return (result);
00116 }