1 /* 2 * Memory region abstractions. 3 * 4 * Copyright (C) 2021 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #include <string.h> 23 #include <stdlib.h> 24 25 #include "region.h" 26 27 28 29 /* Initialise region state, indicating the size, file and position. */ 30 31 RegionState::RegionState(fileid_t fileid, offset_t filepos) 32 : fileid(fileid), filepos(filepos) 33 { 34 } 35 36 void RegionState::fill(fileid_t fileid, offset_t filepos) 37 { 38 this->fileid = fileid; 39 this->filepos = filepos; 40 } 41 42 void RegionState::flush() 43 { 44 fileid = FILEID_INVALID; 45 filepos = 0; 46 } 47 48 49 50 /* Initialise a region having the given 'start' and 'end' addresses, with the 51 'end' being one location beyond the last address in the region. */ 52 53 Region::Region(offset_t start, offset_t end) 54 : start(start), end(end), state(end - start) 55 { 56 /* Content state. */ 57 58 memset((void *) start, 0, end - start); 59 } 60 61 /* Deallocate the region, freeing its memory. */ 62 63 Region::~Region() 64 { 65 free((void *) start); 66 } 67 68 /* Return the size of the region. */ 69 70 offset_t Region::size() 71 { 72 return end - start; 73 } 74 75 /* Debugging methods. */ 76 77 int Region::compare(Region *other) 78 { 79 if (start < other->start) 80 return -1; 81 else if (start > other->start) 82 return 1; 83 else 84 return 0; 85 } 86 87 /* Tag the region with file identifier and position details. */ 88 89 void Region::fill(fileid_t fileid, offset_t filepos) 90 { 91 state.fill(fileid, filepos); 92 } 93 94 /* Remove the file details from the region state. */ 95 96 void Region::flush() 97 { 98 state.flush(); 99 } 100 101 /* Simulation methods. */ 102 103 char *Region::read(offset_t offset) 104 { 105 if (offset < size()) 106 return (char *) start + offset; 107 else 108 return NULL; 109 } 110 111 void Region::write(const char *data, offset_t offset) 112 { 113 size_t length = strlen(data); 114 115 if (offset + length < size()) 116 memcpy((void *) (start + offset), data, length + 1); 117 } 118 119 // vim: tabstop=4 expandtab shiftwidth=4