Loading...
Searching...
No Matches
mjs_string_public.h
1/*
2 * Copyright (c) 2016 Cesanta Software Limited
3 * All rights reserved
4 */
5
6#ifndef MJS_STRING_PUBLIC_H_
7#define MJS_STRING_PUBLIC_H_
8
9#include "mjs_core_public.h"
10
11#define MJS_STRING_LITERAL_MAX_LEN 128
12
13#if defined(__cplusplus)
14extern "C" {
15#endif /* __cplusplus */
16
17/*
18 * Creates a string primitive value.
19 * `str` must point to the utf8 string of length `len`.
20 * If `len` is ~0, `str` is assumed to be NUL-terminated and `strlen(str)` is
21 * used.
22 *
23 * If `copy` is non-zero, the string data is copied and owned by the GC. The
24 * caller can free the string data afterwards. Otherwise (`copy` is zero), the
25 * caller owns the string data, and is responsible for not freeing it while it
26 * is used.
27 */
28mjs_val_t mjs_mk_string(struct mjs* mjs, const char* str, size_t len, int copy);
29
30/* Returns true if given value is a primitive string value */
31int mjs_is_string(mjs_val_t v);
32
33/*
34 * Returns a pointer to the string stored in `mjs_val_t`.
35 *
36 * String length returned in `len`, which is allowed to be NULL. Returns NULL
37 * if the value is not a string.
38 *
39 * JS strings can contain embedded NUL chars and may or may not be NUL
40 * terminated.
41 *
42 * CAUTION: creating new JavaScript object, array, or string may kick in a
43 * garbage collector, which in turn may relocate string data and invalidate
44 * pointer returned by `mjs_get_string()`.
45 *
46 * Short JS strings are embedded inside the `mjs_val_t` value itself. This
47 * is why a pointer to a `mjs_val_t` is required. It also means that the string
48 * data will become invalid once that `mjs_val_t` value goes out of scope.
49 */
50const char* mjs_get_string(struct mjs* mjs, mjs_val_t* v, size_t* len);
51
52/*
53 * Returns a pointer to the string stored in `mjs_val_t`.
54 *
55 * Returns NULL if the value is not a string or if the string is not compatible
56 * with a C string.
57 *
58 * C compatible strings contain exactly one NUL char, in terminal position.
59 *
60 * All strings owned by the MJS engine (see `mjs_mk_string()`) are guaranteed to
61 * be NUL terminated. Out of these, those that don't include embedded NUL chars
62 * are guaranteed to be C compatible.
63 */
64const char* mjs_get_cstring(struct mjs* mjs, mjs_val_t* v);
65
66/*
67 * Returns the standard strcmp comparison code after comparing a JS string a
68 * with a possibly non null-terminated string b. NOTE: the strings are equal
69 * only if their length is equal, i.e. the len field doesn't imply strncmp
70 * behaviour.
71 */
72int mjs_strcmp(struct mjs* mjs, mjs_val_t* a, const char* b, size_t len);
73
74#if defined(__cplusplus)
75}
76#endif /* __cplusplus */
77
78#endif /* MJS_STRING_PUBLIC_H_ */
Definition mjs_core.h:63