#/*
# *  Copyright 2007-2009 hkrn <hikarin@users.sourceforge.jp>
# *
# *  Licensed under the Apache License, Version 2.0 (the "License");
# *  you may not use this file except in compliance with the License.
# *  You may obtain a copy of the License at
# *
# *      http://www.apache.org/licenses/LICENSE-2.0
# *
# *  Unless required by applicable law or agreed to in writing, software
# *  distributed under the License is distributed on an "AS IS" BASIS,
# *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# *  See the License for the specific language governing permissions and
# *  limitations under the License.
# */
#
# $Id: Qdepot.pm 1826 2009-04-08 15:23:25Z hikarin $
#

package Img0ch::Maple::Qdepot;

use strict;
use Depot qw();

sub new {
    my ( $iClass, $iKernel, $path ) = @_;
    bless {
        __depot    => undef,
        __filename => $path,
        __kernel   => $iKernel,
    }, $iClass;
}

sub load {
    my ( $iRepos, $path ) = @_;
    my $repos = Depot->new(
        ( $path || $iRepos->{__filename} ),
        Depot::OWRITER() | Depot::OCREAT()
    ) or $iRepos->{__kernel}->throw_exception($Depot::errmsg);

    $repos->filter_fetch_key( sub   {s/\0\z//xms} );
    $repos->filter_store_key( sub   { $_ .= "\0" } );
    $repos->filter_fetch_value( sub {s/\0\z//xms} );
    $repos->filter_store_value( sub { $_ .= "\0" } );
    $iRepos->{__depot} = $repos;
    return 1;
}

sub save {1}

sub set {
    my ( $iRepos, $key, $value ) = @_;
    $iRepos->{__depot}->put( $key, $value )
        or $iRepos->{__kernel}->throw_exception($Depot::errmsg);
    return;
}

*set_binary = \&set;

sub get {
    my ( $iRepos, $key ) = @_;
    my $repos = $iRepos->{__depot};
    $repos->vsiz($key) >= 0 or return '';
    my $value = $repos->get($key)
        or $iRepos->{__kernel}->throw_exception($Depot::errmsg);
    return $value;
}

*get_binary = \&get;

sub decode_binary { shift; return $_[0] }

sub is_binary_safe {1}

sub get_int { Img0ch::Kernel::intval( $_[0]->get( $_[1] ) ) }

sub remove {
    my ( $iRepos, $key ) = @_;
    my $oldvalue = $iRepos->get($key);
    $iRepos->{__depot}->out($key)
        or $iRepos->{__kernel}->throw_exception($Depot::errmsg);
    return $oldvalue;
}

sub iterate {
    my ( $iRepos, $code_ref, @args ) = @_;
    my $iKernel = $iRepos->{__kernel};
    my $repos   = $iRepos->{__depot};

    $repos->iterinit();
    while ( my $key = $repos->iternext() ) {
        my $value = $repos->get($key)
            or $iKernel->throw_exception($Depot::errmsg);
        my $status = $code_ref->( $key, \$value, @args );
        if ( $status > 0 ) {
            $iRepos->set( $key, $value );
        }
        elsif ( $status < 0 ) {
            $iRepos->remove($key);
        }
    }
    return 1;
}

*iterate_binary = \&iterate;

1;
__END__
