Add byte-swap helpers
[fw/openocd] / src / helper / types.h
index 12b95150b4999fbe115c2950cd86ac0edcc73c23..7a845284e4467cd8f4db5fad568eebfe02f50828 100644 (file)
@@ -18,7 +18,7 @@
  *   You should have received a copy of the GNU General Public License     *
  *   along with this program; if not, write to the                         *
  *   Free Software Foundation, Inc.,                                       *
- *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
  ***************************************************************************/
 #ifndef TYPES_H
 #define TYPES_H
@@ -183,6 +183,46 @@ static inline void h_u16_to_be(uint8_t* buf, int val)
        buf[1] = (uint8_t) (val >> 0);
 }
 
+/**
+ * Byte-swap buffer 16-bit.
+ *
+ * Len must be even, dst and src must be either the same or non-overlapping.
+ *
+ * @param dst Destination buffer.
+ * @param src Source buffer.
+ * @param len Length of source (and destination) buffer, in bytes.
+ */
+static inline void buf_bswap16(uint8_t *dst, const uint8_t *src, size_t len)
+{
+       assert(len % 2 == 0);
+       assert(dst == src || dst + len <= src || src + len <= dst);
+
+       for (size_t n = 0; n < len; n += 2) {
+               uint16_t x = be_to_h_u16(src + n);
+               h_u16_to_le(dst + n, x);
+       }
+}
+
+/**
+ * Byte-swap buffer 32-bit.
+ *
+ * Len must be divisible by four, dst and src must be either the same or non-overlapping.
+ *
+ * @param dst Destination buffer.
+ * @param src Source buffer.
+ * @param len Length of source (and destination) buffer, in bytes.
+ */
+static inline void buf_bswap32(uint8_t *dst, const uint8_t *src, size_t len)
+{
+       assert(len % 4 == 0);
+       assert(dst == src || dst + len <= src || src + len <= dst);
+
+       for (size_t n = 0; n < len; n += 4) {
+               uint32_t x = be_to_h_u32(src + n);
+               h_u32_to_le(dst + n, x);
+       }
+}
+
 #if defined(__ECOS)
 
 /* eCos plain lacks these definition... A series of upstream patches
@@ -197,6 +237,8 @@ static inline void h_u16_to_be(uint8_t* buf, int val)
 #define PRIi32 "i"
 #define PRIu32 "u"
 #define PRId8 PRId32
+#define SCNx64 "llx"
+#define PRIx64 "llx"
 
 typedef CYG_ADDRWORD intptr_t;
 typedef int64_t intmax_t;
@@ -215,11 +257,11 @@ typedef uint64_t uintmax_t;
 #define UINT64_MAX (__CONCAT(INT64_MAX, U) * 2ULL + 1ULL)
 #endif
 
-    #ifndef LLONG_MAX
+       #ifndef LLONG_MAX
        #define ULLONG_MAX      UINT64_C(0xFFFFFFFFFFFFFFFF)
        #define LLONG_MAX       INT64_C(0x7FFFFFFFFFFFFFFF)
        #define LLONG_MIN       ULLONG_MAX
-    #endif
+       #endif
 
 
 #define ULLONG_MAX 18446744073709551615