/* 
   This file is part of libodbc++.
   
   Copyright (C) 1999 Manush Dodunekov <manush@litecom.net>
   
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.
   
   This library 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
   Library General Public License for more details.
   
   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

#ifndef __DTCONV_H
#define __DTCONV_H

#include <odbc++/types.h>

using namespace std;

#include <cstdio>
#include <cstdlib>

/* conversion functions string <-> int/float/double/long double 
 */

// This is a pure mess, but seems to function (tm).

namespace odbc {
  
  const int INT_STR_LEN=12; //10 digits, sign, null
  const int LONG_STR_LEN=22; //20 digits, sign, null
  const int DOUBLE_STR_LEN=80; //???
    

  inline std::string intToString(int i) {
    char buf[INT_STR_LEN];
#if defined(WIN32) && defined(ODBCXX_HAVE__ITOA)
    _itoa(i,buf,10);
#else
    snprintf(buf,INT_STR_LEN,"%d",i);
#endif
    return std::string(buf);
  }
  
  inline int stringToInt(const std::string& s) {
    return (int)strtol(s.c_str(),NULL,10);
  }
  
  inline std::string longToString(Long l) {
    char buf[LONG_STR_LEN];
#if defined(WIN32) && defined(ODBCXX_HAVE__I64TOA)
    _i64toa(l,buf,10);
#else
    snprintf(buf,LONG_STR_LEN,
# if defined(PRId64)
	     "%" PRId64
# elif ODBCXX_SIZEOF_LONG==8
	     "%ld"
# else
	     "%lld"
# endif
	     ,l);
#endif // _i64toa
    return std::string(buf);
  }

  inline odbc::Long stringToLong(const std::string& s) {
#if defined(WIN32) && defined(ODBCXX_HAVE__ATOI64)
    return (Long)_atoi64(s.c_str());
#elif ODBCXX_SIZEOF_LONG==4 && defined(ODBCXX_HAVE_STRTOLL)
    return (Long)strtoll(s.c_str(),NULL,10);
#elif ODBCXX_SIZEOF_LONG==4 && defined(ODBCXX_HAVE_STRTOQ)
    return (Long)strtoq(s.c_str(),NULL,10);
#else
    // either 64bit platform, or I'm stupid.
    return (Long)strtol(s.c_str(),NULL,10);
#endif
  }

  inline std::string doubleToString(double d) {
    char buf[DOUBLE_STR_LEN];
#if defined(ODBCXX_HAVE_SNPRINTF)
    snprintf(buf,DOUBLE_STR_LEN,"%f",d);
#elif defined(ODBCXX_HAVE__SNPRINTF)
    _snprintf(buf,DOUBLE_STR_LEN,"%f",d);
#else
    sprintf(buf,"%f",d);
#endif
    return std::string(buf);
  }
  
  inline double stringToDouble(const std::string& s) {
    return strtod(s.c_str(),NULL);
  }
  
};


#endif
