1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <stdlib.h>
18 #include <sys/types.h>
19
20 #include <gtest/gtest.h>
21
22 #include "gtest_globals.h"
23
24 #define BUFFER_SIZE 1024
25
cmp_long(const void * l,const void * r)26 static int cmp_long(const void *l, const void *r)
27 {
28
29 return (*(long *)l - *(long *)r);
30 }
31
cmp_int(const void * l,const void * r)32 static int cmp_int(const void *l, const void *r)
33 {
34
35 return (*(int *)l - *(int *)r);
36 }
37
38 #ifndef arc4random_uniform
39 static bool seeded;
40
arc4random_uniform(uint32_t upper_bound)41 u_int32_t arc4random_uniform(uint32_t upper_bound)
42 {
43 if (!seeded) {
44 srandom((int)time(NULL));
45 seeded = true;
46 }
47
48 return (random() % upper_bound);
49 }
50 #endif
51
TEST(qsort_test,long_test)52 TEST(qsort_test, long_test) {
53 long buf[BUFFER_SIZE];
54 long i;
55
56 /* Initialize buffer with known numbers */
57 for (i=0; i<BUFFER_SIZE; i++)
58 buf[i] = i;
59
60 /* Stir 1/4 pairs in the buffer */
61 for (i=0; i<BUFFER_SIZE/4; i++) {
62 u_int32_t pos1, pos2;
63 long t;
64
65 pos1 = arc4random_uniform(BUFFER_SIZE);
66 pos2 = arc4random_uniform(BUFFER_SIZE);
67
68 t = buf[pos1];
69 buf[pos1] = buf[pos2];
70 buf[pos2] = t;
71 }
72
73 /* Sort */
74 qsort(buf, BUFFER_SIZE, sizeof(buf[0]), &cmp_long);
75
76 for (i=0; i<BUFFER_SIZE; i++)
77 EXPECT_EQ(i, buf[i]);
78 }
79
TEST(qsort_test,int_test)80 TEST(qsort_test, int_test) {
81 int buf[BUFFER_SIZE];
82 int i;
83
84 /* Initialize buffer with known numbers */
85 for (i=0; i<BUFFER_SIZE; i++)
86 buf[i] = i;
87
88 /* Stir 1/4 pairs in the buffer */
89 for (i=0; i<BUFFER_SIZE/4; i++) {
90 u_int32_t pos1, pos2;
91 int t;
92
93 pos1 = arc4random_uniform(BUFFER_SIZE);
94 pos2 = arc4random_uniform(BUFFER_SIZE);
95
96 t = buf[pos1];
97 buf[pos1] = buf[pos2];
98 buf[pos2] = t;
99 }
100
101 /* Sort */
102 qsort(buf, BUFFER_SIZE, sizeof(buf[0]), &cmp_int);
103
104 for (i=0; i<BUFFER_SIZE; i++)
105 EXPECT_EQ(i, buf[i]);
106 }
107