1
0

Base10.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 <http://www.gnu.org/licenses/>.
  14. */
  15. #include "util/Base10.h"
  16. #include "wire/Message.h"
  17. #include "exception/Except.h"
  18. #include <stdbool.h>
  19. void Base10_write(struct Message* msg, int64_t num, struct Except* eh)
  20. {
  21. bool negative = num < 0;
  22. if (negative) {
  23. num = -num;
  24. } else if (num == 0) {
  25. Message_push8(msg, '0', eh);
  26. return;
  27. }
  28. while (num > 0) {
  29. Message_push8(msg, '0' + (num % 10), eh);
  30. num /= 10;
  31. }
  32. if (negative) {
  33. Message_push8(msg, '-', eh);
  34. }
  35. }
  36. int64_t Base10_read(struct Message* msg, struct Except* eh)
  37. {
  38. int64_t out = 0;
  39. bool negative = false;
  40. uint8_t chr = Message_pop8(msg, eh);
  41. if (chr == '-') {
  42. negative = true;
  43. chr = Message_pop8(msg, eh);
  44. }
  45. if (chr >= '0' && chr <= '9') {
  46. while (chr >= '0' && chr <= '9') {
  47. out *= 10;
  48. out += chr - '0';
  49. if (msg->length == 0) {
  50. if (negative) { out = -out; }
  51. return out;
  52. }
  53. chr = Message_pop8(msg, eh);
  54. }
  55. Message_push8(msg, chr, eh);
  56. if (negative) { out = -out; }
  57. return out;
  58. } else {
  59. Message_push8(msg, chr, eh);
  60. Except_throw(eh, "No base10 characters found");
  61. }
  62. }