#include "fs.h"
#include "fsutil.h"

// utility to turn a file handle into a str with the same bits.
str
fsutil::fh2s(nfs_fh3 fh)
{
  return str(fh.data.base(), fh.data.size());
}

// utility to turn a str into a file handle with the same bits.
nfs_fh3
fsutil::s2fh(str s)
{
  nfs_fh3 fh;
  fh.data.setsize(s.len());
  bcopy(s.cstr(), fh.data.base(), s.len());
  return fh;
}
str
fsutil::fh2hex(nfs_fh3 fh)
{
  char buf[64];
  unsigned int len = fh.data.size();
  char *p = fh.data.base();
  unsigned int i;

  buf[0] = '\0';
  for(i = 0; i < len && i*2+1 < sizeof(buf); i++){
    sprintf(buf + (i * 2), "%02x", p[i] & 0xff);
  }
  
  return str(buf);
}

nfs_fh3
fsutil::hex2fh(str s)
{
  nfs_fh3 fh;
  fh.data.setsize(s.len() / 2);
  char *p = fh.data.base();
  unsigned int i;

  for(i = 0; i*2 < s.len(); i++){
    int x;
    sscanf(s.cstr() + (i*2), "%2x", &x);
    p[i] = x;
  }
  
  return fh;
}

// return the current time in NFS format
nfstime3
fsutil::nfstime()
{
  struct timeval tv;
  gettimeofday(&tv, (struct timezone *) 0);
  nfstime3 t;
  t.seconds = tv.tv_sec;
  t.nseconds = tv.tv_usec * 1000;
  return t;
}
