@@ -53,21 +53,16 @@ public EuclideanPixelMap(Configuration configuration, ReadOnlyMemory<TPixel> pal
5353 this . rgbaPalette = new Rgba32 [ palette . Length ] ;
5454 this . cache = new ColorDistanceCache ( configuration . MemoryAllocator ) ;
5555 PixelOperations < TPixel > . Instance . ToRgba32 ( configuration , this . Palette . Span , this . rgbaPalette ) ;
56- this . transparentIndex = transparentIndex ;
56+
57+ // If the provided transparentIndex is outside of the palette, silently ignore it.
58+ this . transparentIndex = transparentIndex < this . Palette . Length ? transparentIndex : - 1 ;
5759 }
5860
5961 /// <summary>
6062 /// Gets the color palette of this <see cref="EuclideanPixelMap{TPixel}"/>.
6163 /// The palette memory is owned by the palette source that created it.
6264 /// </summary>
63- public ReadOnlyMemory < TPixel > Palette
64- {
65- [ MethodImpl ( InliningOptions . ShortMethod ) ]
66- get ;
67-
68- [ MethodImpl ( InliningOptions . ShortMethod ) ]
69- private set ;
70- }
65+ public ReadOnlyMemory < TPixel > Palette { get ; private set ; }
7166
7267 /// <summary>
7368 /// Returns the closest color in the palette and the index of that pixel.
@@ -106,10 +101,10 @@ public void Clear(ReadOnlyMemory<TPixel> palette)
106101 }
107102
108103 /// <summary>
109- /// Allows setting the transparent index after construction.
104+ /// Allows setting the transparent index after construction. If the provided transparentIndex is outside of the palette, silently ignore it.
110105 /// </summary>
111106 /// <param name="index">An explicit index at which to match transparent pixels.</param>
112- public void SetTransparentIndex ( int index ) => this . transparentIndex = index ;
107+ public void SetTransparentIndex ( int index ) => this . transparentIndex = index < this . Palette . Length ? index : - 1 ;
113108
114109 [ MethodImpl ( InliningOptions . ShortMethod ) ]
115110 private int GetClosestColorSlow ( Rgba32 rgba , ref TPixel paletteRef , out TPixel match )
@@ -122,19 +117,9 @@ private int GetClosestColorSlow(Rgba32 rgba, ref TPixel paletteRef, out TPixel m
122117 {
123118 // We have explicit instructions. No need to search.
124119 index = this . transparentIndex ;
120+ DebugGuard . MustBeLessThan ( index , this . Palette . Length , nameof ( index ) ) ;
125121 this . cache . Add ( rgba , ( byte ) index ) ;
126-
127- if ( index >= 0 && index < this . Palette . Length )
128- {
129- match = Unsafe . Add ( ref paletteRef , ( uint ) index ) ;
130- }
131- else
132- {
133- Unsafe . SkipInit ( out TPixel pixel ) ;
134- pixel . FromScaledVector4 ( Vector4 . Zero ) ;
135- match = pixel ;
136- }
137-
122+ match = Unsafe . Add ( ref paletteRef , ( uint ) index ) ;
138123 return index ;
139124 }
140125
0 commit comments