CommonJS.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum 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. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file CommonJS.cpp
  15. * @authors:
  16. * Gav Wood <i@gavwood.com>
  17. * Marek Kotewicz <marek@ethdev.com>
  18. * @date 2014
  19. */
  20. #include "CommonJS.h"
  21. using namespace std;
  22. namespace dev
  23. {
  24. bytes jsToBytes(string const& _s, OnFailed _f)
  25. {
  26. try
  27. {
  28. return fromHex(_s, WhenError::Throw);
  29. }
  30. catch (...)
  31. {
  32. if (_f == OnFailed::InterpretRaw)
  33. return asBytes(_s);
  34. else if (_f == OnFailed::Throw)
  35. throw invalid_argument("Cannot intepret '" + _s + "' as bytes; must be 0x-prefixed hex or decimal.");
  36. }
  37. return bytes();
  38. }
  39. bytes padded(bytes _b, unsigned _l)
  40. {
  41. while (_b.size() < _l)
  42. _b.insert(_b.begin(), 0);
  43. return asBytes(asString(_b).substr(_b.size() - max(_l, _l)));
  44. }
  45. bytes paddedRight(bytes _b, unsigned _l)
  46. {
  47. _b.resize(_l);
  48. return _b;
  49. }
  50. bytes unpadded(bytes _b)
  51. {
  52. auto p = asString(_b).find_last_not_of((char)0);
  53. _b.resize(p == string::npos ? 0 : (p + 1));
  54. return _b;
  55. }
  56. bytes unpadLeft(bytes _b)
  57. {
  58. unsigned int i = 0;
  59. if (_b.size() == 0)
  60. return _b;
  61. while (i < _b.size() && _b[i] == byte(0))
  62. i++;
  63. if (i != 0)
  64. _b.erase(_b.begin(), _b.begin() + i);
  65. return _b;
  66. }
  67. string fromRaw(h256 _n)
  68. {
  69. if (_n)
  70. {
  71. string s((char const*)_n.data(), 32);
  72. auto l = s.find_first_of('\0');
  73. if (!l)
  74. return "";
  75. if (l != string::npos)
  76. s.resize(l);
  77. for (auto i: s)
  78. if (i < 32)
  79. return "";
  80. return s;
  81. }
  82. return "";
  83. }
  84. }