ronantakizawa/codereview-bench huggingface dataset:
Repository: bevyengine/bevy
File: crates/bevy_image/src/image.rs (Rust)

Code before:
        ));
    }

    #[test]
    fn image_clear() {
        let mut image = Image::new_fill(
            Extent3d {
                width: 32,
                height: 32,
                depth_or_array_layers: 1,
            },
            TextureDimension::D2,
            &[0; 4],
            TextureFormat::Rgba8Snorm,
            RenderAssetUsages::all(),
        );

        assert!(image.data.as_ref().unwrap().iter().all(|&p| p == 0));

        image.clear(&[255; 4]);

        assert!(image.data.as_ref().unwrap().iter().all(|&p| p == 255));
    }

    #[test]
    fn get_or_inti_sampler_modifications() {
        // given some sampler
        let mut default_sampler = ImageSampler::Default;
        // a load_with_settings call wants to customize the descriptor
        let my_sampler_in_a_loader = default_sampler
            .get_or_init_descriptor()
            .with_filter(ImageFilterMode::Linear)
            .with_address_mode(ImageAddressMode::Repeat);

        assert_eq!(
            my_sampler_in_a_loader.address_mode_u,
            ImageAddressMode::Repeat
        );
        assert_eq!(my_sampler_in_a_loader.min_filter, ImageFilterMode::Linear);
    }
}


Review comment (suggestion):
```suggestion
    fn get_or_init_sampler_modifications() {
```

Code after:

        // Grow layers
        image.resize_in_place(Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 2,
        });

        // Pixels in the newly added layer should be zeroes.
        assert!(matches!(
            image.get_color_at_3d(0, 0, 1),
            Ok(Color::LinearRgba(GROW_FILL))
        ));
    }

    #[test]
    fn image_clear() {
        let mut image = Image::new_fill(
            Extent3d {
                width: 32,
                height: 32,
                depth_or_array_layers: 1,
            },
            TextureDimension::D2,
            &[0; 4],
            TextureFormat::Rgba8Snorm,
            RenderAssetUsages::all(),
        );

        assert!(image.data.as_ref().unwrap().iter().all(|&p| p == 0));

        image.clear(&[255; 4]);

        assert!(image.data.as_ref().unwrap().iter().all(|&p| p == 255));
    }

    #[test]
    fn get_or_init_sampler_modifications() {
        // given some sampler
        let mut default_sampler = ImageSampler::Default;
        // a load_with_settings call wants to customize the descriptor
        let my_sampler_in_a_loader = default_sampler
            .get_or_init_descriptor()
            .set_filter(ImageFilterMode::Linear)
            .set_address_mode(ImageAddressMode::Repeat);

        assert_eq!(
            my_sampler_in_a_loader.address_mode_u,
            ImageAddressMode::Repeat
        );
        assert_eq!(my_sampler_in_a_loader.min_filter, ImageFilterMode::Linear);
Repository: bevyengine/bevy
File: crates/bevy_ui_render/src/debug_overlay.rs (Rust)

Code before:
#[reflect(Resource)]
pub struct UiDebugOptions {
    /// Set to true to enable the UI debug overlay
    pub enabled: bool,
    /// Width of the overlay's lines in logical pixels
    pub line_width: f32,
    /// Override Color for the overlay's lines
    pub line_color_override: Option<LinearRgba>,
    /// Show outlines for non-visible UI nodes
    pub show_hidden: bool,
    /// Show outlines for clipped sections of UI nodes
    pub show_clipped: bool,
}

impl UiDebugOptions {
    pub fn toggle(&mut self) {
        self.enabled = !self.enabled;
    }

    pub fn reset(&mut self) {
        self.enabled = false;
        self.line_width = 1.;
        self.line_color_override = None;
        self.show_hidden = false;
        self.show_clipped = false;
    }
}

impl Default for UiDebugOptions {
    fn default() -> Self {
        Self {
            enabled: false,
            line_width: 1.,
            line_color_override: None,
            show_hidden: false,
            show_clipped: false,
        }
    }
}

pub fn extract_debug_overlay(
    mut commands: Commands,
    debug_options: Extract<Res<UiDebugOptions>>,
    mut extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,

Review comment (suggestion):
This could just do `*self = Self::default();`?

I'm not sure it's needed though, just set the state of the resource to the default in the teardown function.

Code after:
#[reflect(Resource)]
pub struct UiDebugOptions {
    /// Set to true to enable the UI debug overlay
    pub enabled: bool,
    /// Width of the overlay's lines in logical pixels
    pub line_width: f32,
    /// Override Color for the overlay's lines
    pub line_color_override: Option<LinearRgba>,
    /// Show outlines for non-visible UI nodes
    pub show_hidden: bool,
    /// Show outlines for clipped sections of UI nodes
    pub show_clipped: bool,
}

impl UiDebugOptions {
    pub fn toggle(&mut self) {
        self.enabled = !self.enabled;
    }
}

impl Default for UiDebugOptions {
    fn default() -> Self {
        Self {
            enabled: false,
            line_width: 1.,
            line_color_override: None,
            show_hidden: false,
            show_clipped: false,
        }
    }
}

pub fn extract_debug_overlay(
    mut commands: Commands,
    debug_options: Extract<Res<UiDebugOptions>>,
    mut extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &ComputedUiTargetCamera,
        )>,
    >,
    ui_stack: Extract<Res<UiStack>>,
    camera_map: Extract<UiCameraMap>,
) {
    if !debug_options.enabled {
        return;
Repository: bevyengine/bevy
File: examples/picking/dragdrop_picking.rs (Rust)

Code before:
        .observe(on_drag_drop)
        .observe(on_drag_leave);

    commands.spawn((
        Text2d::new("Drop here"),
        TextColor(Color::WHITE),
        Pickable::IGNORE,
    ));
}

fn on_drag_enter(
    mut event: On<Pointer<DragEnter>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    if event.dragged == *button {
        let Some(position) = event.hit.position else {
            return;
        };
        commands.spawn((
            GhostPreview,
            Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))),
            MeshMaterial2d(materials.add(Color::srgba(1.0, 1.0, 0.6, 0.5))),
            Transform::from_translation(position),
            Pickable::IGNORE,
        ));
        event.propagate(false);
    }
}

