chiark / gitweb /
ulong improved; clock arithmetic hbytes abolished; secnet responder implemented and...
[chiark-tcl.git] / hbytes / hook.c
index cdcb246d2c742b945ad8444faad1cd1705529b01..61593aba5a1bd5abb6a40c7040308772a2ce9978 100644 (file)
@@ -134,25 +134,35 @@ static int hbytes_t_sfa(Tcl_Interp *ip, Tcl_Obj *o) {
   int l;
   char cbuf[3];
 
-  os= str= Tcl_GetStringFromObj(o,&l);  assert(str);
-  objfreeir(o);
+  if (o->typePtr == &ulong_type) {
+    uint32_t ul;
 
-  if (l & 1) return staticerr(ip, "hbytes: conversion from hex:"
-                             " odd length in hex");
+    ul= htonl(*(const uint32_t*)&o->internalRep.longValue);
+    hbytes_array(OBJ_HBYTES(o), (const Byte*)&ul, 4);
 
-  startbytes= bytes= hbytes_arrayspace(OBJ_HBYTES(o), l/2);
-
-  cbuf[2]= 0;
-  while (l>0) {
-    cbuf[0]= *str++;
-    cbuf[1]= *str++;
-    *bytes++= strtoul(cbuf,&ep,16);
-    if (ep != cbuf+2) {
-      hbytes_free(OBJ_HBYTES(o));
-      return staticerr(ip, "hbytes: conversion from hex:"
-                      " bad hex digit");
+  } else {
+  
+    os= str= Tcl_GetStringFromObj(o,&l);  assert(str);
+    objfreeir(o);
+
+    if (l & 1) return staticerr(ip, "hbytes: conversion from hex:"
+                               " odd length in hex");
+
+    startbytes= bytes= hbytes_arrayspace(OBJ_HBYTES(o), l/2);
+
+    cbuf[2]= 0;
+    while (l>0) {
+      cbuf[0]= *str++;
+      cbuf[1]= *str++;
+      *bytes++= strtoul(cbuf,&ep,16);
+      if (ep != cbuf+2) {
+       hbytes_free(OBJ_HBYTES(o));
+       return staticerr(ip, "hbytes: conversion from hex:"
+                        " bad hex digit");
+      }
+      l -= 2;
     }
-    l -= 2;
+
   }
 
   o->typePtr = &hbytes_type;
@@ -283,7 +293,37 @@ int do_hbytes_range(ClientData cd, Tcl_Interp *ip,
   hbytes_array(result, data+start, size);
   return TCL_OK;
 }
-  
+
+/* hbytes representing uint16_t's */
+
+int do_hbytes_h2ushort(ClientData cd, Tcl_Interp *ip,
+                      HBytes_Value hex, long *result) {
+  const Byte *data;
+  int l;
+
+  l= hbytes_len(&hex);
+  if (l>2)
+    return staticerr(ip, "hbytes h2ushort input more than 4 hex digits");
+
+  data= hbytes_data(&hex);
+  *result= data[l-1] | (l>1 ? data[0]<<8 : 0);
+  return TCL_OK;
+}
+
+int do_hbytes_ushort2h(ClientData cd, Tcl_Interp *ip,
+                      long input, HBytes_Value *result) {
+  uint16_t us;
+
+  if (input > 0x0ffff)
+    return staticerr(ip, "hbytes ushort2h input >2^16");
+
+  us= htons(input);
+  hbytes_array(result,(const Byte*)&us,2);
+  return TCL_OK;
+}
+
+/* toplevel functions */
+
 int do_toplevel_hbytes(ClientData cd, Tcl_Interp *ip,
                       const HBytes_SubCommand *subcmd,
                       int objc, Tcl_Obj *const *objv) {