From d957239a1b2425d810711b8e8a2bd3f1bd1434cb Mon Sep 17 00:00:00 2001 From: Denis Ryabov Date: Wed, 23 Jul 2014 10:49:39 +0400 Subject: [PATCH] binary db (8x smaller) --- habr_twister.php | 4 ++-- habrrssdb.php | 30 ------------------------------ rssdb.php | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 32 deletions(-) delete mode 100644 habrrssdb.php create mode 100644 rssdb.php diff --git a/habr_twister.php b/habr_twister.php index c635d35..04fce8a 100644 --- a/habr_twister.php +++ b/habr_twister.php @@ -16,8 +16,8 @@ $twister = new TwisterPost('habr_ru'); // set user name $twister->twisterPath = '.' . DIRECTORY_SEPARATOR . 'twister-win32-bundle' . DIRECTORY_SEPARATOR; // Initialise RSS database -require_once 'habrrssdb.php'; -$db = new HabrRSSDb('habr_db.dat'); +require_once 'rssdb.php'; +$db = new RSSDb('habr_ru.dat'); foreach ($rss->channel->item as $item) { $link = (string)$item->link; diff --git a/habrrssdb.php b/habrrssdb.php deleted file mode 100644 index f58e180..0000000 --- a/habrrssdb.php +++ /dev/null @@ -1,30 +0,0 @@ -hDatabase = fopen($dbFile, 'r+'); - } - - public function __destruct() - { - fclose($this->hDatabase); - } - - public function isPublished($id) - { - fseek($this->hDatabase, $id); - $status = fgetc($this->hDatabase); - return $status === '1'; - } - - public function setPublished($id) - { - fseek($this->hDatabase, $id); - fwrite($this->hDatabase, '1'); - } -} diff --git a/rssdb.php b/rssdb.php new file mode 100644 index 0000000..9cc5261 --- /dev/null +++ b/rssdb.php @@ -0,0 +1,41 @@ +1, 2, 4, 8, 16, 32, 64, 128); + + public function __construct($dbFile, $minId = 0) + { + fclose(fopen($dbFile, 'a')); // create file if not exists + $this->hDatabase = fopen($dbFile, 'r+'); + $this->minId = $minId; + } + + public function __destruct() + { + fclose($this->hDatabase); + } + + public function isPublished($id) + { + $id -= $this->minId; + if ($id < 0) return true; + $pos = intval($id/8); + fseek($this->hDatabase, $pos); + $status = ord(fgetc($this->hDatabase)); + return (bool)($status & $this->bits[$id % 8]); + } + + public function setPublished($id) + { + $id -= $this->minId; + if ($id < 0) return; + $pos = intval($id/8); + fseek($this->hDatabase, $pos); + $status = ord(fgetc($this->hDatabase)); + fseek($this->hDatabase, $pos); + fwrite($this->hDatabase, chr($status | $this->bits[$id % 8])); + } +}