2 * A helper routine to copy the strings between differing structures.
11 #define MAX_OFFSETS 10
13 #define OFFSET_SHIFT 1
15 #define lstr_at(p, n) (*(char**)(((char*)(p))+(n >> OFFSET_SHIFT)))
17 #define str_at(p, n) ( \
18 (((n) & MPH_STRING_OFFSET_MASK) == MPH_STRING_OFFSET_ARRAY) \
19 ? (char*)(p) + (n >> OFFSET_SHIFT) \
24 _mph_copy_structure_strings (
25 void *to, const mph_string_offset_t *to_offsets,
26 const void *from, const mph_string_offset_t *from_offsets,
32 char *buf, *cur = NULL;
34 g_assert (num_strings < MAX_OFFSETS);
36 for (i = 0; i < num_strings; ++i) {
37 lstr_at (to, to_offsets[i]) = NULL;
41 for (i = 0; i < num_strings; ++i) {
42 const char* s = str_at(from, from_offsets[i]);
43 len [i] = s ? strlen (s) : 0;
44 if (len[i] < INT_MAX - buflen)
50 cur = buf = malloc (buflen);
55 for (i = 0; i < num_strings; ++i) {
57 lstr_at (to, to_offsets[i]) =
58 strcpy (cur, str_at (from, from_offsets[i]));
70 * $ gcc -DTEST -I.. `pkg-config --cflags --libs glib-2.0` x-struct-str.c
94 /* test copying foo to bar */
95 struct foo f = {"hello", 42, "world", "!!"};
97 mph_string_offset_t foo_offsets[] = {
98 MPH_STRING_OFFSET(struct foo, a, MPH_STRING_OFFSET_PTR),
99 MPH_STRING_OFFSET(struct foo, c, MPH_STRING_OFFSET_PTR),
100 MPH_STRING_OFFSET(struct foo, d, MPH_STRING_OFFSET_ARRAY)
102 mph_string_offset_t bar_offsets[] = {
103 MPH_STRING_OFFSET(struct bar, a, MPH_STRING_OFFSET_PTR),
104 MPH_STRING_OFFSET(struct bar, c, MPH_STRING_OFFSET_PTR),
105 MPH_STRING_OFFSET(struct bar, e, MPH_STRING_OFFSET_PTR)
109 buf = _mph_copy_structure_strings (&b, bar_offsets,
111 printf ("b.a=%s\n", b.a);
112 printf ("b.c=%s\n", b.c);
113 printf ("b.e=%s\n", b.e);
116 buf = _mph_copy_structure_strings (&b, bar_offsets,
118 printf ("b.a=%s\n", b.a);
119 printf ("b.c=%s\n", b.c);
120 printf ("b.e=%s\n", b.e);