lfs_util.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * lfs utility functions
  3. *
  4. * Copyright (c) 2017 ARM Limited
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef LFS_UTIL_H
  19. #define LFS_UTIL_H
  20. #include <stdlib.h>
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. // Builtin functions, these may be replaced by more
  24. // efficient implementations in the system
  25. static inline uint32_t lfs_max(uint32_t a, uint32_t b) {
  26. return (a > b) ? a : b;
  27. }
  28. static inline uint32_t lfs_min(uint32_t a, uint32_t b) {
  29. return (a < b) ? a : b;
  30. }
  31. static inline uint32_t lfs_npw2(uint32_t a) {
  32. #if defined(__GNUC__) || defined(__CC_ARM)
  33. return 32 - __builtin_clz(a-1);
  34. #else
  35. uint32_t r = 0;
  36. uint32_t s;
  37. a -= 1;
  38. s = (a > 0xffff) << 4; a >>= s; r |= s;
  39. s = (a > 0xff ) << 3; a >>= s; r |= s;
  40. s = (a > 0xf ) << 2; a >>= s; r |= s;
  41. s = (a > 0x3 ) << 1; a >>= s; r |= s;
  42. return (r | (a >> 1)) + 1;
  43. #endif
  44. }
  45. static inline uint32_t lfs_ctz(uint32_t a) {
  46. #if defined(__GNUC__)
  47. return __builtin_ctz(a);
  48. #else
  49. return lfs_npw2((a & -a) + 1) - 1;
  50. #endif
  51. }
  52. static inline uint32_t lfs_popc(uint32_t a) {
  53. #if defined(__GNUC__) || defined(__CC_ARM)
  54. return __builtin_popcount(a);
  55. #else
  56. a = a - ((a >> 1) & 0x55555555);
  57. a = (a & 0x33333333) + ((a >> 2) & 0x33333333);
  58. return (((a + (a >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24;
  59. #endif
  60. }
  61. static inline int lfs_scmp(uint32_t a, uint32_t b) {
  62. return (int)(unsigned)(a - b);
  63. }
  64. // CRC-32 with polynomial = 0x04c11db7
  65. void lfs_crc(uint32_t *crc, const void *buffer, size_t size);
  66. // Logging functions, these may be replaced by system-specific
  67. // logging functions
  68. #define LFS_DEBUG(fmt, ...) printf("lfs debug: " fmt "\n", __VA_ARGS__)
  69. #define LFS_WARN(fmt, ...) printf("lfs warn: " fmt "\n", __VA_ARGS__)
  70. #define LFS_ERROR(fmt, ...) printf("lfs error: " fmt "\n", __VA_ARGS__)
  71. #endif