*: update all clients of the `CString::to_s` services
[nit.git] / benchmarks / strings / array_to_s_vars / array_to_s_manual.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Implementation of Array::to_s with manual management of the String
12 #
13 # To be used as a Mixin at compile-time for benchmarking purposes.
14 module array_to_s_manual
15
16 intrude import standard::text::flat
17 intrude import standard::collection::array
18
19 redef class NativeArray[E]
20 new(length: Int) is intern
21 end
22
23 redef class Array[E]
24 redef fun to_s: String do
25 var l = length
26 var its = _items
27 var na = new NativeArray[String](l)
28 var i = 0
29 var sl = 0
30 while i < l do
31 var tmp = its[i].to_s
32 sl += tmp.length
33 na[i] = tmp
34 i += 1
35 end
36 var ns = new CString(sl + 1)
37 ns[sl] = '\0'
38 i = 0
39 var off = 0
40 while i < l do
41 var tmp = na[i]
42 var tpl = tmp.length
43 if tmp isa FlatString then
44 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
45 off += tpl
46 else
47 for j in tmp.substrings do
48 var s = j.as(FlatString)
49 s.items.copy_to(ns, tpl, s.index_from, off)
50 off += tpl
51 end
52 end
53 i += 1
54 end
55 return ns.to_s_unsafe(sl, copy=false)
56 end
57 end