Debian Codegraph @

include/ruby/internal/core/rstring.h

raw
1 #ifndef RBIMPL_RSTRING_H /*-*-C++-*-vi:se ft=cpp:*/
2 #define RBIMPL_RSTRING_H
3 /**
4 * @file
5 * @author Ruby developers <[email protected]>
6 * @copyright This file is a part of the programming language Ruby.
7 * Permission is hereby granted, to either redistribute and/or
8 * modify this file, provided that the conditions mentioned in the
9 * file COPYING are met. Consult the file for details.
10 * @warning Symbols prefixed with either `RBIMPL` or `rbimpl` are
11 * implementation details. Don't take them as canon. They could
12 * rapidly appear then vanish. The name (path) of this header file
13 * is also an implementation detail. Do not expect it to persist
14 * at the place it is now. Developers are free to move it anywhere
15 * anytime at will.
16 * @note To ruby-core: remember that this header can be possibly
17 * recursively included from extension libraries written in C++.
18 * Do not expect for instance `__VA_ARGS__` is always available.
19 * We assume C99 for ruby itself but we don't assume languages of
20 * extension libraries. They could be written in C++98.
21 * @brief Defines struct ::RString.
22 */
23 #include "ruby/internal/config.h"
24 #include "ruby/internal/arithmetic/long.h"
25 #include "ruby/internal/attr/artificial.h"
26 #include "ruby/internal/attr/pure.h"
27 #include "ruby/internal/cast.h"
28 #include "ruby/internal/core/rbasic.h"
29 #include "ruby/internal/dllexport.h"
30 #include "ruby/internal/fl_type.h"
31 #include "ruby/internal/value_type.h"
32 #include "ruby/internal/warning_push.h"
33 #include "ruby/assert.h"
34
35 /**
36 * Convenient casting macro.
37 *
38 * @param obj An object, which is in fact an ::RString.
39 * @return The passed object casted to ::RString.
40 */
41 #define RSTRING(obj) RBIMPL_CAST((struct RString *)(obj))
42
43 /** @cond INTERNAL_MACRO */
44 #define RSTRING_NOEMBED RSTRING_NOEMBED
45 #define RSTRING_FSTR RSTRING_FSTR
46 #define RSTRING_LEN RSTRING_LEN
47 #define RSTRING_LENINT RSTRING_LENINT
48 #define RSTRING_PTR RSTRING_PTR
49 #define RSTRING_END RSTRING_END
50 /** @endcond */
51
52 /**
53 * @name Conversion of Ruby strings into C's
54 *
55 * @{
56 */
57
58 /**
59 * Ensures that the parameter object is a String. This is done by calling its
60 * `to_str` method.
61 *
62 * @param[in,out] v Arbitrary Ruby object.
63 * @exception rb_eTypeError No implicit conversion defined.
64 * @post `v` is a String.
65 */
66 #define StringValue(v) rb_string_value(&(v))
67
68 /**
69 * Identical to #StringValue, except it returns a `char*`.
70 *
71 * @param[in,out] v Arbitrary Ruby object.
72 * @exception rb_eTypeError No implicit conversion defined.
73 * @return Converted Ruby string's backend C string.
74 * @post `v` is a String.
75 */
76 #define StringValuePtr(v) rb_string_value_ptr(&(v))
77
78 /**
79 * Identical to #StringValuePtr, except it additionally checks for the contents
80 * for viability as a C string. Ruby can accept wider range of contents as
81 * strings, compared to C. This function is to check that.
82 *
83 * @param[in,out] v Arbitrary Ruby object.
84 * @exception rb_eTypeError No implicit conversion defined.
85 * @exception rb_eArgError String is not C-compatible.
86 * @return Converted Ruby string's backend C string.
87 * @post `v` is a String.
88 */
89 #define StringValueCStr(v) rb_string_value_cstr(&(v))
90
91 /**
92 * @private
93 *
94 * @deprecated This macro once was a thing in the old days, but makes no sense
95 * any longer today. Exists here for backwards compatibility
96 * only. You can safely forget about it.
97 */
98 #define SafeStringValue(v) StringValue(v)
99
100 /**
101 * Identical to #StringValue, except it additionally converts the string's
102 * encoding to default external encoding. Ruby has a concept called encodings.
103 * A string can have different encoding than the environment expects. Someone
104 * has to make sure its contents be converted to something suitable. This is
105 * that routine. Call it when necessary.
106 *
107 * @param[in,out] v Arbitrary Ruby object.
108 * @exception rb_eTypeError No implicit conversion defined.
109 * @return Converted Ruby string's backend C string.
110 * @post `v` is a String.
111 *
112 * @internal
113 *
114 * Not sure but it seems this macro does not raise on encoding
115 * incompatibilities? Doesn't sound right to @shyouhei.
116 */
117 #define ExportStringValue(v) do { \
118 StringValue(v); \
119 (v) = rb_str_export(v); \
120 } while (0)
121
122 /** @} */
123
124 /**
125 * @private
126 *
127 * Bits that you can set to ::RBasic::flags.
128 *
129 * @warning These enums are not the only bits we use for strings.
130 *
131 * @internal
132 *
133 * Actually all bits through FL_USER1 to FL_USER19 are used for strings. Why
134 * only this tiny part of them are made public here? @shyouhei can find no
135 * reason.
136 */
137 enum ruby_rstring_flags {
138
139 /**
140 * This flag has something to do with memory footprint. If the string is
141 * short enough, ruby tries to be creative to abuse padding bits of struct
142 * ::RString for storing contents. If this flag is set that string does
143 * _not_ do that, to resort to good old fashioned external allocation
144 * strategy instead.
145 *
146 * @warning This bit has to be considered read-only. Setting/clearing
147 * this bit without corresponding fix up must cause immediate
148 * SEGV. Also, internal structures of a string change
149 * dynamically and transparently throughout of its lifetime.
150 * Don't assume it being persistent.
151 *
152 * @internal
153 *
154 * 3rd parties must not be aware that there even is more than one way to
155 * store a string. Might better be hidden.
156 */
157 RSTRING_NOEMBED = RUBY_FL_USER1,
158
159 /* Actually, string encodings are also encoded into the flags, using
160 * remaining bits.*/
161
162 /**
163 * This flag has something to do with infamous "f"string. What is a
164 * fstring? Well it is a special subkind of strings that is immutable,
165 * deduped globally, and managed by our GC. It is much like a Symbol (in
166 * fact Symbols are dynamic these days and are backended using fstrings).
167 * This concept has been silently introduced at some point in 2.x era.
168 * Since then it gained wider acceptance in the core. But extension
169 * libraries could not know that until very recently. Strings of this flag
170 * live in a special Limbo deep inside of the interpreter. Never try to
171 * manipulate it by hand.
172 *
173 * @internal
174 *
175 * Fstrings are not the only variant strings that we implement today.
176 * Other things are behind-the-scene. This is the only one that is visible
177 * from extension library. There is no clear reason why it has to be.
178 * Given there are more "polite" ways to create fstrings, it seems this bit
179 * need not be exposed to extension libraries. Might better be hidden.
180 */
181 RSTRING_FSTR = RUBY_FL_USER17
182 };
183
184 /**
185 * Ruby's String. A string in ruby conceptually has these information:
186 *
187 * - Encoding of the string.
188 * - Length of the string.
189 * - Contents of the string.
190 *
191 * It is worth noting that a string is _not_ an array of characters in ruby.
192 * It has never been. In 1.x a string was an array of integers. Since 2.x a
193 * string is no longer an array of anything. A string is a string -- just like
194 * a Time is not an integer.
195 */
196 struct RString {
197
198 /** Basic part, including flags and class. */
199 struct RBasic basic;
200
201 /**
202 * Length of the string, not including terminating NUL character.
203 *
204 * @note This is in bytes.
205 */
206 long len;
207
208 /** String's specific fields. */
209 union {
210
211 /**
212 * Strings that use separated memory region for contents use this
213 * pattern.
214 */
215 struct {
216 /**
217 * Pointer to the contents of the string. In the old days each
218 * string had dedicated memory regions. That is no longer true
219 * today, but there still are strings of such properties. This
220 * field could be used to point such things.
221 */
222 char *ptr;
223
224 /** Auxiliary info. */
225 union {
226
227 /**
228 * Capacity of `*ptr`. A continuous memory region of at least
229 * `capa` bytes is expected to exist at `*ptr`. This can be
230 * bigger than `len`.
231 */
232 long capa;
233
234 /**
235 * Parent of the string. Nowadays strings can share their
236 * contents each other, constructing gigantic nest of objects.
237 * This situation is called "shared", and this is the field to
238 * control such properties.
239 */
240 VALUE shared;
241 } aux;
242 } heap;
243
244 /** Embedded contents. */
245 struct {
246 /* This is a length 1 array because:
247 * 1. GCC has a bug that does not optimize C flexible array members
248 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102452)
249 * 2. Zero length arrays are not supported by all compilers
250 */
251 char ary[1];
252 } embed;
253 } as;
254 };
255
256 RBIMPL_SYMBOL_EXPORT_BEGIN()
257 /**
258 * Identical to rb_check_string_type(), except it raises exceptions in case of
259 * conversion failures.
260 *
261 * @param[in] obj Target object.
262 * @exception rb_eTypeError No implicit conversion to String.
263 * @return Return value of `obj.to_str`.
264 * @see rb_io_get_io
265 * @see rb_ary_to_ary
266 */
267 VALUE rb_str_to_str(VALUE obj);
268
269 /**
270 * Identical to rb_str_to_str(), except it fills the passed pointer with the
271 * converted object.
272 *
273 * @param[in,out] ptr Pointer to a variable of target object.
274 * @exception rb_eTypeError No implicit conversion to String.
275 * @return Return value of `obj.to_str`.
276 * @post `*ptr` is the return value.
277 */
278 VALUE rb_string_value(volatile VALUE *ptr);
279
280 /**
281 * Identical to rb_str_to_str(), except it returns the converted string's
282 * backend memory region.
283 *
284 * @param[in,out] ptr Pointer to a variable of target object.
285 * @exception rb_eTypeError No implicit conversion to String.
286 * @post `*ptr` is the return value of `obj.to_str`.
287 * @return Pointer to the contents of the return value.
288 */
289 char *rb_string_value_ptr(volatile VALUE *ptr);
290
291 /**
292 * Identical to rb_string_value_ptr(), except it additionally checks for the
293 * contents for viability as a C string. Ruby can accept wider range of
294 * contents as strings, compared to C. This function is to check that.
295 *
296 * @param[in,out] ptr Pointer to a variable of target object.
297 * @exception rb_eTypeError No implicit conversion to String.
298 * @exception rb_eArgError String is not C-compatible.
299 * @post `*ptr` is the return value of `obj.to_str`.
300 * @return Pointer to the contents of the return value.
301 */
302 char *rb_string_value_cstr(volatile VALUE *ptr);
303
304 /**
305 * Identical to rb_str_to_str(), except it additionally converts the string
306 * into default external encoding. Ruby has a concept called encodings. A
307 * string can have different encoding than the environment expects. Someone
308 * has to make sure its contents be converted to something suitable. This is
309 * that routine. Call it when necessary.
310 *
311 * @param[in] obj Target object.
312 * @exception rb_eTypeError No implicit conversion to String.
313 * @return Converted ruby string of default external encoding.
314 */
315 VALUE rb_str_export(VALUE obj);
316
317 /**
318 * Identical to rb_str_export(), except it converts into the locale encoding
319 * instead.
320 *
321 * @param[in] obj Target object.
322 * @exception rb_eTypeError No implicit conversion to String.
323 * @return Converted ruby string of locale encoding.
324 */
325 VALUE rb_str_export_locale(VALUE obj);
326
327 RBIMPL_ATTR_ERROR(("rb_check_safe_str() and Check_SafeStr() are obsolete; use StringValue() instead"))
328 /**
329 * @private
330 *
331 * @deprecated This function once was a thing in the old days, but makes no
332 * sense any longer today. Exists here for backwards
333 * compatibility only. You can safely forget about it.
334 */
335 void rb_check_safe_str(VALUE);
336
337 /**
338 * @private
339 *
340 * @deprecated This macro once was a thing in the old days, but makes no sense
341 * any longer today. Exists here for backwards compatibility
342 * only. You can safely forget about it.
343 */
344 #define Check_SafeStr(v) rb_check_safe_str(RBIMPL_CAST((VALUE)(v)))
345
346 /**
347 * @private
348 *
349 * Prints diagnostic message to stderr when RSTRING_PTR or RSTRING_END
350 * is NULL.
351 *
352 * @param[in] func The function name where encountered NULL pointer.
353 */
354 void rb_debug_rstring_null_ptr(const char *func);
355 RBIMPL_SYMBOL_EXPORT_END()
356
357 RBIMPL_ATTR_PURE_UNLESS_DEBUG()
358 RBIMPL_ATTR_ARTIFICIAL()
359 /**
360 * Queries the length of the string.
361 *
362 * @param[in] str String in question.
363 * @return Its length, in bytes.
364 * @pre `str` must be an instance of ::RString.
365 */
366 static inline long
367 RSTRING_LEN(VALUE str)
368 {
369 return RSTRING(str)->len;
370 }
371
372 RBIMPL_WARNING_PUSH()
373 #if RBIMPL_COMPILER_IS(Intel)
374 RBIMPL_WARNING_IGNORED(413)
375 #endif
376
377 RBIMPL_ATTR_PURE_UNLESS_DEBUG()
378 RBIMPL_ATTR_ARTIFICIAL()
379 /**
380 * @private
381 *
382 * "Expands" an embedded string into an ordinal one. This is a function that
383 * returns aggregated type. The returned struct always has its `as.heap.len`
384 * an `as.heap.ptr` fields set appropriately.
385 *
386 * This is an implementation detail that 3rd parties should never bother.
387 */
388 static inline struct RString
389 rbimpl_rstring_getmem(VALUE str)
390 {
391 RBIMPL_ASSERT_TYPE(str, RUBY_T_STRING);
392
393 if (RB_FL_ANY_RAW(str, RSTRING_NOEMBED)) {
394 return *RSTRING(str);
395 }
396 else {
397 /* Expecting compilers to optimize this on-stack struct away. */
398 struct RString retval;
399 retval.len = RSTRING_LEN(str);
400 retval.as.heap.ptr = RSTRING(str)->as.embed.ary;
401 return retval;
402 }
403 }
404
405 RBIMPL_WARNING_POP()
406
407 RBIMPL_ATTR_ARTIFICIAL()
408 /**
409 * Queries the contents pointer of the string.
410 *
411 * @param[in] str String in question.
412 * @return Pointer to its contents.
413 * @pre `str` must be an instance of ::RString.
414 */
415 static inline char *
416 RSTRING_PTR(VALUE str)
417 {
418 char *ptr = rbimpl_rstring_getmem(str).as.heap.ptr;
419
420 if (RUBY_DEBUG && RB_UNLIKELY(! ptr)) {
421 /* :BEWARE: @shyouhei thinks that currently, there are rooms for this
422 * function to return NULL. Better check here for maximum safety.
423 *
424 * Also, this is not rb_warn() because RSTRING_PTR() can be called
425 * during GC (see what obj_info() does). rb_warn() needs to allocate
426 * Ruby objects. That is not possible at this moment. */
427 rb_debug_rstring_null_ptr("RSTRING_PTR");
428 }
429
430 return ptr;
431 }
432
433 RBIMPL_ATTR_ARTIFICIAL()
434 /**
435 * Queries the end of the contents pointer of the string.
436 *
437 * @param[in] str String in question.
438 * @return Pointer to its end of contents.
439 * @pre `str` must be an instance of ::RString.
440 */
441 static inline char *
442 RSTRING_END(VALUE str)
443 {
444 struct RString buf = rbimpl_rstring_getmem(str);
445
446 if (RUBY_DEBUG && RB_UNLIKELY(! buf.as.heap.ptr)) {
447 /* Ditto. */
448 rb_debug_rstring_null_ptr("RSTRING_END");
449 }
450
451 return &buf.as.heap.ptr[buf.len];
452 }
453
454 RBIMPL_ATTR_ARTIFICIAL()
455 /**
456 * Identical to RSTRING_LEN(), except it differs for the return type.
457 *
458 * @param[in] str String in question.
459 * @exception rb_eRangeError Too long.
460 * @return Its length, in bytes.
461 * @pre `str` must be an instance of ::RString.
462 *
463 * @internal
464 *
465 * This API seems redundant but has actual usages.
466 */
467 static inline int
468 RSTRING_LENINT(VALUE str)
469 {
470 return rb_long2int(RSTRING_LEN(str));
471 }
472
473 /**
474 * Convenient macro to obtain the contents and length at once.
475 *
476 * @param str String in question.
477 * @param ptrvar Variable where its contents is stored.
478 * @param lenvar Variable where its length is stored.
479 */
480 #ifdef HAVE_STMT_AND_DECL_IN_EXPR
481 # define RSTRING_GETMEM(str, ptrvar, lenvar) \
482 __extension__ ({ \
483 struct RString rbimpl_str = rbimpl_rstring_getmem(str); \
484 (ptrvar) = rbimpl_str.as.heap.ptr; \
485 (lenvar) = rbimpl_str.len; \
486 })
487 #else
488 # define RSTRING_GETMEM(str, ptrvar, lenvar) \
489 ((ptrvar) = RSTRING_PTR(str), \
490 (lenvar) = RSTRING_LEN(str))
491 #endif /* HAVE_STMT_AND_DECL_IN_EXPR */
492 #endif /* RBIMPL_RSTRING_H */