Newer
Older
SLC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
SLC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SLC; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "slc.hh"
#include "history.hh"
History::History() : max_size_(100) {}
/*!
** Add @param s in history if it's non empty.
*/
void History::add(const string &s) {
assert(strchr(s.c_str(), '\n') == 0);
assert(max_size_ > 0);
if (s.empty())
return;
if (!table_.empty() && s == table_.front())
return;
if (table_.size() >= max_size_)
table_.resize(max_size_);
table_.push_front(s);
}
/*!
** Get @param off element in history
**
** @return string associed with @param off in history
*/
const string &History::get(size_t off) const {
assert(max_size_ > 0);
assert(off < table_.size());
t_lines::const_iterator it;
size_t pos;
static string empty;
for (pos = 0, it = table_.begin();
it != table_.end();
++pos, ++it)
if (pos == off)
return *it;
return empty;
}
void History::load(const string &filename) {
ifstream fs;
t_lines::const_iterator it;
char buf[MAX_LINE_SIZE];
fs.open(filename.c_str(), ifstream::in);
if (!fs.is_open())
return;
while (!fs.eof()) {
if (fs.fail())
throw Error(ERR_FILE, "Unable to load history");
fs.getline(buf, MAX_LINE_SIZE);
add(buf);
}
fs.close();
}
void History::save(const string &filename) const {
ofstream fs;
t_lines::const_reverse_iterator rit;
fs.open(filename.c_str(), ostream::out | ostream::trunc);
if (!fs.is_open())
throw Error(ERR_FILE, "Unable to open history file");
for (rit = table_.rbegin(); rit != table_.rend(); ++rit) {
fs.write((*rit).c_str(), (*rit).length());
fs.put('\n');
if (fs.fail())
throw Error(ERR_FILE, "Unable to save history");
}
fs.close();
}
size_t History::size() const {
return table_.size();
}
/*!
** Set the max history size to @param s
*/