1
0

Base10.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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/Except.h"
  18. #include "util/CString.h"
  19. #include <stdbool.h>
  20. void Base10_write(struct Message* msg, int64_t num, struct Except* eh)
  21. {
  22. bool negative = num < 0;
  23. if (negative) {
  24. num = -num;
  25. } else if (num == 0) {
  26. Message_push8(msg, '0', eh);
  27. return;
  28. }
  29. while (num > 0) {
  30. Message_push8(msg, '0' + (num % 10), eh);
  31. num /= 10;
  32. }
  33. if (negative) {
  34. Message_push8(msg, '-', eh);
  35. }
  36. }
  37. int64_t Base10_read(struct Message* msg, struct Except* eh)
  38. {
  39. int64_t out = 0;
  40. bool negative = false;
  41. uint8_t chr = Message_pop8(msg, eh);
  42. if (chr == '-') {
  43. negative = true;
  44. chr = Message_pop8(msg, eh);
  45. }
  46. if (chr >= '0' && chr <= '9') {
  47. while (chr >= '0' && chr <= '9') {
  48. out *= 10;
  49. out += chr - '0';
  50. if (msg->length == 0) {
  51. if (negative) { out = -out; }
  52. return out;
  53. }
  54. chr = Message_pop8(msg, eh);
  55. }
  56. Message_push8(msg, chr, eh);
  57. if (negative) { out = -out; }
  58. return out;
  59. } else {
  60. Message_push8(msg, chr, eh);
  61. Except_throw(eh, "No base10 characters found");
  62. }
  63. }
  64. int Base10_fromString(uint8_t* str, int64_t* numOut)
  65. {
  66. int len = CString_strlen(str);
  67. if (len < 1) {
  68. return -1;
  69. } else if (str[0] == '-') {
  70. if (len < 2 || str[1] < '0' || str[1] > '9') {
  71. return -1;
  72. }
  73. } else if (str[0] < '0' || str[0] > '9') {
  74. return -1;
  75. }
  76. struct Message msg = { .length = len, .bytes = str, .capacity = len };
  77. *numOut = Base10_read(&msg, NULL);
  78. return 0;
  79. }