function s = eml_rand_cast_double2single(d)
%MATLAB Code Generation Private Function
% Cast a scalar double in (0,1) to a single in (0,1) preventing the case of
% casting a d within single eps of 0 or 1 to an endpoint.  d can also be a
% single in which case it is not cast.  The value is simply adjusted.

%   Copyright 2013 The MathWorks, Inc.
%#codegen
coder.inline('always')
CLS = 'single';
SINGLE_EPS = eps(CLS);
ZERO = zeros(CLS);
ONE = ones(CLS);
TWO = single(2);

% d comes from a uniform generator and must be in (0,1) so this is safe
if (isa(d,'double'))
    s = eml_cast(d,CLS,'spill');
else
    s = d;
end

% If the cast mapped d to an endpoint then adjust to the closest non-boundary
% single value
if (s == ZERO)
    s = realmin(CLS);
elseif (s == ONE)
    s = eml_minus(ONE, eml_rdivide(SINGLE_EPS,TWO,CLS,'spill'), CLS, 'spill');
end

