00001 #include "PostlistWriter.hpp"
00002 #include "System.hpp"
00003
00004 namespace aitools {
00005 namespace invertedindex {
00006
00007 PostlistWriter::PostlistWriter()
00008 : file_(NULL)
00009 {}
00010
00011 PostlistWriter::PostlistWriter(const bfs::path& path)
00012 throw (std::invalid_argument)
00013 : file_(NULL)
00014 {
00015 open(path);
00016 }
00017
00018 PostlistWriter::~PostlistWriter()
00019 {
00020 close();
00021 }
00022
00023 void
00024 PostlistWriter::close()
00025 {
00026 if (is_open())
00027 {
00028 path_ = bfs::path();
00029 System::fclose(file_);
00030 file_ = NULL;
00031 }
00032 }
00033
00034 bool
00035 PostlistWriter::is_open() const
00036 {
00037 return file_ != NULL;
00038 }
00039
00040 void
00041 PostlistWriter::open(const bfs::path& path)
00042 throw (std::runtime_error, std::invalid_argument)
00043 {
00044 if (is_open())
00045 {
00046 Exception::throw_runtime_error("File already open");
00047 }
00048 file_ = System::fopen(path, "wb");
00049 path_ = path;
00050 }
00051
00052 const bfs::path&
00053 PostlistWriter::path() const
00054 {
00055 return path_;
00056 }
00057
00058 void
00059 PostlistWriter::write(Iterator::SharedPointer iterator)
00060 {
00061 assert(iterator);
00062 iterator->rewind();
00063 System::fwrite((char*)&iterator->header(),
00064 Iterator::sizeof_header, 1, file_);
00065 if (!iterator->value_sizes().empty())
00066 {
00067 System::fwrite((char*)iterator->value_sizes().data(),
00068 sizeof(iterator->value_sizes().front()),
00069 iterator->value_sizes().size(), file_);
00070 }
00071 do
00072 {
00073 System::fwrite((char*)iterator->chunk().buffer->data(), 1,
00074 iterator->chunk().buffer->size(), file_);
00075 }
00076 while (iterator->swap());
00077 }
00078
00079 bool
00080 PostlistWriter::ready() const
00081 {
00082 return is_open() && std::feof(file_) == 0;
00083 }
00084
00085 uint64_t
00086 PostlistWriter::tell()
00087 {
00088 return is_open() ? System::ftell(file_) : 0;
00089 }
00090
00091 }
00092 }