Ruby: compar.c Source File

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

compar.c
1/**********************************************************************
2
3 compar.c -
4
5 $Author$
6 created at: Thu Aug 26 14:39:48 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "id.h"
13#include "internal.h"
14#include "internal/compar.h"
15#include "internal/error.h"
16#include "internal/vm.h"
17#include "ruby/ruby.h"
18
19 VALUE rb_mComparable;
20
21static VALUE
22rb_cmp(VALUE x, VALUE y)
23{
24 return rb_funcallv(x, idCmp, 1, &y);
25}
26
27void
28rb_cmperr(VALUE x, VALUE y)
29{
30 VALUE classname;
31
32 if (SPECIAL_CONST_P(y) || BUILTIN_TYPE(y) == T_FLOAT) {
33 classname = rb_inspect(y);
34 }
35 else {
36 classname = rb_obj_class(y);
37 }
38 rb_raise(rb_eArgError, "comparison of %"PRIsVALUE" with %"PRIsVALUE" failed",
39 rb_obj_class(x), classname);
40}
41
42static VALUE
43invcmp_recursive(VALUE x, VALUE y, int recursive)
44{
45 if (recursive) return Qnil;
46 return rb_cmp(y, x);
47}
48
49 VALUE
50rb_invcmp(VALUE x, VALUE y)
51{
52 VALUE invcmp = rb_exec_recursive(invcmp_recursive, x, y);
53 if (NIL_OR_UNDEF_P(invcmp)) {
54 return Qnil;
55 }
56 else {
57 int result = -rb_cmpint(invcmp, x, y);
58 return INT2FIX(result);
59 }
60}
61
62static VALUE
63cmp_eq_recursive(VALUE arg1, VALUE arg2, int recursive)
64{
65 if (recursive) return Qnil;
66 return rb_cmp(arg1, arg2);
67}
68
69/*
70 * call-seq:
71 * obj == other -> true or false
72 *
73 * Compares two objects based on the receiver's <code><=></code>
74 * method, returning true if it returns 0. Also returns true if
75 * _obj_ and _other_ are the same object.
76 */
77
78static VALUE
79cmp_equal(VALUE x, VALUE y)
80{
81 VALUE c;
82 if (x == y) return Qtrue;
83
84 c = rb_exec_recursive_paired_outer(cmp_eq_recursive, x, y, y);
85
86 if (NIL_P(c)) return Qfalse;
87 return RBOOL(rb_cmpint(c, x, y) == 0);
88}
89
90static int
91cmpint(VALUE x, VALUE y)
92{
93 return rb_cmpint(rb_cmp(x, y), x, y);
94}
95
96/*
97 * call-seq:
98 * obj > other -> true or false
99 *
100 * Compares two objects based on the receiver's <code><=></code>
101 * method, returning true if it returns a value greater than 0.
102 */
103
104static VALUE
105cmp_gt(VALUE x, VALUE y)
106{
107 return RBOOL(cmpint(x, y) > 0);
108}
109
110/*
111 * call-seq:
112 * obj >= other -> true or false
113 *
114 * Compares two objects based on the receiver's <code><=></code>
115 * method, returning true if it returns a value greater than or equal to 0.
116 */
117
118static VALUE
119cmp_ge(VALUE x, VALUE y)
120{
121 return RBOOL(cmpint(x, y) >= 0);
122}
123
124/*
125 * call-seq:
126 * obj < other -> true or false
127 *
128 * Compares two objects based on the receiver's <code><=></code>
129 * method, returning true if it returns a value less than 0.
130 */
131
132static VALUE
133cmp_lt(VALUE x, VALUE y)
134{
135 return RBOOL(cmpint(x, y) < 0);
136}
137
138/*
139 * call-seq:
140 * obj <= other -> true or false
141 *
142 * Compares two objects based on the receiver's <code><=></code>
143 * method, returning true if it returns a value less than or equal to 0.
144 */
145
146static VALUE
147cmp_le(VALUE x, VALUE y)
148{
149 return RBOOL(cmpint(x, y) <= 0);
150}
151
152/*
153 * call-seq:
154 * obj.between?(min, max) -> true or false
155 *
156 * Returns <code>false</code> if _obj_ <code><=></code> _min_ is less
157 * than zero or if _obj_ <code><=></code> _max_ is greater than zero,
158 * <code>true</code> otherwise.
159 *
160 * 3.between?(1, 5) #=> true
161 * 6.between?(1, 5) #=> false
162 * 'cat'.between?('ant', 'dog') #=> true
163 * 'gnu'.between?('ant', 'dog') #=> false
164 *
165 */
166
167static VALUE
168cmp_between(VALUE x, VALUE min, VALUE max)
169{
170 return RBOOL((cmpint(x, min) >= 0 && cmpint(x, max) <= 0));
171}
172
173/*
174 * call-seq:
175 * obj.clamp(min, max) -> obj
176 * obj.clamp(range) -> obj
177 *
178 * In <code>(min, max)</code> form, returns _min_ if _obj_
179 * <code><=></code> _min_ is less than zero, _max_ if _obj_
180 * <code><=></code> _max_ is greater than zero, and _obj_
181 * otherwise.
182 *
183 * 12.clamp(0, 100) #=> 12
184 * 523.clamp(0, 100) #=> 100
185 * -3.123.clamp(0, 100) #=> 0
186 *
187 * 'd'.clamp('a', 'f') #=> 'd'
188 * 'z'.clamp('a', 'f') #=> 'f'
189 *
190 * In <code>(range)</code> form, returns _range.begin_ if _obj_
191 * <code><=></code> _range.begin_ is less than zero, _range.end_
192 * if _obj_ <code><=></code> _range.end_ is greater than zero, and
193 * _obj_ otherwise.
194 *
195 * 12.clamp(0..100) #=> 12
196 * 523.clamp(0..100) #=> 100
197 * -3.123.clamp(0..100) #=> 0
198 *
199 * 'd'.clamp('a'..'f') #=> 'd'
200 * 'z'.clamp('a'..'f') #=> 'f'
201 *
202 * If _range.begin_ is +nil+, it is considered smaller than _obj_,
203 * and if _range.end_ is +nil+, it is considered greater than
204 * _obj_.
205 *
206 * -20.clamp(0..) #=> 0
207 * 523.clamp(..100) #=> 100
208 *
209 * When _range.end_ is excluded and not +nil+, an exception is
210 * raised.
211 *
212 * 100.clamp(0...100) # ArgumentError
213 */
214
215static VALUE
216cmp_clamp(int argc, VALUE *argv, VALUE x)
217{
218 VALUE min, max;
219 int c, excl = 0;
220
221 if (rb_scan_args(argc, argv, "11", &min, &max) == 1) {
222 VALUE range = min;
223 if (!rb_range_values(range, &min, &max, &excl)) {
224 rb_raise(rb_eTypeError, "wrong argument type %s (expected Range)",
225 rb_builtin_class_name(range));
226 }
227 if (!NIL_P(max)) {
228 if (excl) rb_raise(rb_eArgError, "cannot clamp with an exclusive range");
229 }
230 }
231 if (!NIL_P(min) && !NIL_P(max) && cmpint(min, max) > 0) {
232 rb_raise(rb_eArgError, "min argument must be smaller than max argument");
233 }
234
235 if (!NIL_P(min)) {
236 c = cmpint(x, min);
237 if (c == 0) return x;
238 if (c < 0) return min;
239 }
240 if (!NIL_P(max)) {
241 c = cmpint(x, max);
242 if (c > 0) return max;
243 }
244 return x;
245}
246
247/*
248 * The Comparable mixin is used by classes whose objects may be
249 * ordered. The class must define the <code><=></code> operator,
250 * which compares the receiver against another object, returning a
251 * value less than 0, returning 0, or returning a value greater than 0,
252 * depending on whether the receiver is less than, equal to,
253 * or greater than the other object. If the other object is not
254 * comparable then the <code><=></code> operator should return +nil+.
255 * Comparable uses <code><=></code> to implement the conventional
256 * comparison operators (<code><</code>, <code><=</code>,
257 * <code>==</code>, <code>>=</code>, and <code>></code>) and the
258 * method <code>between?</code>.
259 *
260 * class SizeMatters
261 * include Comparable
262 * attr :str
263 * def <=>(other)
264 * str.size <=> other.str.size
265 * end
266 * def initialize(str)
267 * @str = str
268 * end
269 * def inspect
270 * @str
271 * end
272 * end
273 *
274 * s1 = SizeMatters.new("Z")
275 * s2 = SizeMatters.new("YY")
276 * s3 = SizeMatters.new("XXX")
277 * s4 = SizeMatters.new("WWWW")
278 * s5 = SizeMatters.new("VVVVV")
279 *
280 * s1 < s2 #=> true
281 * s4.between?(s1, s3) #=> false
282 * s4.between?(s3, s5) #=> true
283 * [ s3, s2, s5, s4, s1 ].sort #=> [Z, YY, XXX, WWWW, VVVVV]
284 *
285 * == What's Here
286 *
287 * \Module \Comparable provides these methods, all of which use method <tt><=></tt>:
288 *
289 * - #<: Returns whether +self+ is less than the given object.
290 * - #<=: Returns whether +self+ is less than or equal to the given object.
291 * - #==: Returns whether +self+ is equal to the given object.
292 * - #>: Returns whether +self+ is greater than or equal to the given object.
293 * - #>=: Returns whether +self+ is greater than the given object.
294 * - #between?: Returns +true+ if +self+ is between two given objects.
295 * - #clamp: For given objects +min+ and +max+, or range <tt>(min..max)</tt>, returns:
296 *
297 * - +min+ if <tt>(self <=> min) < 0</tt>.
298 * - +max+ if <tt>(self <=> max) > 0</tt>.
299 * - +self+ otherwise.
300 *
301 */
302
303void
304Init_Comparable(void)
305{
306 rb_mComparable = rb_define_module("Comparable");
307 rb_define_method(rb_mComparable, "==", cmp_equal, 1);
308 rb_define_method(rb_mComparable, ">", cmp_gt, 1);
309 rb_define_method(rb_mComparable, ">=", cmp_ge, 1);
310 rb_define_method(rb_mComparable, "<", cmp_lt, 1);
311 rb_define_method(rb_mComparable, "<=", cmp_le, 1);
312 rb_define_method(rb_mComparable, "between?", cmp_between, 2);
313 rb_define_method(rb_mComparable, "clamp", cmp_clamp, -1);
314}
rb_define_method
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition cxxanyargs.hpp:670
rb_define_module
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition class.c:1038
rb_scan_args
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:2579
INT2FIX
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
T_FLOAT
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
SPECIAL_CONST_P
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
Definition special_consts.h:56
Qtrue
#define Qtrue
Old name of RUBY_Qtrue.
Definition special_consts.h:61
Qnil
#define Qnil
Old name of RUBY_Qnil.
Definition special_consts.h:60
Qfalse
#define Qfalse
Old name of RUBY_Qfalse.
Definition special_consts.h:59
NIL_P
#define NIL_P
Old name of RB_NIL_P.
Definition special_consts.h:55
BUILTIN_TYPE
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
rb_raise
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition error.c:3150
rb_eTypeError
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1091
rb_eArgError
VALUE rb_eArgError
ArgumentError exception.
Definition error.c:1092
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:191
rb_inspect
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:601
rb_mComparable
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
rb_range_values
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1490
rb_exec_recursive
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5237
rb_exec_recursive_paired_outer
VALUE rb_exec_recursive_paired_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive_outer(), except it checks for the recursion on the ordered pair of { g...
Definition thread.c:5278
ruby.h
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40