Panda3D
jni_NativeIStream.cxx
1 // Filename: jni_NativeIStream.cxx
2 // Created by: rdb (22Jan13)
3 //
4 ////////////////////////////////////////////////////////////////////
5 //
6 // PANDA 3D SOFTWARE
7 // Copyright (c) Carnegie Mellon University. All rights reserved.
8 //
9 // All use of this software is subject to the terms of the revised BSD
10 // license. You should have received a copy of this license along
11 // with this source code in a file named "LICENSE."
12 //
13 ////////////////////////////////////////////////////////////////////
14 
15 #include <jni.h>
16 
17 #include <istream>
18 
19 ////////////////////////////////////////////////////////////////////
20 // Function: NativeIStream::nativeGet
21 // Access: Private, Static
22 // Description: Reads a single character from the istream.
23 // Should return -1 on EOF.
24 ////////////////////////////////////////////////////////////////////
25 extern "C" jint
26 Java_org_panda3d_android_NativeIStream_nativeGet(JNIEnv *env, jclass clazz, jlong ptr) {
27  std::istream *stream = (std::istream *) ptr;
28 
29  int ch = stream->get();
30  return stream->good() ? ch : -1;
31 }
32 
33 ////////////////////////////////////////////////////////////////////
34 // Function: NativeIStream::nativeRead
35 // Access: Private, Static
36 // Description: Reads an array of bytes from the istream. Returns
37 // the actual number of bytes that were read.
38 // Should return -1 on EOF.
39 ////////////////////////////////////////////////////////////////////
40 extern "C" jint
41 Java_org_panda3d_android_NativeIStream_nativeRead(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byte_array, jint offset, jint length) {
42  std::istream *stream = (std::istream *) ptr;
43  jbyte *buffer = (jbyte *) env->GetPrimitiveArrayCritical(byte_array, NULL);
44  if (buffer == NULL) {
45  return -1;
46  }
47 
48  stream->read((char*) buffer + offset, length);
49  env->ReleasePrimitiveArrayCritical(byte_array, buffer, 0);
50 
51  // We have to return -1 on EOF, otherwise it will keep trying to read.
52  size_t count = stream->gcount();
53  if (count == 0 && stream->eof()) {
54  return -1;
55  } else {
56  return count;
57  }
58 }
59 
60 ////////////////////////////////////////////////////////////////////
61 // Function: NativeIStream::nativeIgnore
62 // Access: Private, Static
63 // Description: Skips ahead N bytes in the stream. Returns the
64 // actual number of skipped bytes.
65 ////////////////////////////////////////////////////////////////////
66 extern "C" jlong
67 Java_org_panda3d_android_NativeIStream_nativeIgnore(JNIEnv *env, jclass clazz, jlong ptr, jlong offset) {
68  std::istream *stream = (std::istream *) ptr;
69  stream->ignore(offset);
70  return stream->gcount();
71 }