fn on_drag_over(
    mut event: On<Pointer<DragOver>>,
    button: Single<Entity, With<DraggableButton>>,
    mut ghost_transform: Single<&mut Transform, With<GhostPreview>>,
) {
    if event.dragged == *button {
        let Some(position) = event.hit.position else {
            return;
        };
        ghost_transform.translation = position;
        event.propagate(false);
    }
}

fn on_drag_drop(
    mut event: On<Pointer<DragDrop>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
    ghost: Single<Entity, With<GhostPreview>>,

Review comment (suggestion):
```suggestion
            Transform::from_translation(position + 2. * Vec3::Z),
```

Code after:
                TextColor(Color::BLACK),
                Pickable::IGNORE,
                Transform::from_translation(Vec3::Z),
            )],
        ))
        .observe(on_drag_enter)
        .observe(on_drag_over)
        .observe(on_drag_drop)
        .observe(on_drag_leave);
}

fn on_drag_enter(
    mut event: On<Pointer<DragEnter>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    if event.dragged == *button {
        let Some(position) = event.hit.position else {
            return;
        };
        commands.spawn((
            GhostPreview,
            Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))),
            MeshMaterial2d(materials.add(Color::srgba(1.0, 1.0, 0.6, 0.5))),
            Transform::from_translation(position + 2. * Vec3::Z),
            Pickable::IGNORE,
        ));
        event.propagate(false);
    }
}

fn on_drag_over(
    mut event: On<Pointer<DragOver>>,
    button: Single<Entity, With<DraggableButton>>,
    mut ghost_transform: Single<&mut Transform, With<GhostPreview>>,
) {
    if event.dragged == *button {
        let Some(position) = event.hit.position else {
            return;
        };
        ghost_transform.translation = position;
        event.propagate(false);
    }
}

fn on_drag_drop(
    mut event: On<Pointer<DragDrop>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
Repository: bevyengine/bevy
File: examples/picking/dragdrop_picking.rs (Rust)

Code before:
        let Some(position) = event.hit.position else {
            return;
        };
        ghost_transform.translation = position;
        event.propagate(false);
    }
}

fn on_drag_drop(
    mut event: On<Pointer<DragDrop>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
    ghost: Single<Entity, With<GhostPreview>>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    if event.dropped == *button {
        commands.entity(*ghost).despawn();
        let Some(position) = event.hit.position else {
            return;
        };
        commands.spawn((
            DroppedElement,
            Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))),
            MeshMaterial2d(materials.add(Color::srgb(1.0, 1.0, 0.6))),
            Transform::from_translation(position),
            Pickable::IGNORE,
        ));
        event.propagate(false);
    }
}

fn on_drag_leave(
    mut event: On<Pointer<DragLeave>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
    ghost: Single<Entity, With<GhostPreview>>,
) {
    if event.dragged == *button {
        commands.entity(*ghost).despawn();
        event.propagate(false);
    }
}


Review comment (suggestion):
```suggestion
            Transform::from_translation(position + 2. * Vec3::Z),
```

