From 4708a4568ae56f08d0d6c9759be49efa6f99b3fe Mon Sep 17 00:00:00 2001 From: Chris Bridge Date: Sat, 1 Aug 2026 11:41:25 -0400 Subject: [PATCH] Add further checks on validity of segmented LUT data --- src/highdicom/pixels.py | 18 ++++++++++++++++++ tests/test_content.py | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/highdicom/pixels.py b/src/highdicom/pixels.py index b12bf00e..db313d2e 100644 --- a/src/highdicom/pixels.py +++ b/src/highdicom/pixels.py @@ -511,6 +511,15 @@ def _expand_segmented_lut( i += (length + 2) elif opcode == 1: # Linear segment type (interpolation) + + # This type of segment may not be placed first as it requires the + # previous value + if i == 0: + raise ValueError( + "Error reading segmented LUT data, a linear segment may " + "not be used as the first segment." + ) + length = segmented_lut_data[i + 1] # Need signed integers for subsequent calculations @@ -570,6 +579,15 @@ def _get_expanded_lut_length( i += (length + 2) elif opcode == 1: # Linear segment type (interpolation) + + # This type of segment may not be placed first as it requires the + # previous value + if i == 0: + raise ValueError( + "Error reading segmented LUT data, a linear segment may " + "not be used as the first segment." + ) + length = segmented_lut_data[i + 1] total_length += length i += 3 diff --git a/tests/test_content.py b/tests/test_content.py index 11b4fd7a..567d0ad7 100644 --- a/tests/test_content.py +++ b/tests/test_content.py @@ -2157,6 +2157,33 @@ def test_construction_8bit(self): with pytest.raises(TypeError): lut.apply(arr, dtype=dtype) + def test_construction_invalid_opcode(self): + # Example with an invalid opcode (4) + segmented_lut_data = np.array([4, 0, 0], dtype=np.uint8) + + msg = "Encountered unexpected segment type 4" + with pytest.raises(ValueError, match=msg): + SegmentedPaletteColorLUT( + 0, + segmented_lut_data, + 'red', + ) + + def test_construction_linear_segment_first(self): + # Linear segment (opcode 1) may not be the first segment + segmented_lut_data = np.array([1, 10, 10], dtype=np.uint8) + + msg = ( + "Error reading segmented LUT data, a linear segment may not be " + "used as the first segment." + ) + with pytest.raises(ValueError, match=msg): + SegmentedPaletteColorLUT( + 0, + segmented_lut_data, + 'red', + ) + def test_extract_from_dataset(self): for dtype in [np.uint8, np.uint16]: for color in ['red', 'green', 'blue']: