ronantakizawa/codereview-bench huggingface dataset:
Repository: rust-lang/rust
File: tests/codegen-llvm/riscv-abi/call-llvm-intrinsics.rs (Rust)

Code before:
//@ add-minicore
//@ compile-flags: -C no-prepopulate-passes
//@ revisions: host riscv64gc
//@ [host] only-riscv64
//@ [riscv64gc] compile-flags: --target riscv64gc-unknown-linux-gnu
//@ [riscv64gc] needs-llvm-components: riscv
//@ min-llvm-version: 21

#![feature(link_llvm_intrinsics)]
#![crate_type = "lib"]

struct A;

impl Drop for A {
    fn drop(&mut self) {
        println!("A");
    }
}

extern "C" {
    #[link_name = "llvm.sqrt.f32"]
    fn sqrt(x: f32) -> f32;
}

pub fn do_call() {
    let _a = A;

Review comment (suggestion):
just the minicore annotation is not enough. I think you also need 

```
#![feature(no_core, lang_items)]
#![no_std]
#![no_core]
```

and then 

```
extern crate minicore;
use minicore::*;
```

for e.g. `Drop` and `f32`. For iteration speed it is useful to run this test locally, e.g. using 

```
./x test tests/codegen-llvm/riscv-abi/call-llvm-intrinsics.rs
```

Code after:
//@ add-minicore
//@ compile-flags: -C no-prepopulate-passes
//@ revisions: riscv32gc riscv64gc
//@ [riscv32gc] compile-flags: --target riscv32gc-unknown-linux-gnu
//@ [riscv32gc] needs-llvm-components: riscv
//@ [riscv64gc] compile-flags: --target riscv64gc-unknown-linux-gnu
//@ [riscv64gc] needs-llvm-components: riscv
//@ min-llvm-version: 21

#![feature(link_llvm_intrinsics)]
#![feature(no_core, lang_items)]
#![no_std]
#![no_core]
#![crate_type = "lib"]

extern crate minicore;
use minicore::*;

extern "C" {
    #[link_name = "llvm.sqrt.f32"]
    fn sqrt(x: f32) -> f32;
}

pub fn do_call() {
    unsafe {
        // Ensure that we `call` LLVM intrinsics instead of trying to `invoke` them
Repository: rust-lang/rustlings
File: exercises/11_hashmaps/hashmaps2.rs (Rust)

Code before:
// represents the name of each fruit we collect and the value represents how
// many of that particular fruit we have collected. Three types of fruits -
// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You
// must add fruit to the basket so that there is at least one of each kind and
// more than 11 in total - we have a lot of mouths to feed. You are not allowed
// to insert any more of these fruits!
//
// Make me pass the tests!
//
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::collections::HashMap;

#[derive(Hash, PartialEq, Eq, Debug)]
enum Fruit {
    Apple,
    Banana,
    Mango,
    Lychee,
    Pineapple,
}

const FRUIT_KINDS: [Fruit; 5] = [
    Fruit::Apple,
    Fruit::Banana,
    Fruit::Mango,
    Fruit::Lychee,
    Fruit::Pineapple,
];

fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
    let fruit_kinds = vec![
        Fruit::Apple,
        Fruit::Banana,
        Fruit::Mango,
        Fruit::Lychee,
        Fruit::Pineapple,
    ];

    for fruit in fruit_kinds {
        // TODO: Insert new fruits if they are not already present in the
        // basket. Note that you are not allowed to put any type of fruit that's
        // already present!
    }
}

#[cfg(test)]
mod tests {

Review comment (suggestion):
this can be in the test module, and there's no reason to have this be an array when it could be a `Vec<Fruit>` instead

Code after:
// represents the name of each fruit we collect and the value represents how
// many of that particular fruit we have collected. Three types of fruits -
// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You
// must add fruit to the basket so that there is at least one of each kind and
// more than 11 in total - we have a lot of mouths to feed. You are not allowed
// to insert any more of these fruits!
//
// Make me pass the tests!
//
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::collections::HashMap;

#[derive(Hash, PartialEq, Eq, Debug)]
enum Fruit {
    Apple,
    Banana,
    Mango,
    Lychee,
    Pineapple,
}

fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
    let fruit_kinds = vec![
        Fruit::Apple,
        Fruit::Banana,
        Fruit::Mango,
        Fruit::Lychee,
        Fruit::Pineapple,
    ];

    for fruit in fruit_kinds {
        // TODO: Insert new fruits if they are not already present in the
        // basket. Note that you are not allowed to put any type of fruit that's
        // already present!
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Don't modify this function!
    fn get_fruit_basket() -> HashMap<Fruit, u32> {
        let mut basket = HashMap::<Fruit, u32>::new();
        basket.insert(Fruit::Apple, 4);
        basket.insert(Fruit::Mango, 2);
        basket.insert(Fruit::Lychee, 5);
Repository: samber/lo
File: drop.go (Go)

Code before:
package lo

func Drop[T any](collection []T, n int) []T {
	if len(collection) <= n {
		return make([]T, 0)
	}

	result := make([]T, len(collection)-n)
	for i := n; i < len(collection); i++ {
		result[i-n] = collection[i]
	}

	return result
}

func DropWhile[T any](collection []T, predicate func(T) bool) []T {
	result := []T{}

	i := 0
	for ; i < len(collection); i++ {
		if !predicate(collection[i]) {
			break
		}
	}

	for ; i < len(collection); i++ {
		result = append(result, collection[i])
	}

	return result
}

func DropRight[T any](collection []T, n int) []T {
	if len(collection) <= n {
		return make([]T, 0)
	}

	result := make([]T, len(collection)-n)
	for i := len(collection) - 1 - n; i != 0; i-- {
		result[i] = collection[i]
	}

	return result
}

func DropRightWhile[T any](collection []T, predicate func(T) bool) []T {
	result := []T{}

	i := len(collection) - 1
	for ; i >= 0; i-- {

Review comment (suggestion):
Since you know the size of result, you should allocate it here, and use `result[j - i] = xxx` instead of `append`.

(prevent a little overhead)

Code after:
package lo

//Drop drops n elements from the beginning of a slice or array.
func Drop[T any](collection []T, n int) []T {
	if len(collection) <= n {
		return make([]T, 0)
	}

	result := make([]T, len(collection)-n)
	for i := n; i < len(collection); i++ {
		result[i-n] = collection[i]
	}

	return result
}

//DropWhile drops elements from the beginning of a slice or array while the predicate returns true.
func DropWhile[T any](collection []T, predicate func(T) bool) []T {
	i := 0
	for ; i < len(collection); i++ {
		if !predicate(collection[i]) {
			break
		}
	}

	result := make([]T, len(collection)-i)

	for j := 0; i < len(collection); i, j = i+1, j+1 {
		result[j] = collection[i]
	}

	return result
}

//DropRight drops n elements from the end of a slice or array.
func DropRight[T any](collection []T, n int) []T {
	if len(collection) <= n {
		return make([]T, 0)
	}

	result := make([]T, len(collection)-n)
	for i := len(collection) - 1 - n; i != 0; i-- {
		result[i] = collection[i]
	}

	return result
}

//DropRightWhile drops elements from the end of a slice or array while the predicate returns true.
func DropRightWhile[T any](collection []T, predicate func(T) bool) []T {
Repository: samber/lo
File: try.go (Go)

Code before:
package lo

func Try(callback func() error) (err bool) {
	err = true

	defer func() {
		if r := recover(); r != nil {
			err = false
		}
	}()

	if callback() != nil {
		err = false
	}

	return
}

func TryWithErrorValue(callback func() error) (err bool, errorValue any) {
	err = true

	defer func() {
		if r := recover(); r != nil {
			err = false
			errorValue = r
		}
	}()

	if errorValue = callback(); errorValue != nil {
		err = false
	}

	return
}

func TryCatch(callback func() error, catch func()) {
	if !Try(callback) {
		catch()
	}
}

func TryCatchWithErrorValue(callback func() error, catch func(any)) {
	if err, val := TryWithErrorValue(callback); !err {
		catch(val)

Review comment (suggestion):
I would rather use the following prototype, more respectful of go standards:

```go
func TryWithErrorValue(callback func() error) (errorValue any, ok bool) {
```

(reversed order of returned value)

Code after:
package lo

func Try(callback func() error) (ok bool) {
	ok = true

	defer func() {
		if r := recover(); r != nil {
			ok = false
		}
	}()

	err := callback()
	if err != nil {
		ok = false
	}

	return
}

func Try2[T any](callback func() (T, error)) bool {
	return Try(func() error {
		_, err := callback()
		return err
	})
}

func Try3[T, R any](callback func() (T, R, error)) bool {
	return Try(func() error {
		_, _, err := callback()
		return err
	})
}

func Try4[T, R, S any](callback func() (T, R, S, error)) bool {
	return Try(func() error {
		_, _, _, err := callback()
		return err
	})
}

func Try5[T, R, S, Q any](callback func() (T, R, S, Q, error)) bool {
	return Try(func() error {
		_, _, _, _, err := callback()
		return err
Repository: samber/lo
File: util.go (Go)

Code before:
package lo

// Range creates an array of numbers (positive and/or negative) with given length.
func Range(elementNum int) []int {
	if elementNum >= 0 {
		result := make([]int, elementNum)
		for i := 0; i < elementNum; i++ {
			result[i] = i
		}
		return result
	}
	result := make([]int, -elementNum)
	for i := 0; i < -elementNum; i++ {
		result[i] = -i
	}
	return result
}

// RangeFrom creates an array of numbers from start with specified length.
func RangeFrom(start, elementNum int) []int {
	if elementNum >= 0 {
		result := make([]int, elementNum)
		for i := 0; i < elementNum; i++ {
			result[i] = i + start
		}
		return result
	}
	result := make([]int, -elementNum)
	for i := 0; i < -elementNum; i++ {
		result[i] = start - i

Review comment (suggestion):
Range can be simplified into:

```go
func Range(start, elementNum int) []int {
	result := make([]int, If(elementNum < 0, -elementNum).Else(elementNum))
	it := If(start <= elementNum, 1).Else(-1)

	for j, i := 0, start; i != elementNum; j, i = j+1, i+it {
		result[j] = i + start
	}

	return result
}
```

Code after:
package lo

import "golang.org/x/exp/constraints"

// Range creates an array of numbers (positive and/or negative) with given length.
func Range(elementNum int) []int {
	length := If(elementNum < 0, -elementNum).Else(elementNum)
	result := make([]int, length)
	step := If(elementNum < 0, -1).Else(1)
	for i, j := 0, 0; i < length; i, j = i+1, j+step {
		result[i] = j
	}
	return result
}

// RangeFrom creates an array of numbers from start with specified length.
func RangeFrom[T constraints.Integer | constraints.Float](start T, elementNum int) []T {
	length := If(elementNum < 0, -elementNum).Else(elementNum)
	result := make([]T, length)
	step := If(elementNum < 0, -1).Else(1)
	for i, j := 0, start; i < length; i, j = i+1, j+T(step) {
		result[i] = j
	}
	return result
}

// RangeWithSteps creates an array of numbers (positive and/or negative) progressing from start up to, but not including end.
// step set to zero will return empty array.
func RangeWithSteps[T constraints.Integer | constraints.Float](start, end, step T) []T {
	result := []T{}
Repository: samber/lo
File: slice.go (Go)

Code before:
// Repeat builds a slice with N copies of initial value.
func Repeat[T Clonable[T]](count int, initial T) []T {
	result := make([]T, 0, count)

	for i := 0; i < count; i++ {
		result = append(result, initial.Clone())
	}

	return result
}

// ToMap transforms a slice or an array of structs to a map based on a pivot callback.
func ToMap[K comparable, V any](collection []V, iteratee func(V) K) map[K]V {
	result := make(map[K]V, len(collection))

	for _, v := range collection {
		k := iteratee(v)
		result[k] = v
	}

	return result
}


// Reject - the opposite of Filter, this method returns the elements of collection that predicate does not return truthy for.
func Reject[V any](collection []V, predicate func(V, int) bool) []V {
	result := []V{}

	for i, item := range collection {
		if !predicate(item, i) {
			result = append(result, item)
		}
	}

	return result
}

Review comment (suggestion):
Wouldn't it be better to implement this as not filter? 

So something like:

```go 
notPredicate := func(val V, i int) bool {
    return !predicate(val, i)
}
return Map(collection, notPredicate)
```

Code after:
// Repeat builds a slice with N copies of initial value.
func Repeat[T Clonable[T]](count int, initial T) []T {
	result := make([]T, 0, count)

	for i := 0; i < count; i++ {
		result = append(result, initial.Clone())
	}

	return result
}

// KeyBy transforms a slice or an array of structs to a map based on a pivot callback.
func KeyBy[K comparable, V any](collection []V, iteratee func(V) K) map[K]V {
	result := make(map[K]V, len(collection))

	for _, v := range collection {
		k := iteratee(v)
		result[k] = v
	}

	return result
}

// Reject is the opposite of Filter, this method returns the elements of collection that predicate does not return truthy for.
func Reject[V any](collection []V, predicate func(V, int) bool) []V {
	result := []V{}

	for i, item := range collection {
		if !predicate(item, i) {
			result = append(result, item)
		}
	}

	return result
}
Repository: samber/lo
File: concurrency.go (Go)

Code before:
package lo

// Async executes a function in a goroutine and returns the result in a channel.
func Async[T any](f func() T) chan T {
	ch := make(chan T)
	go func() {
		ch <- f()
	}()
	return ch
}

// Async0 executes a function in a goroutine and returns a channel closed after execution.
func Async0(f func()) chan struct{} {
	ch := make(chan struct{})
	go func() {
		f()
		close(ch)
	}()
	return ch
}

// Async1 executes a function in a goroutine and returns the result in a channel.
func Async1[A any](f func() A) chan A {
	return Async(f)
}


Review comment (suggestion):
Add:

```go
// Async1 is an alias to Async.
```

Code after:
package lo

// Async executes a function in a goroutine and returns the result in a channel.
func Async[A any](f func() A) chan A {
	ch := make(chan A)
	go func() {
		ch <- f()
	}()
	return ch
}

// Async0 executes a function in a goroutine and returns a channel set once the function finishes.
func Async0(f func()) chan struct{} {
	ch := make(chan struct{})
	go func() {
		f()
		ch <- struct{}{}
	}()
	return ch
}

// Async1 is an alias to Async.
func Async1[A any](f func() A) chan A {
	return Async(f)
}

// Async2 has the same behavior as Async, but returns the 2 results as a tuple inside the channel.
func Async2[A any, B any](f func() (A, B)) chan Tuple2[A, B] {
	ch := make(chan Tuple2[A, B])
	go func() {
		ch <- T2(f())
	}()
	return ch
}

// Async3 has the same behavior as Async, but returns the 3 results as a tuple inside the channel.
func Async3[A any, B any, C any](f func() (A, B, C)) chan Tuple3[A, B, C] {
	ch := make(chan Tuple3[A, B, C])
	go func() {
		ch <- T3(f())
	}()
	return ch
}

// Async4 has the same behavior as Async, but returns the 4 results as a tuple inside the channel.
func Async4[A any, B any, C any, D any](f func() (A, B, C, D)) chan Tuple4[A, B, C, D] {
	ch := make(chan Tuple4[A, B, C, D])
Repository: samber/lo
File: intersect.go (Go)

Code before:

// Intersect returns the intersection between collections.
// Play: https://go.dev/play/p/uuElL9X9e58
func Intersect[T comparable, Slice ~[]T](lists ...Slice) Slice {
	result := Slice{}
	if len(lists) == 0 {
		return result
	}
	if len(lists) == 1 {
		return lists[0]
	}
	seen := map[T]struct{}{}

	for _, elem := range lists[0] {
		seen[elem] = struct{}{}
	}

	for _, elem := range lists[len(lists)-1] {
		if _, ok := seen[elem]; ok {
			result = append(result, elem)
		}
	}

	lists[0] = result

	return Intersect(lists[:len(lists)-1]...)
}

// Difference returns the difference between two collections.
// The first value is the collection of elements absent from list2.
// The second value is the collection of elements absent from list1.
// Play: https://go.dev/play/p/pKE-JgzqRpz
func Difference[T comparable, Slice ~[]T](list1, list2 Slice) (Slice, Slice) {
	left := Slice{}
	right := Slice{}

	seenLeft := map[T]struct{}{}
	seenRight := map[T]struct{}{}

	for i := range list1 {
		seenLeft[list1[i]] = struct{}{}
	}

	for i := range list2 {
		seenRight[list2[i]] = struct{}{}
	}

	for i := range list1 {
		if _, ok := seenRight[list1[i]]; !ok {
			left = append(left, list1[i])
		}

Review comment (suggestion):
please don't perform recursion since it will require extra computation

```go
for i := 1; i < len(lists); i++ {
    for j := 0; j < len(lists[i]); j++ {
		if _, ok := seen[lists[i][j]]; !ok {
			delete(seen, lists[i][j])
		}
	}
    if len(seen) == 0 {
        return Slice{}
    }
}

return Keys(seen)
```

Code after:
	}

	return true
}

// NoneBy returns true if the predicate returns true for none of the elements in the collection or if the collection is empty.
// Play: https://go.dev/play/p/O64WZ32H58S
func NoneBy[T any](collection []T, predicate func(item T) bool) bool {
	for i := range collection {
		if predicate(collection[i]) {
			return false
		}
	}

	return true
}

// Intersect returns the intersection between collections.
// Play: https://go.dev/play/p/uuElL9X9e58
func Intersect[T comparable, Slice ~[]T](lists ...Slice) Slice {
	if len(lists) == 0 {
		return Slice{}
	}

	// Create a map to count occurrences of each element across lists
	counts := make(map[T]int)
	for i, list := range lists {
		// Use a set to avoid counting duplicates within a single list
		seen := make(map[T]struct{})
		for _, elem := range list {
			if _, ok := seen[elem]; !ok {
				seen[elem] = struct{}{}
				counts[elem]++
			}
		}
		// Optimization: if at any point the current list is empty, intersection will be empty
		if i > 0 && len(counts) == 0 {
			return []T{}
		}
	}

	// Collect elements that appear in all lists
	result := []T{}
	for elem, c := range counts {
		if c == len(lists) {
			result = append(result, elem)
		}
	}

	return result
Repository: samber/lo
File: string.go (Go)

Code before:

// Substring return part of a string.
func Substring[T ~string](str T, offset int, length uint) T {
	size := len(str)

	if offset < 0 {
		offset = size + offset
		if offset < 0 {
			offset = 0
		}
	}

	if offset > size {
		return Empty[T]()
	}

	if length > uint(size)-uint(offset) {
		length = uint(size - offset)
	}

	return str[offset : offset+int(length)]
}

// ChunkString returns an array of strings split into groups the length of size. If array can't be split evenly,
// the final chunk will be the remaining elements.
func ChunkString(str string, size int) []string {
	if size <= 0 {
		panic("lo.ChunkString: Size parameter must be greater than 0")
	}

	if len(str) == 0 {
		return []string{""}
	}

	if size >= len(str) {
		return []string{str}
	}

	var chunks []string = make([]string, 0, ((len(str)-1)/size)+1)
	currentLen := 0
	currentStart := 0
	for i := range str {
		if currentLen == size {
			chunks = append(chunks, str[currentStart:i])
			currentLen = 0
			currentStart = i
		}
		currentLen++
	}
	chunks = append(chunks, str[currentStart:])
	return chunks

Review comment (suggestion):
I would use the following prototype instead:

```go
func ChunkString[T ~string](str T, size int) []T
```

Code after:

// Substring return part of a string.
func Substring[T ~string](str T, offset int, length uint) T {
	size := len(str)

	if offset < 0 {
		offset = size + offset
		if offset < 0 {
			offset = 0
		}
	}

	if offset > size {
		return Empty[T]()
	}

	if length > uint(size)-uint(offset) {
		length = uint(size - offset)
	}

	return str[offset : offset+int(length)]
}

// ChunkString returns an array of strings split into groups the length of size. If array can't be split evenly,
// the final chunk will be the remaining elements.
func ChunkString[T ~string](str T, size int) []T {
	if size <= 0 {
		panic("lo.ChunkString: Size parameter must be greater than 0")
	}

	if len(str) == 0 {
		return []T{""}
	}

	if size >= len(str) {
		return []T{str}
	}

	var chunks []T = make([]T, 0, ((len(str)-1)/size)+1)
	currentLen := 0
	currentStart := 0
	for i := range str {
		if currentLen == size {
			chunks = append(chunks, str[currentStart:i])
			currentLen = 0
			currentStart = i
		}
		currentLen++
	}
	chunks = append(chunks, str[currentStart:])
	return chunks
Repository: samber/lo
File: parallel/slice_test.go (Go)

Code before:
	"strconv"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestMap(t *testing.T) {
	is := assert.New(t)

	result1 := Map([]int{1, 2, 3, 4}, func(x int, _ int) string {
		return "Hello"
	})
	result2 := Map([]int64{1, 2, 3, 4}, func(x int64, _ int) string {
		return strconv.FormatInt(x, 10)
	})

	is.Equal(len(result1), 4)
	is.Equal(len(result2), 4)
	is.Equal(result1, []string{"Hello", "Hello", "Hello", "Hello"})
	is.Equal(result2, []string{"1", "2", "3", "4"})
}

func TestForEach(t *testing.T) {
	is := assert.New(t)
	
	count := 0
	collection := []int{1, 2, 3, 4}
	ForEach(collection, func(x int, i int) {
		count++
	})
	
	is.Equal(4, count)
}

func TestTimes(t *testing.T) {
	is := assert.New(t)
	
	result1 := Times(3, func(i int) string {
		return strconv.FormatInt(int64(i), 10)
	})

	is.Equal(len(result1), 3)
	is.Equal(result1, []string{"0", "1", "2"})
}

func TestGroupBy(t *testing.T) {
	is := assert.New(t)

	result1 := GroupBy([]int{0, 1, 2, 3, 4, 5}, func(i int) int {
		return i % 3
	})

Review comment (suggestion):
please use 

```go
var counter uint64
atomic.AddUint64(&counter, 1)
```

instead

Code after:
	"strconv"
	"sync/atomic"
	"testing"
	
	"github.com/stretchr/testify/assert"
)

func TestMap(t *testing.T) {
	is := assert.New(t)
	
	result1 := Map([]int{1, 2, 3, 4}, func(x int, _ int) string {
		return "Hello"
	})
	result2 := Map([]int64{1, 2, 3, 4}, func(x int64, _ int) string {
		return strconv.FormatInt(x, 10)
	})
	
	is.Equal(len(result1), 4)
	is.Equal(len(result2), 4)
	is.Equal(result1, []string{"Hello", "Hello", "Hello", "Hello"})
	is.Equal(result2, []string{"1", "2", "3", "4"})
}

func TestForEach(t *testing.T) {
	is := assert.New(t)
	
	var counter uint64
	collection := []int{1, 2, 3, 4}
	ForEach(collection, func(x int, i int) {
		atomic.AddUint64(&counter, 1)
	})
	
	is.Equal(uint64(4), atomic.LoadUint64(&counter))
}

func TestTimes(t *testing.T) {
	is := assert.New(t)
	
	result1 := Times(3, func(i int) string {
		return strconv.FormatInt(int64(i), 10)
	})
	
	is.Equal(len(result1), 3)
	is.Equal(result1, []string{"0", "1", "2"})
}

func TestGroupBy(t *testing.T) {
	is := assert.New(t)
	
	result1 := GroupBy([]int{0, 1, 2, 3, 4, 5}, func(i int) int {
		return i % 3