@@ -8,7 +8,7 @@ use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawWindowHandle};
88
99use std:: io;
1010use std:: marker:: PhantomData ;
11- use std:: mem;
11+ use std:: mem:: size_of ;
1212use std:: num:: { NonZeroI32 , NonZeroU32 } ;
1313use std:: ptr:: { self , NonNull } ;
1414use std:: slice;
@@ -55,7 +55,7 @@ impl Buffer {
5555 // Create a new bitmap info struct.
5656 let bitmap_info = BitmapInfo {
5757 bmi_header : Gdi :: BITMAPINFOHEADER {
58- biSize : mem :: size_of :: < Gdi :: BITMAPINFOHEADER > ( ) as u32 ,
58+ biSize : size_of :: < Gdi :: BITMAPINFOHEADER > ( ) as u32 ,
5959 biWidth : width. get ( ) ,
6060 biHeight : -height. get ( ) ,
6161 biPlanes : 1 ,
@@ -116,12 +116,9 @@ impl Buffer {
116116
117117 #[ inline]
118118 fn pixels_mut ( & mut self ) -> & mut [ Pixel ] {
119- unsafe {
120- slice:: from_raw_parts_mut (
121- self . pixels . as_ptr ( ) ,
122- i32:: from ( self . width ) as usize * i32:: from ( self . height ) as usize ,
123- )
124- }
119+ let num_bytes =
120+ byte_stride ( self . width . get ( ) as u32 , 32 ) as usize * self . height . get ( ) as usize ;
121+ unsafe { slice:: from_raw_parts_mut ( self . pixels . as_ptr ( ) , num_bytes / size_of :: < Pixel > ( ) ) }
125122 }
126123}
127124
@@ -252,11 +249,7 @@ pub struct BufferImpl<'a> {
252249impl BufferInterface for BufferImpl < ' _ > {
253250 fn byte_stride ( & self ) -> NonZeroU32 {
254251 let width = self . buffer . width . get ( ) as u32 ;
255- let bit_count = 32 ;
256- // https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader#calculating-surface-stride
257- // When `bit_count == 32`, this is always just equal to `width * 4`.
258- let stride = ( ( width * bit_count + 31 ) & !31 ) >> 3 ;
259- NonZeroU32 :: new ( stride) . unwrap ( )
252+ NonZeroU32 :: new ( byte_stride ( width, 32 ) ) . unwrap ( )
260253 }
261254
262255 fn width ( & self ) -> NonZeroU32 {
@@ -476,3 +469,10 @@ impl<T> From<T> for OnlyUsedFromOrigin<T> {
476469 Self ( t)
477470 }
478471}
472+
473+ #[ inline]
474+ fn byte_stride ( width : u32 , bit_count : u32 ) -> u32 {
475+ // <https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader#calculating-surface-stride>
476+ // When `bit_count == 32`, this is always just equal to `width * 4`.
477+ ( ( width * bit_count + 31 ) & !31 ) >> 3
478+ }
0 commit comments