/* This file is part of cardwords
   (c) 1999 Tobias Peters
   see file COPYING for the copyright terms.
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// cardwords_fixlennum.hh

// this file defines functions for converting numbers into a string of a
// fixed length with leading 0's and back:

// **** CHANGE: ****  Now works with signed ints!

#ifndef CARDWORDS_FIXLENNUM_HH
#define CARDWORDS_FIXLENNUM_HH

// these functions return 0 on success and -1 on failure:

inline
int size2str (size_t size, Machine_Char * str,
              size_t strlen, bool add_endstring = false)
{
  assert (str != 0);
  if (add_endstring == true) {
    str[strlen] = (Machine_Char) '\0';
  }
  size_t pos;
  for (pos = strlen - 1; pos < strlen; (--pos),(size/=10)) {
    str[pos] = (Machine_Char)(size%10) + (Machine_Char)'0';
  }
  if (size == 0) {
    return 0;
  }
  return -1;
}

inline
int str2size(const Machine_Char * str, size_t * size, size_t strlen)
{
  assert (str != 0);
  assert (size != 0);
  size_t pos;
  *size = 0;
  for (pos = 0; pos < strlen; (++pos)) {
    *size *= 10;
    if (str[pos] < (Machine_Char)'0' || str[pos] > (Machine_Char)'9') {
      return -1;
    }
    *size += str[pos] - (Machine_Char)'0';
  }
  return 0;
}

#endif

