1 // Copyright 2016 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef COMPONENTS_CRONET_ANDROID_IO_BUFFER_WITH_BYTE_BUFFER_H_ 6 #define COMPONENTS_CRONET_ANDROID_IO_BUFFER_WITH_BYTE_BUFFER_H_ 7 8 #include <jni.h> 9 10 #include "base/android/scoped_java_ref.h" 11 #include "net/base/io_buffer.h" 12 13 namespace cronet { 14 15 // net::WrappedIOBuffer subclass for a buffer owned by a Java ByteBuffer. Keeps 16 // the ByteBuffer alive until destroyed. Uses WrappedIOBuffer because data() is 17 // owned by the embedder. 18 class IOBufferWithByteBuffer : public net::WrappedIOBuffer { 19 public: 20 // Creates a buffer wrapping the Java ByteBuffer |jbyte_buffer|. 21 // |byte_buffer_data| points to the memory backed by the ByteBuffer, and 22 // |position| is the index of the first byte of data inside of the buffer. 23 // |limit| is the the index of the first element that should not be read or 24 // written, preserved to verify that buffer is not changed externally during 25 // networking operations. 26 IOBufferWithByteBuffer( 27 JNIEnv* env, 28 const base::android::JavaParamRef<jobject>& jbyte_buffer, 29 void* byte_buffer_data, 30 jint position, 31 jint limit); 32 33 IOBufferWithByteBuffer(const IOBufferWithByteBuffer&) = delete; 34 IOBufferWithByteBuffer& operator=(const IOBufferWithByteBuffer&) = delete; 35 initial_position()36 jint initial_position() const { return initial_position_; } initial_limit()37 jint initial_limit() const { return initial_limit_; } 38 byte_buffer()39 const base::android::JavaRef<jobject>& byte_buffer() const { 40 return byte_buffer_; 41 } 42 43 private: 44 ~IOBufferWithByteBuffer() override; 45 46 base::android::ScopedJavaGlobalRef<jobject> byte_buffer_; 47 48 const jint initial_position_; 49 const jint initial_limit_; 50 }; 51 52 // Represents a Java direct ByteBuffer backed by a net::IOBuffer. Keeps both the 53 // net::IOBuffer and the Java ByteBuffer object alive until destroyed. 54 class ByteBufferWithIOBuffer { 55 public: 56 ByteBufferWithIOBuffer(JNIEnv* env, 57 scoped_refptr<net::IOBuffer> io_buffer, 58 int io_buffer_len); 59 60 ByteBufferWithIOBuffer(const ByteBufferWithIOBuffer&) = delete; 61 ByteBufferWithIOBuffer& operator=(const ByteBufferWithIOBuffer&) = delete; 62 63 ~ByteBufferWithIOBuffer(); io_buffer()64 const net::IOBuffer* io_buffer() const { return io_buffer_.get(); } io_buffer_len()65 int io_buffer_len() const { return io_buffer_len_; } 66 byte_buffer()67 const base::android::JavaRef<jobject>& byte_buffer() const { 68 return byte_buffer_; 69 } 70 71 private: 72 scoped_refptr<net::IOBuffer> io_buffer_; 73 int io_buffer_len_; 74 75 base::android::ScopedJavaGlobalRef<jobject> byte_buffer_; 76 }; 77 78 } // namespace cronet 79 80 #endif // COMPONENTS_CRONET_ANDROID_IO_BUFFER_WITH_BYTE_BUFFER_H_ 81