Code after:
    if event.dragged == *button {
        let Some(position) = event.hit.position else {
            return;
        };
        ghost_transform.translation = position;
        event.propagate(false);
    }
}

fn on_drag_drop(
    mut event: On<Pointer<DragDrop>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
    ghost: Single<Entity, With<GhostPreview>>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    if event.dropped == *button {
        commands.entity(*ghost).despawn();
        let Some(position) = event.hit.position else {
            return;
        };
        commands.spawn((
            DroppedElement,
            Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))),
            MeshMaterial2d(materials.add(Color::srgb(1.0, 1.0, 0.6))),
            Transform::from_translation(position + 2. * Vec3::Z),
            Pickable::IGNORE,
        ));
        event.propagate(false);
    }
}

fn on_drag_leave(
    mut event: On<Pointer<DragLeave>>,
    button: Single<Entity, With<DraggableButton>>,
    mut commands: Commands,
    ghost: Single<Entity, With<GhostPreview>>,
) {
    if event.dragged == *button {
        commands.entity(*ghost).despawn();
        event.propagate(false);
    }
}
Repository: bevyengine/bevy
File: examples/2d/rotate_to_cursor.rs (Rust)

Code before:
//! Demonstrates sprites to face the cursor.

use bevy::{math::ops, prelude::*};
use std::f32::consts::FRAC_PI_2;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(FixedUpdate, player_movement_system)
        .run();
}

/// Player component
#[derive(Component)]
struct Player;

/// Add the game's entities to our world and creates an orthographic camera for 2D rendering.
///
/// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:
///
/// * `X` axis goes from left to right (`+X` points right)
/// * `Y` axis goes from bottom to top (`+Y` point up)
/// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)
///
/// The origin is at the center of the screen.

Review comment (suggestion):
```suggestion
//! Demonstrates rotating sprites to face the cursor.
```

Code after:
//! Demonstrates rotating sprites to face the cursor.

use bevy::prelude::*;
use std::f32::consts::FRAC_PI_2;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(FixedUpdate, player_movement_system)
        .run();
}

/// Player component
#[derive(Component)]
struct Player;

/// Add the game's entities to our world and create an orthographic camera for 2D rendering.
///
/// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:
///
/// * `X` axis goes from left to right (`+X` points right)
/// * `Y` axis goes from bottom to top (`+Y` point up)
/// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)
///
/// The world origin in this case is at the center of the screen, but the camera could
Repository: bevyengine/bevy
File: examples/2d/rotate_to_cursor.rs (Rust)

Code before:
//! Demonstrates sprites to face the cursor.

use bevy::{math::ops, prelude::*};
use std::f32::consts::FRAC_PI_2;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(FixedUpdate, player_movement_system)
        .run();
}

/// Player component
#[derive(Component)]
struct Player;

/// Add the game's entities to our world and creates an orthographic camera for 2D rendering.
///
/// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:
///
/// * `X` axis goes from left to right (`+X` points right)
/// * `Y` axis goes from bottom to top (`+Y` point up)
/// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)
///
/// The origin is at the center of the screen.
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    let ship_handle = asset_server.load("textures/simplespace/ship_C.png");

    commands.spawn(Camera2d);

    // Player controlled ship
    commands.spawn((Sprite::from_image(ship_handle), Player));
}

/// Demonstrates applying rotation and movement based on keyboard input.
fn player_movement_system(
    time: Res<Time>,
    keyboard_input: Res<ButtonInput<KeyCode>>,
    mut player: Single<&mut Transform, With<Player>>,
    camera_query: Single<(&Camera, &GlobalTransform)>,
    window: Single<&Window>,
) {

Review comment (suggestion):
```suggestion
/// Add the game's entities to our world and create an orthographic camera for 2D rendering.
```

Code after:
//! Demonstrates rotating sprites to face the cursor.

use bevy::prelude::*;
use std::f32::consts::FRAC_PI_2;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(FixedUpdate, player_movement_system)
        .run();
}

/// Player component
#[derive(Component)]
struct Player;

/// Add the game's entities to our world and create an orthographic camera for 2D rendering.
///
/// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:
///
/// * `X` axis goes from left to right (`+X` points right)
/// * `Y` axis goes from bottom to top (`+Y` point up)
/// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)
///
/// The world origin in this case is at the center of the screen, but the camera could
/// move in which case the world origin would not be the center of the screen
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    let ship_handle = asset_server.load("textures/simplespace/ship_C.png");

    commands.spawn(Camera2d);

    // Player controlled ship
    commands.spawn((Sprite::from_image(ship_handle), Player));
}

