Merge: doc: fixed some typos and other misc. corrections
[nit.git] / tests / test_ffi_cpp_strings.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Module wrapping the C++ class vector<int>
18 module test_ffi_cpp_strings
19
20 import cpp # gives us String.to_cpp_string and the CppString class
21
22 in "C++ Header" `{
23 #include <vector>
24
25 using namespace std;
26 `}
27
28 # Nit class over C++'s vector<int>
29 extern class CppVector in "C++" `{vector<int>*`}
30
31 # Extern constructor
32 new in "C++" `{
33 return new vector<int>();
34 `}
35
36 # Adds an element to the end of the vector
37 fun push(v: Int) in "C++" `{
38 self->push_back(v);
39 `}
40
41 # Pops an element from the end of the vector
42 fun pop: Int in "C++" `{
43 long val = self->back();
44 self->pop_back();
45 return val;
46 `}
47
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++" `{
50 if (self->empty()) {
51 CppVector_report_error(self);
52 return default_return;
53 } else {
54 long val = self->back();
55 self->pop_back();
56 return val;
57 }
58 `}
59
60 # Callback for `safe_pop_with_default`
61 private fun report_error do print "Vector is empty!"
62
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++" `{
65 if (self->empty()) {
66 string *cpp_error_msg = String_to_cpp_string(error_msg);
67 cout << *cpp_error_msg << "\n";
68 return default_return;
69 } else {
70 long val = self->back();
71 self->pop_back();
72 return val;
73 }
74 `}
75 end
76
77 var a = new CppVector
78 a.push(1)
79 a.push(2)
80 a.push(3)
81 a.push(4)
82 print a.pop
83 print a.pop
84 print a.pop
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")