|
37 | 37 | % License: GPLv3 or 3-clause BSD license, see https://github.com/NeuroJSON/easyh5 for details |
38 | 38 | % |
39 | 39 |
|
40 | | -% Fast path: check first character directly instead of calling isvarname |
| 40 | +% Check first character - use isvarname for the first char check to maintain |
| 41 | +% Octave compatibility (Octave allows underscore as first character) |
41 | 42 | c1 = str(1); |
42 | | -if ~((c1 >= 'a' && c1 <= 'z') || (c1 >= 'A' && c1 <= 'Z')) |
43 | | - % First char is not a letter - need to encode it |
44 | | - if (exist('unicode2native', 'builtin')) |
| 43 | +firstcharvalid = (c1 >= 'a' && c1 <= 'z') || (c1 >= 'A' && c1 <= 'Z'); |
| 44 | + |
| 45 | +% In Octave, underscore is valid as first character; check this case |
| 46 | +if ~firstcharvalid && c1 == '_' |
| 47 | + persistent isaliasaliased |
| 48 | + if isempty(isaliasaliased) |
| 49 | + isaliasaliased = exist('OCTAVE_VERSION', 'builtin') ~= 0; |
| 50 | + end |
| 51 | + if isaliasaliased |
| 52 | + firstcharvalid = true; |
| 53 | + end |
| 54 | +end |
| 55 | + |
| 56 | +if ~firstcharvalid |
| 57 | + % First char is not valid - need to encode it |
| 58 | + if exist('unicode2native', 'builtin') |
45 | 59 | str = sprintf('x0x%s_%s', sprintf('%X', unicode2native(c1)), str(2:end)); |
46 | 60 | else |
47 | 61 | str = sprintf('x0x%X_%s', c1 + 0, str(2:end)); |
|
66 | 80 | end |
67 | 81 |
|
68 | 82 | % Slow path: has invalid characters, need full encoding |
69 | | -if (exist('unicode2native', 'builtin')) |
| 83 | +if exist('unicode2native', 'builtin') |
70 | 84 | str = regexprep(str, '([^0-9A-Za-z_])', '_0x${sprintf(''%X'',unicode2native($1))}_'); |
71 | 85 | else |
72 | 86 | cpos = find(~ismember(str, ['0':'9', 'A':'Z', 'a':'z', '_'])); |
73 | | - if (isempty(cpos)) |
| 87 | + if isempty(cpos) |
74 | 88 | return |
75 | 89 | end |
76 | 90 | str0 = str; |
|
79 | 93 | for i = 1:length(cpos) |
80 | 94 | str = [str str0(pos0(i) + 1:cpos(i) - 1) sprintf('_0x%X_', str0(cpos(i)) + 0)]; |
81 | 95 | end |
82 | | - if (cpos(end) ~= length(str)) |
| 96 | + if cpos(end) ~= length(str) |
83 | 97 | str = [str str0(pos0(end - 1) + 1:pos0(end))]; |
84 | 98 | end |
85 | 99 | end |
0 commit comments