Stxxl  1.4.0
io/mem_file.cpp
Go to the documentation of this file.
00001 /***************************************************************************
00002  *  io/mem_file.cpp
00003  *
00004  *  Part of the STXXL. See http://stxxl.sourceforge.net
00005  *
00006  *  Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
00007  *
00008  *  Distributed under the Boost Software License, Version 1.0.
00009  *  (See accompanying file LICENSE_1_0.txt or copy at
00010  *  http://www.boost.org/LICENSE_1_0.txt)
00011  **************************************************************************/
00012 
00013 #include <cstring>
00014 
00015 #include <stxxl/bits/io/mem_file.h>
00016 #include <stxxl/bits/io/iostats.h>
00017 
00018 
00019 __STXXL_BEGIN_NAMESPACE
00020 
00021 
00022 void mem_file::serve(const request * req) throw (io_error)
00023 {
00024     assert(req->get_file() == this);
00025     offset_type offset = req->get_offset();
00026     void * buffer = req->get_buffer();
00027     size_type bytes = req->get_size();
00028     request::request_type type = req->get_type();
00029 
00030     if (type == request::READ)
00031     {
00032         stats::scoped_read_timer read_timer(bytes);
00033         memcpy(buffer, ptr + offset, bytes);
00034     }
00035     else
00036     {
00037         stats::scoped_write_timer write_timer(bytes);
00038         memcpy(ptr + offset, buffer, bytes);
00039     }
00040 }
00041 
00042 const char * mem_file::io_type() const
00043 {
00044     return "memory";
00045 }
00046 
00047 mem_file::~mem_file()
00048 {
00049     delete[] ptr;
00050     ptr = NULL;
00051 }
00052 
00053 void mem_file::lock()
00054 {
00055     // nothing to do
00056 }
00057 
00058 file::offset_type mem_file::size()
00059 {
00060     return sz;
00061 }
00062 
00063 void mem_file::set_size(offset_type newsize)
00064 {
00065     assert(ptr == NULL); // no resizing
00066     if (ptr == NULL)
00067         ptr = new char[sz = newsize];
00068 }
00069 
00070 void mem_file::discard(offset_type offset, offset_type size)
00071 {
00072 #ifndef STXXL_MEMFILE_DONT_CLEAR_FREED_MEMORY
00073     // overwrite the freed region with uninitialized memory
00074     STXXL_VERBOSE("discard at " << offset << " len " << size);
00075     void * uninitialized = malloc(BLOCK_ALIGN);
00076     while (size >= BLOCK_ALIGN) {
00077         memcpy(ptr + offset, uninitialized, BLOCK_ALIGN);
00078         offset += BLOCK_ALIGN;
00079         size -= BLOCK_ALIGN;
00080     }
00081     if (size > 0)
00082         memcpy(ptr + offset, uninitialized, size);
00083     free(uninitialized);
00084 #else
00085     STXXL_UNUSED(offset);
00086     STXXL_UNUSED(size);
00087 #endif
00088 }
00089 
00090 __STXXL_END_NAMESPACE
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines