3 * Copyright 1998-1999 The OpenLDAP Foundation, All Rights Reserved.
4 * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
7 * Copyright (c) 1994 Regents of the University of Michigan.
10 * Redistribution and use in source and binary forms are permitted
11 * provided that this notice is preserved and that due credit is given
12 * to the University of Michigan at Ann Arbor. The name of the University
13 * may not be used to endorse or promote products derived from this
14 * software without specific prior written permission. This software
15 * is provided ``as is'' without express or implied warranty.
17 * sort.c: LDAP library entry and value sort routines
23 #include <ac/stdlib.h>
26 #include <ac/string.h>
35 int (*et_cmp_fn) LDAP_P((const char *a, const char *b));
38 static int et_cmp LDAP_P(( const void *aa, const void *bb));
47 return( strcasecmp( *(char *const *)a, *(char *const *)b ) );
57 const struct entrything *a = (const struct entrything *)aa;
58 const struct entrything *b = (const struct entrything *)bb;
60 if ( a->et_vals == NULL && b->et_vals == NULL )
62 if ( a->et_vals == NULL )
64 if ( b->et_vals == NULL )
67 for ( i = 0; a->et_vals[i] && b->et_vals[i]; i++ ) {
68 if ( (rc = a->et_cmp_fn( a->et_vals[i], b->et_vals[i] )) != 0 ) {
73 if ( a->et_vals[i] == NULL && b->et_vals[i] == NULL )
75 if ( a->et_vals[i] == NULL )
84 LDAP_CONST char *attr, /* NULL => sort by DN */
85 int (*cmp) (LDAP_CONST char *, LDAP_CONST char *)
89 struct entrything *et;
90 LDAPMessage *e, *last;
93 count = ldap_count_entries( ld, *chain );
98 ld->ld_errno = LDAP_PARAM_ERROR;
102 } else if ( count < 2 ) {
103 /* zero or one entries -- already sorted! */
107 if ( (et = (struct entrything *) LDAP_MALLOC( count *
108 sizeof(struct entrything) )) == NULL ) {
109 ld->ld_errno = LDAP_NO_MEMORY;
114 for ( i = 0; i < count; i++ ) {
115 et[i].et_cmp_fn = cmp;
117 if ( attr == NULL ) {
120 dn = ldap_get_dn( ld, e );
121 et[i].et_vals = ldap_explode_dn( dn, 1 );
124 et[i].et_vals = ldap_get_values( ld, e, attr );
131 qsort( et, count, sizeof(struct entrything), et_cmp );
134 for ( i = 0; i < count; i++ ) {
136 ep = &(*ep)->lm_chain;
138 ldap_value_free( et[i].et_vals );
141 LDAP_FREE( (char *) et );
150 int (*cmp) (const void *, const void *)
155 for ( nel = 0; vals[nel] != NULL; nel++ )
158 qsort( vals, nel, sizeof(char *), cmp );