3 * Copyright 1998-2003 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;
95 count = ldap_count_entries( ld, *chain );
100 } else if ( count < 2 ) {
101 /* zero or one entries -- already sorted! */
105 if ( (et = (struct entrything *) LDAP_MALLOC( count *
106 sizeof(struct entrything) )) == NULL ) {
107 ld->ld_errno = LDAP_NO_MEMORY;
112 for ( i = 0; i < count; i++ ) {
113 et[i].et_cmp_fn = cmp;
115 if ( attr == NULL ) {
118 dn = ldap_get_dn( ld, e );
119 et[i].et_vals = ldap_explode_dn( dn, 1 );
122 et[i].et_vals = ldap_get_values( ld, e, attr );
129 qsort( et, count, sizeof(struct entrything), et_cmp );
132 for ( i = 0; i < count; i++ ) {
134 ep = &(*ep)->lm_chain;
136 LDAP_VFREE( et[i].et_vals );
139 LDAP_FREE( (char *) et );
148 int (*cmp) (LDAP_CONST void *, LDAP_CONST void *)
153 for ( nel = 0; vals[nel] != NULL; nel++ )
156 qsort( vals, nel, sizeof(char *), cmp );