Project

General

Profile

comparable-clamp.diff

nerdinand (Ferdinand Niedermann), 09/02/2015 06:12 PM

View differences:

ChangeLog
1
Thu Jul  9 18:31:49 2015  Ferdinand Niedermann  <nerdinand@nerdinand.com>
2

  
3
  * compar.c (cmp_clamp): Introduce Comparable#clamp [Bug #10594]
4

  
1 5
Thu Jul  9 15:07:12 2015  NAKAMURA Usaku  <usa@ruby-lang.org>
2 6

  
3 7
	* win32/win32.c (waitpid): return immediately if interrupted.
compar.c
173 173
    return Qtrue;
174 174
}
175 175

  
176

  
177
/*
178
 *  call-seq:
179
 *     obj.clamp(min, max) ->  obj
180
 *
181
 * Returns <i>min</i> if <i>obj</i> <code><=></code> <i>min</i> is less
182
 * than zero, <i>max</i> if <i>obj</i> <code><=></code> <i>min</i> is
183
 * greater than zero and <i>obj</i> otherwise.
184
 *
185
 *     12.clamp(0, 100)         #=> 12
186
 *     523.clamp(0, 100)        #=> 100
187
 *     -3.123.clamp(0, 100)     #=> 0
188
 *
189
 *     'd'.clamp('a', 'f')      #=> 'd'
190
 *     'z'.clamp('a', 'f')      #=> 'f'
191
 */
192

  
193
static VALUE
194
cmp_clamp(VALUE x, VALUE min, VALUE max)
195
{
196
    if (RTEST(cmp_gt(min, max))) {
197
        rb_raise(rb_eArgError, "min argument must be smaller than max argument");
198
    }
199

  
200
    if (RTEST(cmp_lt(x, min))) return min;
201
    if (RTEST(cmp_gt(x, max))) return max;
202
    return x;
203
}
204

  
176 205
/*
177 206
 *  The <code>Comparable</code> mixin is used by classes whose objects
178 207
 *  may be ordered. The class must define the <code><=></code> operator,
......
225 254
    rb_define_method(rb_mComparable, "<", cmp_lt, 1);
226 255
    rb_define_method(rb_mComparable, "<=", cmp_le, 1);
227 256
    rb_define_method(rb_mComparable, "between?", cmp_between, 2);
257
    rb_define_method(rb_mComparable, "clamp", cmp_clamp, 2);
228 258

  
229 259
    cmp = rb_intern("<=>");
230 260
}
test/ruby/test_comparable.rb
75 75
    assert_equal(true, @o.between?(0, 0))
76 76
  end
77 77

  
78
  def test_clamp
79
    cmp->(x) do 0 <=> x end
80
    assert_equal(1, @o.clamp(1, 2))
81
    assert_equal(-1, @o.clamp(-2, -1))
82
    assert_equal(0, @o.clamp(-1, 3))
83

  
84
    assert_equal(1, @o.clamp(1, 1))
85
    assert_equal(0, @o.clamp(0, 0))
86

  
87
    assert_raise_with_message(ArgumentError, 'min argument must be smaller than max argument') {
88
      @o.clamp(2, 1)
89
    }
90
   end
91

  
78 92
  def test_err
79 93
    assert_raise(ArgumentError) { 1.0 < nil }
80 94
    assert_raise(ArgumentError) { 1.0 < Object.new }