summaryrefslogtreecommitdiffstats
path: root/library/cpp/ipreg/reader.cpp
blob: 2e4ae1b178699b8e6c060e02fa03e5888a6458c4 (plain) (blame)
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
#include "reader.h"

#include <util/stream/file.h>

namespace NIPREG {

namespace {
    const TString DASH_FNAME = "-";
}

TReader::TReader(const TString& filename, bool isEmptyData, const TString& dataDelim)
    : OwnedStreamPtr((filename.empty() || filename == DASH_FNAME) ? nullptr : new TFileInput(filename))
    , Stream(OwnedStreamPtr ? *OwnedStreamPtr.Get() : Cin)
    , IsEmptyData(isEmptyData)
    , DataDelim(dataDelim)
{
}

TReader::TReader(IInputStream& stream, bool isEmptyData, const TString& dataDelim)
    : Stream(stream)
    , IsEmptyData(isEmptyData)
    , DataDelim(dataDelim)
{
}

bool TReader::Next() {
    TString line;
    if (!Stream.ReadLine(line))
        return false;

    CurrentEntry = TRange::BuildRange(line, IsEmptyData, DataDelim);
    if (CurrentEntry.Data.empty()) {
        if (!IsEmptyData) {
            throw yexception() << "empty data part detected for [" << line << "]";
        }
        CurrentEntry.Data = "";
    }
    return true;
}

TReverseByLastIpReader::TReverseByLastIpReader(const TString& filename, bool isEmptyData, const TString& dataDelim)
    : TParent(filename, isEmptyData, dataDelim)
{
    Valid = TParent::Next();
}

TReverseByLastIpReader::TReverseByLastIpReader(IInputStream& stream, bool isEmptyData, const TString& dataDelim)
    : TParent(stream, isEmptyData, dataDelim)
{
    Valid = TParent::Next();
}

bool TReverseByLastIpReader::Next() {
    if (!CurrentEntries.empty()) {
        CurrentEntries.pop_back();
    }

    if (CurrentEntries.empty()) {
        return PrepareNextEntries();
    } else {
        return true;
    }
}

const TGenericEntry& TReverseByLastIpReader::Get() const {
    return CurrentEntries.back();
}

bool TReverseByLastIpReader::PrepareNextEntries() {
    if (!Valid) {
        return false;
    }

    do {
        CurrentEntries.push_back(TParent::Get());
        Valid = TParent::Next();
    } while (Valid && TParent::Get().First == CurrentEntries.back().First);

    return true;
}

} // NIPREG