realm-js/src/js_util.hpp

80 lines
2.4 KiB
C++
Raw Permalink Normal View History

2016-02-18 11:59:34 -08:00
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
2015-08-13 09:12:48 -07:00
2015-12-01 14:52:38 -08:00
#pragma once
#include <limits>
2015-12-08 12:37:38 -08:00
#include <sstream>
2015-08-13 09:12:48 -07:00
#include <stdexcept>
2016-03-29 13:36:01 -07:00
#include "shared_realm.hpp"
2015-08-13 09:12:48 -07:00
namespace realm {
namespace js {
2015-08-13 09:12:48 -07:00
template<typename T>
class RealmDelegate;
2015-08-13 09:12:48 -07:00
template<typename T>
static inline RealmDelegate<T> *get_delegate(Realm *realm) {
return static_cast<RealmDelegate<T> *>(realm->m_binding_context.get());
}
2015-12-08 12:37:38 -08:00
template<typename T>
static inline T stot(const std::string &s) {
2015-12-08 12:37:38 -08:00
std::istringstream iss(s);
T value;
iss >> value;
if (iss.fail()) {
throw std::invalid_argument("Cannot convert string '" + s + "'");
}
return value;
}
static inline uint32_t validated_positive_index(std::string string) {
int64_t index = stot<int64_t>(string);
if (index < 0) {
throw std::out_of_range(std::string("Index ") + string + " cannot be less than zero.");
2015-08-13 09:12:48 -07:00
}
if (index > std::numeric_limits<uint32_t>::max()) {
throw std::out_of_range(std::string("Index ") + string + " must be a 32-bit unsigned integer");
2015-08-13 09:12:48 -07:00
}
return static_cast<uint32_t>(index);
2016-03-28 13:21:36 -07:00
}
static inline void validate_argument_count(size_t count, size_t expected, const char *message = nullptr) {
if (count != expected) {
throw std::invalid_argument(message ?: "Invalid arguments");
2016-03-28 13:21:36 -07:00
}
}
static inline void validate_argument_count(size_t count, size_t min, size_t max, const char *message = nullptr) {
if (count < min || count > max) {
throw std::invalid_argument(message ?: "Invalid arguments");
2016-03-28 13:21:36 -07:00
}
}
static inline void validate_argument_count_at_least(size_t count, size_t expected, const char *message = nullptr) {
if (count < expected) {
throw std::invalid_argument(message ?: "Invalid arguments");
}
2016-03-28 13:21:36 -07:00
}
2016-03-29 13:36:01 -07:00
} // js
} // realm