From 0bc8d4968400b2e94227409a1eab7f53e8f5c236 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 17 Jun 2024 18:02:22 +0300 Subject: [PATCH] LibImage: Add image format probing Instead of determining the image type in Image.cpp call image probing functions for each supported image type --- LibImage/Image.cpp | 23 +++-------------------- LibImage/Netbpm.cpp | 20 ++++++++++++++++++++ LibImage/include/LibImage/Netbpm.h | 1 + 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/LibImage/Image.cpp b/LibImage/Image.cpp index 2bee497ee8..0e0befa6be 100644 --- a/LibImage/Image.cpp +++ b/LibImage/Image.cpp @@ -41,12 +41,6 @@ namespace LibImage return BAN::Error::from_errno(errno); } - if (st.st_size < 2) - { - fprintf(stddbg, "invalid image (too small)\n"); - return BAN::Error::from_errno(EINVAL); - } - void* addr = mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (addr == MAP_FAILED) { @@ -58,21 +52,10 @@ namespace LibImage auto image_data_span = BAN::ConstByteSpan(reinterpret_cast(addr), st.st_size); - uint16_t u16_signature = image_data_span.as(); - switch (u16_signature) - { - case 0x3650: - case 0x3550: - case 0x3450: - case 0x3350: - case 0x3250: - case 0x3150: - return TRY(load_netbpm(image_data_span)); - default: - fprintf(stderr, "unrecognized image format\n"); - break; - } + if (probe_netbpm(image_data_span)) + return TRY(load_netbpm(image_data_span)); + fprintf(stderr, "unrecognized image format\n"); return BAN::Error::from_errno(ENOTSUP); } diff --git a/LibImage/Netbpm.cpp b/LibImage/Netbpm.cpp index 18c95f101d..87d58f4f13 100644 --- a/LibImage/Netbpm.cpp +++ b/LibImage/Netbpm.cpp @@ -34,6 +34,26 @@ namespace LibImage return result; } + + bool probe_netbpm(BAN::ConstByteSpan image_data) + { + if (image_data.size() < 2) + return false; + uint16_t u16_signature = image_data.as(); + switch (u16_signature) + { + case 0x3650: + case 0x3550: + case 0x3450: + case 0x3350: + case 0x3250: + case 0x3150: + return true; + default: + return false; + } + } + BAN::ErrorOr> load_netbpm(BAN::ConstByteSpan image_data) { if (image_data.size() < 11) diff --git a/LibImage/include/LibImage/Netbpm.h b/LibImage/include/LibImage/Netbpm.h index 5e6554fb2a..31190a1aff 100644 --- a/LibImage/include/LibImage/Netbpm.h +++ b/LibImage/include/LibImage/Netbpm.h @@ -5,6 +5,7 @@ namespace LibImage { + bool probe_netbpm(BAN::ConstByteSpan); BAN::ErrorOr> load_netbpm(BAN::ConstByteSpan); }