Skip to content

Commit 5cb0e8b

Browse files
lgritzscott-wilson
authored andcommitted
feat(span.h): span_memcpy is a safer memcpy when you know the span boundaries (AcademySoftwareFoundation#4597)
Signed-off-by: Larry Gritz <[email protected]> Signed-off-by: Scott Wilson <[email protected]>
1 parent ce7a03c commit 5cb0e8b

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/iff.imageio/iffoutput.cpp

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -679,8 +679,7 @@ IffOutput::compress_verbatim(const uint8_t*& in, uint8_t*& out, int size,
679679
// copy
680680
OIIO_DASSERT(out >= out_span.begin() && out < out_span.end());
681681
*out++ = count - 1;
682-
OIIO_DASSERT(out >= out_span.begin() && out + count <= out_span.end());
683-
memcpy(out, in, count);
682+
span_memcpy(out, in, size_t(count), out_span, in_span);
684683

685684
out += count;
686685
in += count;

src/include/OpenImageIO/span.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,22 @@ spancpy(span<T> dst, size_t dstoffset, cspan<T> src, size_t srcoffset = 0,
531531

532532

533533

534+
/// Perform a safe `memcpy(dst, src, n*sizeof(T))` but ensuring that the
535+
/// memory accesses stay within the boundaries of spans `dst_span` and
536+
/// `src_span`.
537+
///
538+
/// This is intended to be used as a memory-safe replacement for memcpy if
539+
/// you know the spans representing safe areas.
540+
template<typename T>
541+
inline size_t
542+
span_memcpy(T* dst, const T* src, size_t n, span<T> dst_span, cspan<T> src_span)
543+
{
544+
return spancpy(dst_span, dst - dst_span.begin(), src_span,
545+
src - src_span.begin(), n);
546+
}
547+
548+
549+
534550
/// Try to write `n` copies of `val` into `dst[offset...]`. Don't write
535551
/// outside the span boundaries. Return the number of items actually written,
536552
/// which should be `n` if the operation was fully successful, but may be less

0 commit comments

Comments
 (0)