1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix gen_array_sort() (#8077)

This commit is contained in:
yuyi 2021-01-13 13:12:22 +08:00 committed by GitHub
parent 254df0ca62
commit dd6febf6fa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 2 deletions

View File

@ -254,9 +254,9 @@ fn (mut g Gen) gen_array_sort(node ast.CallExpr) {
// when generating the function as long as the args are named the same.
g.definitions.writeln('int $compare_fn ($styp* a, $styp* b) {')
sym := g.table.get_type_symbol(typ)
if sym.has_method('<') && infix_expr.left.str().len == 1 {
if !is_reverse && sym.has_method('<') && infix_expr.left.str().len == 1 {
g.definitions.writeln('\tif (${styp}__lt(*a, *b)) { return -1; } else { return 1; }}')
} else if sym.has_method('>') && infix_expr.left.str().len == 1 {
} else if is_reverse && sym.has_method('>') && infix_expr.left.str().len == 1 {
g.definitions.writeln('\tif (${styp}__gt(*a, *b)) { return -1; } else { return 1; }}')
} else {
field_type := g.typ(infix_expr.left_type)

View File

@ -11,6 +11,10 @@ fn (p Parent) < (p1 Parent) bool {
return p.name < p1.name
}
fn (p Parent) > (p1 Parent) bool {
return p.name > p1.name
}
fn test_sorting_by_different_criteria_in_same_function() {
mut arr := [
Parent{Child{0.2}, 'def'},
@ -26,4 +30,6 @@ fn test_sorting_by_different_criteria_in_same_function() {
assert arr[0].name == 'xyz'
arr.sort(a < b)
assert arr[0].name == 'abc'
arr.sort(a > b)
assert arr[0].name == 'xyz'
}