Base10.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "util/Base10.h"
  16. #include "wire/Message.h"
  17. #include "exception/Err.h"
  18. #include "util/CString.h"
  19. #include "rust/cjdns_sys/Rffi.h"
  20. #include <stdbool.h>
  21. Err_DEFUN Base10_write(Message_t* msg, int64_t num)
  22. {
  23. bool negative = num < 0;
  24. if (negative) {
  25. num = -num;
  26. } else if (num == 0) {
  27. Err(Message_epush8(msg, '0'));
  28. return NULL;
  29. }
  30. while (num > 0) {
  31. Err(Message_epush8(msg, '0' + (num % 10)));
  32. num /= 10;
  33. }
  34. if (negative) {
  35. Err(Message_epush8(msg, '-'));
  36. }
  37. return NULL;
  38. }
  39. Err_DEFUN Base10_read(int64_t* outP, Message_t* msg)
  40. {
  41. int64_t numOut = 0;
  42. uint32_t bytes = 0;
  43. int out = Rffi_parseBase10(
  44. Message_bytes(msg), Message_getLength(msg), &numOut, &bytes);
  45. if (out != 0) {
  46. Err_raise(Message_getAlloc(msg), "Error reading base10: %d", out);
  47. }
  48. Err(Message_eshift(msg, -bytes));
  49. *outP = numOut;
  50. return NULL;
  51. }
  52. int Base10_fromString(uint8_t* str, int64_t* numOut)
  53. {
  54. int len = CString_strlen((char*)str);
  55. if (len < 1) {
  56. return -1;
  57. }
  58. uint32_t bytes = 0;
  59. return Rffi_parseBase10(str, len, numOut, &bytes);
  60. }