datasketches-cpp
memory_operations.hpp
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #ifndef _MEMORY_OPERATIONS_HPP_
21 #define _MEMORY_OPERATIONS_HPP_
22 
23 #include <memory>
24 #include <exception>
25 #include <iostream>
26 #include <string>
27 #include <cstring>
28 
29 namespace datasketches {
30 
31 static inline void ensure_minimum_memory(size_t bytes_available, size_t min_needed) {
32  if (bytes_available < min_needed) {
33  throw std::out_of_range("Insufficient buffer size detected: bytes available "
34  + std::to_string(bytes_available) + ", minimum needed " + std::to_string(min_needed));
35  }
36 }
37 
38 static inline void check_memory_size(size_t requested_index, size_t capacity) {
39  if (requested_index > capacity) {
40  throw std::out_of_range("Attempt to access memory beyond limits: requested index "
41  + std::to_string(requested_index) + ", capacity " + std::to_string(capacity));
42  }
43 }
44 
45 // note: size is in bytes, not items
46 static inline size_t copy_from_mem(const void* src, void* dst, size_t size) {
47  memcpy(dst, src, size);
48  return size;
49 }
50 
51 // note: size is in bytes, not items
52 static inline size_t copy_to_mem(const void* src, void* dst, size_t size) {
53  memcpy(dst, src, size);
54  return size;
55 }
56 
57 template<typename T>
58 static inline size_t copy_from_mem(const void* src, T& item) {
59  memcpy(&item, src, sizeof(T));
60  return sizeof(T);
61 }
62 
63 template<typename T>
64 static inline size_t copy_to_mem(T item, void* dst) {
65  memcpy(dst, &item, sizeof(T));
66  return sizeof(T);
67 }
68 
69 } // namespace
70 
71 #endif // _MEMORY_OPERATIONS_HPP_
DataSketches namespace.
Definition: binomial_bounds.hpp:38