xref: /aosp_15_r20/external/webrtc/sdk/android/native_api/jni/jni_int_wrapper.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2018 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 // Originally this class is from Chromium.
12 // https://cs.chromium.org/chromium/src/base/android/jni_int_wrapper.h.
13 
14 #ifndef SDK_ANDROID_NATIVE_API_JNI_JNI_INT_WRAPPER_H_
15 #define SDK_ANDROID_NATIVE_API_JNI_JNI_INT_WRAPPER_H_
16 
17 #include <jni.h>
18 
19 #include <cstdint>
20 
21 // Wrapper used to receive int when calling Java from native. The wrapper
22 // disallows automatic conversion of anything besides int32_t to a jint.
23 // Checking is only done in debugging builds.
24 
25 #ifdef NDEBUG
26 
27 typedef jint JniIntWrapper;
28 
29 // This inline is sufficiently trivial that it does not change the
30 // final code generated by g++.
as_jint(JniIntWrapper wrapper)31 inline jint as_jint(JniIntWrapper wrapper) {
32   return wrapper;
33 }
34 
35 #else
36 
37 class JniIntWrapper {
38  public:
JniIntWrapper()39   JniIntWrapper() : i_(0) {}
JniIntWrapper(int32_t i)40   JniIntWrapper(int32_t i) : i_(i) {}  // NOLINT(runtime/explicit)
JniIntWrapper(const JniIntWrapper & ji)41   explicit JniIntWrapper(const JniIntWrapper& ji) : i_(ji.i_) {}
42 
as_jint()43   jint as_jint() const { return i_; }
44 
45   // If you get an "invokes a deleted function" error at the lines below it is
46   // because you used an implicit conversion to convert e.g. a long to an
47   // int32_t when calling Java. We disallow this. If you want a lossy
48   // conversion, please use an explicit conversion in your C++ code.
49   JniIntWrapper(uint32_t) = delete;  // NOLINT(runtime/explicit)
50   JniIntWrapper(uint64_t) = delete;  // NOLINT(runtime/explicit)
51   JniIntWrapper(int64_t) = delete;   // NOLINT(runtime/explicit)
52 
53  private:
54   const jint i_;
55 };
56 
as_jint(const JniIntWrapper & wrapper)57 inline jint as_jint(const JniIntWrapper& wrapper) {
58   return wrapper.as_jint();
59 }
60 
61 #endif  // NDEBUG
62 
63 #endif  // SDK_ANDROID_NATIVE_API_JNI_JNI_INT_WRAPPER_H_
64