Skip to content

Commit d1bf9a9

Browse files
committed
Use strncpy instead of byte-oriented operations
The strncpy(s1, s2, n) function shall copy not more than n bytes (bytes that follow a NUL character are not copied) from the array pointed to by s2 to the array pointed to by s1. Both strncpy and strlen are usually optimized in libc implementation, and we should utilize them when possible.
1 parent 666b7eb commit d1bf9a9

File tree

2 files changed

+10
-15
lines changed

2 files changed

+10
-15
lines changed

src/io.c

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -61,27 +61,22 @@ void memory_delete(memory_t *mem)
6161
free(mem);
6262
}
6363

64-
void memory_read(memory_t *mem, uint8_t *dst, uint32_t addr, uint32_t size)
64+
void memory_read(const memory_t *mem,
65+
uint8_t *dst,
66+
uint32_t addr,
67+
uint32_t size)
6568
{
6669
memcpy(dst, mem->mem_base + addr, size);
6770
}
6871

69-
uint32_t memory_read_str(memory_t *mem,
72+
uint32_t memory_read_str(const memory_t *mem,
7073
uint8_t *dst,
7174
uint32_t addr,
7275
uint32_t max)
7376
{
74-
uint32_t len = 0;
75-
const uint8_t *end = dst + max;
76-
for (;; ++len, ++dst) {
77-
uint8_t ch = 0;
78-
memory_read(mem, &ch, addr + len, 1);
79-
if (dst < end)
80-
*dst = ch;
81-
if (!ch)
82-
break;
83-
}
84-
return len + 1;
77+
char *d = (char *) dst;
78+
char *s = (char *) mem->mem_base + addr;
79+
return strlen(strncpy(d, s, max));
8580
}
8681

8782
uint32_t memory_ifetch(uint32_t addr)

src/io.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ memory_t *memory_new();
2121
void memory_delete(memory_t *m);
2222

2323
/* read a C-style string from memory */
24-
uint32_t memory_read_str(memory_t *m,
24+
uint32_t memory_read_str(const memory_t *m,
2525
uint8_t *dst,
2626
uint32_t addr,
2727
uint32_t max);
@@ -39,7 +39,7 @@ uint16_t memory_read_s(uint32_t addr);
3939
uint8_t memory_read_b(uint32_t addr);
4040

4141
/* read a length of data from memory */
42-
void memory_read(memory_t *m, uint8_t *dst, uint32_t addr, uint32_t size);
42+
void memory_read(const memory_t *m, uint8_t *dst, uint32_t addr, uint32_t size);
4343

4444
static inline void memory_write(memory_t *m,
4545
uint32_t addr,

0 commit comments

Comments
 (0)