Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

infinite loop #7

Open
weoil opened this issue Nov 19, 2024 · 0 comments
Open

infinite loop #7

weoil opened this issue Nov 19, 2024 · 0 comments

Comments

@weoil
Copy link

weoil commented Nov 19, 2024

jsgif/gif.js

Line 52 in 8f57a8d

var lzwDecode = function(minCodeSize, data) {

I encountered an infinite loop issue while using the library. The problematic image is shown below. After making the following changes, the issue was resolved:

var lzwDecode = function (minCodeSize, data) {
        var pos = 0;
        var readCode = function (size) {
            var code = 0;
            for (var i = 0; i < size; i++) {
                if (pos >= data.length * 8) {
                    return null; // 返回 null 以指示读取超出范围
                }
                if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) {
                    code |= 1 << i;
                }
                pos++;
            }
            return code;
        };
    
        var output = [];
        var clearCode = 1 << minCodeSize;
        var eoiCode = clearCode + 1;
        var codeSize = minCodeSize + 1;
        var dict = [];
    
        var clear = function () {
            dict = [];
            codeSize = minCodeSize + 1;
            for (var i = 0; i < clearCode; i++) {
                dict[i] = [i];
            }
            dict[clearCode] = [];
            dict[eoiCode] = null;
        };
    
        var code;
        var last;
    
        while (true) {
            last = code;
            code = readCode(codeSize);
    
            // 检查 code 是否为 null
            if (code === null) {
                break; // 退出循环
            }
    
            if (code === clearCode) {
                clear();
                continue;
            }
            if (code === eoiCode) break;
    
            if (code < dict.length) {
                if (last !== clearCode) {
                    dict.push(dict[last].concat(dict[code][0]));
                }
            } else {
                if (code !== dict.length) throw new Error('Invalid LZW code.');
                dict.push(dict[last].concat(dict[last][0]));
            }
            output.push.apply(output, dict[code]);
    
            if (dict.length === (1 << codeSize) && codeSize < 12) {
                codeSize++;
            }
        }
    
        return output;
    };

1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant