util.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (C) 2011 Anders Sundman <anders@4zm.org>
  3. *
  4. * This file is part of mfterm.
  5. *
  6. * mfterm is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * mfterm is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with mfterm. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. * Parts of code used in this file are from the GNU readline library file
  20. * fileman.c (GPLv3). Copyright (C) 1987-2009 Free Software Foundation, Inc
  21. */
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <stdio.h>
  25. #include "util.h"
  26. char* strdup(const char* string) {
  27. if (string == NULL)
  28. return NULL;
  29. // Allocate memory for the string + '\0'
  30. char* new_string = malloc(strlen(string) + 1);
  31. if(new_string)
  32. strcpy(new_string, string);
  33. return new_string;
  34. }
  35. int is_space(char c) {
  36. return c == ' ' || c == '\t';
  37. }
  38. /* Strip whitespace from the start and end of STRING. Return a pointer
  39. into STRING. */
  40. char* trim(char* string) {
  41. char* s = string;
  42. while (is_space(*s))
  43. ++s;
  44. if (*s == 0)
  45. return s;
  46. char* t = s + strlen(s) - 1;
  47. while (t > s && is_space(*t))
  48. --t;
  49. *++t = '\0';
  50. return s;
  51. }
  52. void print_hex_array(const unsigned char* data, size_t nbytes) {
  53. print_hex_array_sep(data, nbytes, NULL);
  54. }
  55. void print_hex_array_sep(const unsigned char* data, size_t nbytes, char* sep) {
  56. for (int i = 0; i < nbytes; ++i) {
  57. printf("%02x", data[i]);
  58. if (sep)
  59. printf("%s", sep);
  60. }
  61. }