1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-24 12:32:21 +00:00

examples/ch2-06-qsort: 调整目录名称, 增加测试

This commit is contained in:
chai2010 2018-04-28 07:41:04 +08:00
parent 245063d26a
commit 7a55d875c4
12 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,26 @@
// Copyright © 2018 ChaiShushan <chaishushan{AT}gmail.com>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
package qsort
import (
"sort"
"testing"
"unsafe"
)
func TestSort(t *testing.T) {
values := []int32{42, 9, 101, 95, 27, 25}
Sort(unsafe.Pointer(&values[0]),
len(values), int(unsafe.Sizeof(values[0])),
t_get_go_qsort_compare(),
)
isSorted := sort.SliceIsSorted(values, func(i, j int) bool {
return values[i] < values[j]
})
if !isSorted {
t.Fatal("should be sorted")
}
}

View File

@ -0,0 +1,21 @@
// Copyright © 2018 ChaiShushan <chaishushan{AT}gmail.com>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
package qsort
//extern int t_go_qsort_compare(void* a, void* b);
import "C"
import (
"unsafe"
)
func t_get_go_qsort_compare() CompareFunc {
return CompareFunc(C.t_go_qsort_compare)
}
//export t_go_qsort_compare
func t_go_qsort_compare(a, b unsafe.Pointer) C.int {
pa, pb := (*C.int)(a), (*C.int)(b)
return C.int(*pa - *pb)
}

View File

@ -0,0 +1,28 @@
// Copyright © 2018 ChaiShushan <chaishushan{AT}gmail.com>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
package qsort
import (
"sort"
"testing"
"unsafe"
)
func TestSort(t *testing.T) {
values := []int32{42, 9, 101, 95, 27, 25}
Sort(unsafe.Pointer(&values[0]), len(values), int(unsafe.Sizeof(values[0])),
func(a, b unsafe.Pointer) int {
pa, pb := (*int32)(a), (*int32)(b)
return int(*pa - *pb)
},
)
isSorted := sort.SliceIsSorted(values, func(i, j int) bool {
return values[i] < values[j]
})
if !isSorted {
t.Fatal("should be sorted")
}
}

View File

@ -0,0 +1,24 @@
// Copyright © 2018 ChaiShushan <chaishushan{AT}gmail.com>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
package qsort
import (
"sort"
"testing"
)
func TestSlice(t *testing.T) {
values := []int32{42, 9, 101, 95, 27, 25}
Slice(values, func(i, j int) bool {
return values[i] < values[j]
})
isSorted := sort.SliceIsSorted(values, func(i, j int) bool {
return values[i] < values[j]
})
if !isSorted {
t.Fatal("should be sorted")
}
}