/// Demonstrates applying rotation and movement based on keyboard input.
fn player_movement_system(
    mut player: Single<&mut Transform, With<Player>>,
    camera_query: Single<(&Camera, &GlobalTransform)>,
    window: Single<&Window>,
) {
    let (camera, camera_transform) = *camera_query;
Repository: bevyengine/bevy
File: examples/ui/generic_font_families.rs (Rust)

Code before:
//! This example demonstrates generic font families

use bevy::{
    color::palettes::{
        css::{WHEAT, YELLOW},
        tailwind::ZINC_600,
    },
    prelude::*,
    text::CosmicFontSystem,
};

fn main() {
    let mut app = App::new();
    app.add_plugins(DefaultPlugins).add_systems(Startup, setup);

    // The default font will be used where there is no system font matching the
    // generic font variant's font name stored in Cosmic Text's `Database`.
    app.world_mut()
        .resource_mut::<CosmicFontSystem>()
        .db_mut()
        .load_system_fonts();

    app.run();
}

const FONT_SIZE: f32 = 25.;

Review comment (suggestion):
```suggestion
//! This example demonstrates generic font families,
//! which look up a matching font from installed fonts on the user's device.
//!
//! This is used as a fallback in case a specific selected font is available,
//! ensuring that the provided font approximately matches the needs
//! of a given piece of text.
//!
//! This feature is most useful for non-game applications;
//! most games instead choose to simply bundle their required fonts
//! to ensure a unified visual look.
```

Code after:
//! This example demonstrates generic font families,
//! which allow font faces to be selected using broadly defined
//! categories (such as serif or monospace) without selecting
//! a specific font family.
//!
//! Each generic font family is first resolved to a concrete
//! family name, which is then matched to a font in the internal
//! font database. This example loads system installed fonts to
//! populate the database.
//!
//! This feature is most useful for non-game applications;
//! most games instead choose to simply bundle their required fonts
//! to ensure a unified visual look.

use bevy::{
    color::palettes::{
        css::{WHEAT, YELLOW},
        tailwind::ZINC_600,
    },
    prelude::*,
    text::CosmicFontSystem,
};

fn main() {
    let mut app = App::new();
    app.add_plugins(DefaultPlugins).add_systems(Startup, setup);
Repository: bevyengine/bevy
File: benches/benches/bevy_ecs/world/spawn.rs (Rust)

Code before:
        group.bench_function(format!("{entity_count}_entities"), |bencher| {
            let mut world = World::default();
            bencher.iter(|| {
                for _ in 0..entity_count {
                    world.spawn((A(Mat4::default()), B(Vec4::default())));
                }
            });
        });
    }

    group.finish();
}

pub fn world_spawn_batch(criterion: &mut Criterion) {
    let mut group = criterion.benchmark_group("spawn_world_batch");
    group.warm_up_time(core::time::Duration::from_millis(500));
    group.measurement_time(core::time::Duration::from_secs(4));

    for batch_count in [1, 100, 1000, 10_000] {
        group.bench_function(format!("{batch_count}_entities"), |bencher| {
            let mut world = World::default();
            bencher.iter(|| {
                for _ in 0..(10_000 / batch_count) {
                    world.spawn_batch(
                        (0..batch_count).map(|_| (A(Mat4::default()), B(Vec4::default()))),
                    );
                }
            });
        });
    }

    group.finish();
}


Review comment (performance):
```suggestion
                    world.spawn_batch(std::iter::repeat_n(
                        (A(Mat4::default()), B(Vec4::default())),
                        batch_count,
                    ));
```

I prefer to use `repeat_n` over an iterator on a range, but doesn't matter that much

Code after:
        group.bench_function(format!("{entity_count}_entities"), |bencher| {
            let mut world = World::default();
            bencher.iter(|| {
                for _ in 0..entity_count {
                    world.spawn((A(Mat4::default()), B(Vec4::default())));
                }
            });
        });
    }

    group.finish();
}

pub fn world_spawn_batch(criterion: &mut Criterion) {
    let mut group = criterion.benchmark_group("spawn_world_batch");
    group.warm_up_time(core::time::Duration::from_millis(500));
    group.measurement_time(core::time::Duration::from_secs(4));

    for batch_count in [1, 100, 1000, 10_000] {
        group.bench_function(format!("{batch_count}_entities"), |bencher| {
            let mut world = World::default();
            bencher.iter(|| {
                for _ in 0..(10_000 / batch_count) {
                    world.spawn_batch(std::iter::repeat_n(
                        (A(Mat4::default()), B(Vec4::default())),
                        batch_count,
                    ));
                }
            });
        });
    }

    group.finish();
}