1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 */
20 package org.apache.directory.api.ldap.model.schema.comparators;
21
22
23 import org.apache.directory.api.ldap.model.schema.LdapComparator;
24 import org.apache.directory.api.util.Strings;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28
29 /**
30 * A comparator for byte[]s.
31 *
32 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
33 */
34 public class ByteArrayComparator extends LdapComparator<byte[]>
35 {
36 /** The serial version UID */
37 private static final long serialVersionUID = 2L;
38
39 /** A logger for this class */
40 private static final Logger LOG = LoggerFactory.getLogger( ByteArrayComparator.class );
41
42
43 /**
44 * The ByteArrayComparator constructor. Its OID is the OctetStringMatch matching
45 * rule OID.
46 *
47 * @param oid The Comparator's OID
48 */
49 public ByteArrayComparator( String oid )
50 {
51 super( oid );
52 }
53
54
55 /**
56 * {@inheritDoc}
57 */
58 public int compare( byte[] b1, byte[] b2 )
59 {
60 LOG.debug( "comparing OctetString objects '{}' with '{}'",
61 Strings.dumpBytes( b1 ), Strings.dumpBytes( b2 ) );
62
63 // -------------------------------------------------------------------
64 // Handle some basis cases
65 // -------------------------------------------------------------------
66
67 if ( b1 == null )
68 {
69 return ( b2 == null ) ? 0 : -1;
70 }
71
72 if ( b2 == null )
73 {
74 return 1;
75 }
76
77 if ( b1.length == b2.length )
78 {
79 for ( int i = 0; i < b1.length; i++ )
80 {
81 if ( b1[i] > b2[i] )
82 {
83 return 1;
84 }
85 else if ( b1[i] < b2[i] )
86 {
87 return -1;
88 }
89 }
90
91 return 0;
92 }
93
94 int minLength = Math.min( b1.length, b2.length );
95
96 for ( int i = 0; i < minLength; i++ )
97 {
98 if ( b1[i] > b2[i] )
99 {
100 return 1;
101 }
102 else if ( b1[i] < b2[i] )
103 {
104 return -1;
105 }
106 }
107
108 // b2 is longer w/ b1 as prefix
109 if ( b1.length == minLength )
110 {
111 return -1;
112 }
113
114 // b1 is longer w/ b2 as prefix
115 if ( b2.length == minLength )
116 {
117 return 1;
118 }
119
120 return 0;
121 }
122 }