Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

I learnt a clean idea: all read is from the 4-char buffer.

int read4(char *buf);
class Solution {
    int offset;
    int validLen;
    char _buf[4];
    
    void _readBuffer(char *&buf, int &len, int n)
    {
        for (; offset < validLen && len < n; offset++)
        {
            *(buf++) = _buf[offset];
            len++;
        }
    }
public:
    Solution() : offset(0), validLen(0){}
    
    //    Point: all through _buf, as a buffer\cache
    int read(char *buf, int n) {
        int len = 0;
        // read carry over bytes first, if any
        _readBuffer(buf, len, n);
        
        //    main
        while (len < n)
        {
            //  reload cache
            validLen = read4(_buf);    offset = 0;
            
            _readBuffer(buf, len, n);
            
            if (validLen < 4) break;
        }
        return len;
    }
};
posted on 2015-08-24 11:42  Tonix  阅读(157)  评论(0编辑  收藏  举报