memory_segment_local.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (C) 2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include "memory_segment_local.h"
  15. #include <exceptions/exceptions.h>
  16. namespace isc {
  17. namespace util {
  18. void*
  19. MemorySegmentLocal::allocate(size_t size) {
  20. void* ptr = malloc(size);
  21. if (ptr == NULL) {
  22. throw std::bad_alloc();
  23. }
  24. allocated_size_ += size;
  25. return (ptr);
  26. }
  27. void
  28. MemorySegmentLocal::deallocate(void* ptr, size_t size) {
  29. if (ptr == NULL) {
  30. // Return early if NULL is passed to be deallocated (without
  31. // modifying allocated_size, or comparing against it).
  32. return;
  33. }
  34. if (size > allocated_size_) {
  35. isc_throw(OutOfRange, "Invalid size to deallocate: " << size
  36. << "; currently allocated size: " << allocated_size_);
  37. }
  38. allocated_size_ -= size;
  39. free(ptr);
  40. }
  41. bool
  42. MemorySegmentLocal::allMemoryDeallocated() const {
  43. return (allocated_size_ == 0 && named_addrs_.empty());
  44. }
  45. MemorySegment::NamedAddressResult
  46. MemorySegmentLocal::getNamedAddressImpl(const char* name) const {
  47. std::map<std::string, void*>::const_iterator found =
  48. named_addrs_.find(name);
  49. if (found != named_addrs_.end()) {
  50. return (NamedAddressResult(true, found->second));
  51. }
  52. return (NamedAddressResult(false, NULL));
  53. }
  54. bool
  55. MemorySegmentLocal::setNamedAddressImpl(const char* name, void* addr) {
  56. named_addrs_[name] = addr;
  57. return (false);
  58. }
  59. bool
  60. MemorySegmentLocal::clearNamedAddressImpl(const char* name) {
  61. const size_t n_erased = named_addrs_.erase(name);
  62. return (n_erased != 0);
  63. }
  64. } // namespace util
  65. } // namespace isc