(root)/
strace-6.5/
tests-mx32/
hexquote_strndup.c
       1  /*
       2   * Make a hexquoted copy of a string
       3   *
       4   * Copyright (c) 2016-2021 Dmitry V. Levin <ldv@strace.io>
       5   * All rights reserved.
       6   *
       7   * SPDX-License-Identifier: GPL-2.0-or-later
       8   */
       9  
      10  #include "tests.h"
      11  
      12  #include <assert.h>
      13  #include <stdlib.h>
      14  #include <string.h>
      15  
      16  const char *
      17  hexquote_strndup(const char *src, const size_t src_len)
      18  {
      19  	const size_t dst_size = 4 * src_len + 1;
      20  	assert(dst_size > src_len);
      21  
      22  	char *dst = malloc(dst_size);
      23  	if (!dst)
      24  		perror_msg_and_fail("malloc(%zu)", dst_size);
      25  
      26  	char *p = dst;
      27  	for (size_t i = 0; i < src_len; ++i) {
      28  		unsigned int c = ((const unsigned char *) src)[i];
      29  		*(p++) = '\\';
      30  		*(p++) = 'x';
      31  		*(p++) = "0123456789abcdef"[c >> 4];
      32  		*(p++) = "0123456789abcdef"[c & 0xf];
      33  	}
      34  	*p = '\0';
      35  
      36  	return dst;
      37  }