1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Module wrapping the C++ class vector<int>
18 module test_ffi_cpp_strings
20 import cpp
# gives us String.to_cpp_string and the CppString class
28 # Nit class over C++'s vector<int>
29 extern class CppVector in "C++" `{vector<int>*`}
33 return new vector
<int
>();
36 # Adds an element to the end of the vector
37 fun push(v: Int) in "C++" `{
41 # Pops an element from the end of the vector
42 fun pop: Int in "C++" `{
43 long val
= self-
>back
();
48 # Uses a callback to report when receiver is empty
49 fun safe_pop_with_default(default_return: Int): Int import report_error in "C++" `{
51 CppVector_report_error(self);
52 return default_return
;
54 long val
= self-
>back
();
60 # Callback for `safe_pop_with_default
`
61 private fun report_error do print "Vector is empty!"
63 # Prints the given string when receiver is empty
64 fun safe_pop_with_custom_error(default_return: Int, error_msg: String): Int import String.to_cpp_string in "C++" `{
66 string
*cpp_error_msg
= String_to_cpp_string(error_msg
);
67 cout
<< *cpp_error_msg
<< "\n";
68 return default_return
;
70 long val
= self-
>back
();
85 print a.safe_pop_with_default(1234)
86 print a.safe_pop_with_default(1234)
87 print a.safe_pop_with_custom_error(1234, "3rd safe pop")
88 print a.safe_pop_with_custom_error(1234, "4th safe pop")