aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/core/basetypes/MCDataStreamDecoder.cpp
blob: 3b24c56e6304c3611d78f94800d3aaf93dc14983 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "MCDataStreamDecoder.h"

#include "MCString.h"
#include "MCUtils.h"
#include "MCDataDecoderUtils.h"

using namespace mailcore;

DataStreamDecoder::DataStreamDecoder()
{
    mFilename = NULL;
    mEncoding = Encoding7Bit;
    mRemainingData = NULL;
    mFile = NULL;
}

DataStreamDecoder::~DataStreamDecoder()
{
    MC_SAFE_RELEASE(mRemainingData);
    MC_SAFE_RELEASE(mFilename);
    if (mFile != NULL) {
        fclose(mFile);
        mFile = NULL;
    }
}

void DataStreamDecoder::setEncoding(Encoding encoding)
{
    mEncoding = encoding;
}

void DataStreamDecoder::setFilename(String * filename)
{
    MC_SAFE_REPLACE_COPY(String, mFilename, filename);
}

ErrorCode DataStreamDecoder::appendData(Data * data)
{
    Data * dataForDecode;
    if (mRemainingData && mRemainingData->length()) {
        // the data remains from previous append
        dataForDecode = (Data *) MC_SAFE_COPY(mRemainingData);
        dataForDecode->appendData(data);
    } else {
        dataForDecode = (Data *) MC_SAFE_RETAIN(data);
    }

    Data * remainingData = NULL;
    Data * decodedData = MCDecodeData(dataForDecode, mEncoding, true, &remainingData);

    ErrorCode errorCode = appendDecodedData(decodedData);

    if (errorCode == ErrorNone) {
        MC_SAFE_REPLACE_RETAIN(Data, mRemainingData, remainingData);
    }

    MC_SAFE_RELEASE(dataForDecode);
    return errorCode;
}

ErrorCode DataStreamDecoder::flushData()
{
    if (mRemainingData == NULL || mRemainingData->length() == 0) {
        return ErrorNone;
    }

    Data * unused = NULL;
    Data * decodedData = MCDecodeData(mRemainingData, mEncoding, false, &unused);

    ErrorCode errorCode = appendDecodedData(decodedData);

    if (errorCode == ErrorNone) {
        if (mFile != NULL) {
            if (fclose(mFile) != 0) {
                return ErrorFile;
            }
        }

        MC_SAFE_RELEASE(mRemainingData);
    }

    return errorCode;
}

ErrorCode DataStreamDecoder::appendDecodedData(Data * decodedData)
{
    if (mFilename == NULL) {
        return ErrorFile;
    }

    if (decodedData->length() == 0) {
        return ErrorNone;
    }

    if (mFile == NULL) {
        mFile = fopen(mFilename->fileSystemRepresentation(), "wb");

        if (mFile == NULL) {
            return ErrorFile;
        }
    }

    size_t result = fwrite(decodedData->bytes(), decodedData->length(), 1, mFile);
    if (result == 0) {
        return ErrorFile;
    }

    return ErrorNone;
}