function s = int2str(xin)
%MATLAB Code Generation Library Function

%   Copyright 2016-2017 The MathWorks, Inc.

% Limitations:
%
%   1. Input must be a compile-time scalar
%
%   Copyright 2016-2020 The MathWorks, Inc.
%#codegen
coder.internal.prefer_const(xin);
coder.internal.assert(coder.internal.isConstTrue(isscalar(xin)), ...
                      'Coder:toolbox:StringScalarsOnly', class(xin), mfilename);
coder.internal.assert(coder.internal.isBuiltInNumeric(xin) || ischar(xin) || islogical(xin), ...
                      'Coder:toolbox:unsupportedClass', mfilename, class(xin));

% Only work with real portion of x and convert to numeric type if logical or
% char
x = real(xin);

if coder.internal.isConst(x)
    s = coder.const(@feval,'int2str',x);
    return
end

if isfloat(x)
    x = round(x);
    if x == 0
        % Avoid negative zero
        s = '0';
        return
    end
    if isinf(x)
        if x > 0
            s = 'Inf';
        else
            s = '-Inf';
        end
        return
    end
    if isnan(x)
        s = 'NaN';
        return
    end

    % +1 for floor +1 for sign
    bufSize = coder.const(coder.internal.indexInt(floor(log10(realmax(class(x))))+2));

    if x == 0
        ub = ones('like',x);
    else
        % +1 for floor
        ub = floor(log10(abs(x)))+1;
        % +1 for sign
        if x < 0
            ub = ub+1;
        end
    end
    cfmt = '%.0f';
    mlfmt = cfmt;
elseif coder.internal.isaUint(x)
    % +1 for floor
    dbuf = double(intmax(class(x)));
    bufSize = coder.const(coder.internal.indexInt(floor(log10(dbuf))+1));

    if x == 0
        ub = 1;
    else
        dx = double(x);
        % +1 for floor
        ub = floor(log10(dx))+1;
    end
    [cfmt, mlfmt] = getIntegerFormatPrefix('u',class(x));
else
    % +1 for floor +1 for sign
    dbuf = double(intmax(class(x)));
    bufSize = coder.const(coder.internal.indexInt(floor(log10(dbuf)))+2);

    if x == 0
        ub = 1;
    else
        % +1 for floor
        dx = double(x);
        ub = floor(log10(abs(dx)))+1;
        
        % +1 for sign
        if x < 0
            ub = ub+1;
        end
    end
    [cfmt, mlfmt] = getIntegerFormatPrefix('d',class(x));
end
s = coder.internal.printNumToBuffer(x, coder.internal.indexInt(ub), bufSize, cfmt, mlfmt);

%--------------------------------------------------------------------------

function [cfmt, mlfmt] = getIntegerFormatPrefix(fmt,cls)
coder.internal.prefer_const(fmt,cls);
nbits = coder.internal.int_nbits(cls);
sizeArray = [coder.internal.target_csizeof('int'), ...
             coder.internal.target_csizeof('long'), ...
             coder.internal.target_csizeof('long long')];

pfx = coder.internal.getPrintfIntegerFormatPrefix(fmt, nbits, sizeArray, ...
                                                       coder.internal.isPWSEnabled());
cfmt = ['%', pfx, fmt];
mlfmt = ['%', fmt];

%--------------------------------------------------------------------------
