File: mem_file.cpp

package info (click to toggle)
libstxxl 1.4.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,476 kB
  • sloc: cpp: 45,101; ansic: 4,071; perl: 610; sh: 555; xml: 174; makefile: 18
file content (92 lines) | stat: -rw-r--r-- 2,330 bytes parent folder | download | duplicates (4)
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
83
84
85
86
87
88
89
90
91
92
/***************************************************************************
 *  lib/io/mem_file.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
 *  Copyright (C) 2013-2014 Timo Bingmann <tb@panthema.net>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <cstring>
#include <limits>
#include <cassert>

#include <stxxl/bits/io/mem_file.h>
#include <stxxl/bits/io/iostats.h>

STXXL_BEGIN_NAMESPACE

void mem_file::serve(void* buffer, offset_type offset, size_type bytes,
                     request::request_type type)
{
    scoped_mutex_lock lock(m_mutex);

    if (type == request::READ)
    {
        stats::scoped_read_timer read_timer(bytes);
        memcpy(buffer, m_ptr + offset, bytes);
    }
    else
    {
        stats::scoped_write_timer write_timer(bytes);
        memcpy(m_ptr + offset, buffer, bytes);
    }
}

const char* mem_file::io_type() const
{
    return "memory";
}

mem_file::~mem_file()
{
    free(m_ptr);
    m_ptr = NULL;
}

void mem_file::lock()
{
    // nothing to do
}

file::offset_type mem_file::size()
{
    return m_size;
}

void mem_file::set_size(offset_type newsize)
{
    scoped_mutex_lock lock(m_mutex);
    assert(newsize <= std::numeric_limits<offset_type>::max());

    m_ptr = (char*)realloc(m_ptr, (size_t)newsize);
    m_size = newsize;
}

void mem_file::discard(offset_type offset, offset_type size)
{
    scoped_mutex_lock lock(m_mutex);
#ifndef STXXL_MEMFILE_DONT_CLEAR_FREED_MEMORY
    // overwrite the freed region with uninitialized memory
    STXXL_VERBOSE("discard at " << offset << " len " << size);
    void* uninitialized = malloc(STXXL_BLOCK_ALIGN);
    while (size >= STXXL_BLOCK_ALIGN) {
        memcpy(m_ptr + offset, uninitialized, STXXL_BLOCK_ALIGN);
        offset += STXXL_BLOCK_ALIGN;
        size -= STXXL_BLOCK_ALIGN;
    }
    assert(size <= std::numeric_limits<offset_type>::max());
    if (size > 0)
        memcpy(m_ptr + offset, uninitialized, (size_t)size);
    free(uninitialized);
#else
    STXXL_UNUSED(offset);
    STXXL_UNUSED(size);
#endif
}

STXXL_END_NAMESPACE