Skip to content

Commit 53f9cbf

Browse files
committed
allowed downcast flag when converting types
1 parent 02eb5b0 commit 53f9cbf

File tree

2 files changed

+22
-28
lines changed

2 files changed

+22
-28
lines changed

+file/fillConstructor.m

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@
9797
overridemap(nm) = ['''' props(nm).value ''''];
9898
else
9999
overridemap(nm) =...
100-
sprintf('types.util.correctType(%s, ''%s'')',...
100+
sprintf('types.util.correctType(%s, ''%s'', true)',...
101101
props(nm).value,...
102102
props(nm).dtype);
103103
end

+types/+util/correctType.m

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,30 @@
1-
function val = correctType(val, type)
1+
function val = correctType(val, type, allowDowncast)
22
%CORRECTTYPE upcasts if type is smaller than minimum
33
% Will error if type is simply incompatible
44
% Will throw if casting is impossible
55

66
%check different types and correct
7-
switch (type)
8-
case {'float64' 'float32' 'float'}
9-
if ~isfloat(val)
10-
val = double(val);
11-
end
12-
case 'int'
13-
if ~isinteger(val)
14-
val = int64(val);
15-
end
16-
case 'uint'
17-
if ~isinteger(val)
18-
val = uint64(val);
19-
end
20-
case 'numeric'
21-
if ~isnumeric(val)
22-
val = double(val);
23-
end
24-
case 'logical'
25-
if ~islogical(val)
26-
val = logical(val);
27-
end
7+
8+
if startsWith(type, 'float') && ~isfloat(val)
9+
val = double(val);
10+
elseif startsWith(type, 'int') && ~isinteger(val)
11+
val = int64(val);
12+
elseif startsWith(type, 'uint') && ~isinteger(val)
13+
val = uint64(val);
14+
elseif strcmp(type, 'numeric') && ~isnumeric(val)
15+
val = double(val);
16+
elseif strcmp(type, 'bool') && ~islogical(val)
17+
val = logical(val);
2818
end
2919

3020
%check different types sizes and upcast to meet minimum (if applicable)
31-
if strcmp(type, 'float64') && strcmp(class(val), 'single')
32-
val = double(val);
33-
if (~strcmp(type, 'int') && startsWith(type, 'int')) ||...
21+
if any(strcmp(type, {'float64' 'float32'})
22+
if issingle(val)
23+
val = double(val);
24+
elseif allowDowncast && strcmp(type, 'float32')
25+
val = single(val);
26+
end
27+
elseif (~strcmp(type, 'int') && startsWith(type, 'int')) ||...
3428
(~strcmp(type, 'uint') && startsWith(type, 'uint'))
3529
pattern = 'int%d';
3630
if startsWith(type, 'u')
@@ -39,8 +33,8 @@
3933
typsz = sscanf(type, pattern);
4034
valsz = sscanf(class(val), pattern);
4135

42-
if valsz < typsz
43-
val = eval([type '(val)']);
36+
if valsz < typsz || (nargin > 2 && allowDowncast)
37+
val = eval([type '(val)']);
4438
end
4539
end
4640
end

0 commit comments

Comments
 (0)