Charstring.cc 104 KB
Newer Older
Elemer Lelik's avatar
Elemer Lelik committed
1
/******************************************************************************
Adam Knapp's avatar
Adam Knapp committed
2
 * Copyright (c) 2000-2021 Ericsson Telecom AB
Elemer Lelik's avatar
Elemer Lelik committed
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v2.0
Elemer Lelik's avatar
Elemer Lelik committed
5
 * which accompanies this distribution, and is available at
6
 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
Elemer Lelik's avatar
Elemer Lelik committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 *
 * Contributors:
 *   Baji, Laszlo
 *   Balasko, Jeno
 *   Baranyi, Botond
 *   Beres, Szabolcs
 *   Delic, Adam
 *   Forstner, Matyas
 *   Kovacs, Ferenc
 *   Raduly, Csaba
 *   Szabados, Kristof
 *   Szabo, Bence Janos
 *   Szabo, Janos Zoltan – initial implementation
 *   Szalai, Gabor
 *   Tatarka, Gabor
 *   Zalanyi, Balazs Andor
 *   Pandi, Krisztian
 *
 ******************************************************************************/
Elemer Lelik's avatar
Elemer Lelik committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "Charstring.hh"
#include "../common/memory.h"
#include "../common/pattern.hh"
#include "Integer.hh"
#include "Octetstring.hh"
#include "String_struct.hh"
#include "Parameters.h"
#include "Param_Types.hh"
#include "Error.hh"
#include "Logger.hh"
#include "Encdec.hh"
#include "RAW.hh"
#include "BER.hh"
#include "TEXT.hh"
#include "XER.hh"
#include "JSON.hh"
#include "Addfunc.hh"
43
#include "Optional.hh"
Elemer Lelik's avatar
Elemer Lelik committed
44
45

#include "../common/dbgnew.hh"
46
#include "OER.hh"
Elemer Lelik's avatar
Elemer Lelik committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

#include <string.h>
#include <ctype.h>
#include <limits.h>

#define ERRMSG_BUFSIZE 500

/** The amount of memory needed for a string containing n characters.
 * -sizeof(int) because that much is already in charstring_struct.
 * +1 for the terminating null character. */
#define MEMORY_SIZE(n) (sizeof(charstring_struct) - sizeof(int) + 1 + (n))

/** Allocate the memory needed to hold n_chars characters.
 *
 * @param \p n_chars the number of characters to hold
 * @pre \p n_chars must be >= 0
 */
void CHARSTRING::init_struct(int n_chars)
{
  if (n_chars < 0) {
    val_ptr = NULL;
    TTCN_error("Initializing a charstring with a negative length.");
  } else if (n_chars == 0) {
    /** This will represent the empty strings so they won't need allocated
      * memory, this delays the memory allocation until it is really needed.
      */
    static charstring_struct empty_string = { 1, 0, "" };
    val_ptr = &empty_string;
    empty_string.ref_count++;
  } else {
    val_ptr = (charstring_struct*)Malloc(MEMORY_SIZE(n_chars));
    val_ptr->ref_count = 1;
    val_ptr->n_chars = n_chars;
    val_ptr->chars_ptr[n_chars] = '\0';
  }
}

/** Implement the copy-on-write.
 *
 * Called from the various CHARSTRING_ELEMENT::operator=(), just before
 * the string is about to be modified. Stops the sharing of the CHARSTRING
 * and creates a new copy for modification.
 */
void CHARSTRING::copy_value()
{
  if (val_ptr == NULL || val_ptr->n_chars <= 0)
    TTCN_error("Internal error: Invalid internal data structure when copying "
      "the memory area of a charstring value.");
  if (val_ptr->ref_count > 1) {
    charstring_struct *old_ptr = val_ptr;
    old_ptr->ref_count--;
    init_struct(old_ptr->n_chars);
    memcpy(val_ptr->chars_ptr, old_ptr->chars_ptr, old_ptr->n_chars + 1);
  }
}

/** Create an uninitialized CHARSTRING object.
 *
 * Called from CHARSTRING::operator+() to create the return value with
 * enough storage to hold the concatenation of the arguments.
 *
 * @param n_chars the number of characters to hold
 *
 */
CHARSTRING::CHARSTRING(int n_chars)
{
  init_struct(n_chars);
}

CHARSTRING::CHARSTRING()
{
  val_ptr = NULL;
}

CHARSTRING::CHARSTRING(char other_value)
{
  init_struct(1);
  val_ptr->chars_ptr[0] = other_value;
}

CHARSTRING::CHARSTRING(const char *chars_ptr)
{
  int n_chars;
  if (chars_ptr != NULL) n_chars = strlen(chars_ptr);
  else n_chars = 0;
  init_struct(n_chars);
  memcpy(val_ptr->chars_ptr, chars_ptr, n_chars);
}

CHARSTRING::CHARSTRING(int n_chars, const char *chars_ptr)
{
  init_struct(n_chars);
  memcpy(val_ptr->chars_ptr, chars_ptr, n_chars);
}

CHARSTRING::CHARSTRING(const CHARSTRING& other_value)
: Base_Type(other_value), val_ptr(other_value.val_ptr)
{
  other_value.must_bound("Copying an unbound charstring value.");
  // ref_count can only be incremented after we check val_ptr
  val_ptr->ref_count++;
}

CHARSTRING::CHARSTRING(const CHARSTRING_ELEMENT& other_value)
{
  other_value.must_bound("Initialization of a charstring with an unbound "
                         "charstring element.");
  init_struct(1);
  val_ptr->chars_ptr[0] = other_value.get_char();
}

158
159
160
161
162
163
164
165
166
167
168
169
170
171
CHARSTRING::CHARSTRING(const UNIVERSAL_CHARSTRING& other_value)
{
  other_value.must_bound("Initialization of a charstring with an unbound "
    "universal charstring.");
  if (other_value.charstring) {
    val_ptr = other_value.cstr.val_ptr;
    val_ptr->ref_count++;
  }
  else {
    int n_chars = other_value.val_ptr->n_uchars;
    init_struct(n_chars);
    for (int i = 0; i < n_chars; ++i) {
      const universal_char& uc = other_value.val_ptr->uchars_ptr[i];
      if (uc.uc_group != 0 || uc.uc_plane != 0 || uc.uc_row != 0 || uc.uc_cell > 127) {
172
173
174
175
        Free(val_ptr);
        TTCN_error("Non-ASCII characters cannot be used to initialize a charstring, "
          "invalid character char(%u, %u, %u, %u) at index %d.",
          uc.uc_group, uc.uc_plane, uc.uc_row, uc.uc_cell, i);
176
177
178
179
180
181
      }
      val_ptr->chars_ptr[i] = other_value.val_ptr->uchars_ptr[i].uc_cell;
    }
  }
}

Elemer Lelik's avatar
Elemer Lelik committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
CHARSTRING::~CHARSTRING()
{
  clean_up();
}

void CHARSTRING::clean_up()
{
  if (val_ptr != NULL) {
    if (val_ptr->ref_count > 1) val_ptr->ref_count--;
    else if (val_ptr->ref_count == 1) Free(val_ptr);
    else TTCN_error("Internal error: Invalid reference counter in a charstring "
      "value.");
    val_ptr = NULL;
  }
}

CHARSTRING& CHARSTRING::operator=(const char* other_value)
{
  if (val_ptr == NULL || val_ptr->chars_ptr != other_value) {
    clean_up();
    int n_chars;
    if (other_value != NULL) n_chars = strlen(other_value);
    else n_chars = 0;
    init_struct(n_chars);
    memcpy(val_ptr->chars_ptr, other_value, n_chars);
  }
  return *this;
}

CHARSTRING& CHARSTRING::operator=(const CHARSTRING& other_value)
{
  other_value.must_bound("Assignment of an unbound charstring value.");
  if (&other_value != this) {
    clean_up();
    val_ptr = other_value.val_ptr;
    val_ptr->ref_count++;
  }
  return *this;
}

CHARSTRING& CHARSTRING::operator=(const CHARSTRING_ELEMENT& other_value)
{
  other_value.must_bound("Assignment of an unbound charstring element to "
                         "a charstring.");
  char char_value = other_value.get_char();
  clean_up();
  init_struct(1);
  val_ptr->chars_ptr[0] = char_value;
  return *this;
}

CHARSTRING& CHARSTRING::operator=(const UNIVERSAL_CHARSTRING& other_value)
{
  other_value.must_bound("Assignment of an unbound universal charstring to "
                         "a charstring.");
237
238
239
240
241
242
243
244
245
  if (other_value.charstring) {
    *this = other_value.cstr;
  }
  else {
    clean_up();
    int n_chars = other_value.val_ptr->n_uchars;
    init_struct(n_chars);
    for (int i = 0; i < n_chars; ++i) {
      const universal_char& uc = other_value.val_ptr->uchars_ptr[i];
246
247
      if (uc.uc_group != 0 || uc.uc_plane != 0 || uc.uc_row != 0 || uc.uc_cell > 127) {
        TTCN_error("Non-ASCII characters cannot be assigned to a charstring, "
248
249
250
251
          "invalid character char(%u, %u, %u, %u) at index %d.", 
          uc.uc_group, uc.uc_plane, uc.uc_row, uc.uc_cell, i);
      }
      val_ptr->chars_ptr[i] = other_value.val_ptr->uchars_ptr[i].uc_cell;
Elemer Lelik's avatar
Elemer Lelik committed
252
253
254
255
256
257
258
259
    }
  }
  return *this;
}

boolean CHARSTRING::operator==(const char* other_value) const
{
  must_bound("Unbound operand of charstring comparison.");
Kristof Szabados's avatar
bugfix    
Kristof Szabados committed
260
  if (other_value == NULL) return val_ptr->n_chars == 0;
Elemer Lelik's avatar
Elemer Lelik committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
  return !strcmp(val_ptr->chars_ptr, other_value);
}

boolean CHARSTRING::operator==(const CHARSTRING& other_value) const
{
  must_bound("Unbound operand of charstring comparison.");
  other_value.must_bound("Unbound operand of charstring comparison.");
  if (val_ptr->n_chars != other_value.val_ptr->n_chars) return FALSE;
  else return !memcmp(val_ptr->chars_ptr, other_value.val_ptr->chars_ptr,
                      val_ptr->n_chars);
}

boolean CHARSTRING::operator==(const CHARSTRING_ELEMENT& other_value) const
{
  other_value.must_bound("Unbound operand of charstring element "
                         "comparison.");
  must_bound("Unbound operand of charstring comparison.");
  if (val_ptr->n_chars != 1) return FALSE;
  else return val_ptr->chars_ptr[0] == other_value.get_char();
}

boolean CHARSTRING::operator==(const UNIVERSAL_CHARSTRING& other_value) const
{
  must_bound("The left operand of comparison is an unbound charstring value.");
  other_value.must_bound("The right operand of comparison is an unbound "
    "universal charstring value.");
  if (other_value.charstring)
    return *this == other_value.cstr;
  if (val_ptr->n_chars != other_value.val_ptr->n_uchars) return FALSE;
  for (int i = 0; i < val_ptr->n_chars; i++) {
    if (other_value.val_ptr->uchars_ptr[i].uc_group != 0 ||
      other_value.val_ptr->uchars_ptr[i].uc_plane != 0 ||
      other_value.val_ptr->uchars_ptr[i].uc_row != 0 ||
      other_value.val_ptr->uchars_ptr[i].uc_cell != (cbyte)val_ptr->chars_ptr[i])
      return FALSE;
  }
  return TRUE;
}

boolean CHARSTRING::operator==(const UNIVERSAL_CHARSTRING_ELEMENT& other_value)
  const
{
  must_bound("The left operand of comparison is an unbound charstring value.");
  other_value.must_bound("The right operand of comparison is an unbound "
    "universal charstring element.");
  if (val_ptr->n_chars != 1) return FALSE;
  const universal_char& uchar = other_value.get_uchar();
  return uchar.uc_group == 0 && uchar.uc_plane == 0 && uchar.uc_row == 0 &&
    uchar.uc_cell == (cbyte)val_ptr->chars_ptr[0];
}

CHARSTRING CHARSTRING::operator+(const char* other_value) const
{
  must_bound("Unbound operand of charstring concatenation.");
  int other_len;
  if (other_value == NULL) other_len = 0;
  else other_len = strlen(other_value);
  if (other_len == 0) return *this;
  CHARSTRING ret_val(val_ptr->n_chars + other_len);
  memcpy(ret_val.val_ptr->chars_ptr, val_ptr->chars_ptr, val_ptr->n_chars);
  memcpy(ret_val.val_ptr->chars_ptr + val_ptr->n_chars, other_value, other_len);
  return ret_val;
}

CHARSTRING CHARSTRING::operator+(const CHARSTRING& other_value) const
{
  must_bound("Unbound operand of charstring concatenation.");
  other_value.must_bound("Unbound operand of charstring concatenation.");
  int first_n_chars = val_ptr->n_chars;
  if (first_n_chars == 0) return other_value;
  int second_n_chars = other_value.val_ptr->n_chars;
  if (second_n_chars == 0) return *this;
  CHARSTRING ret_val(first_n_chars + second_n_chars);
  memcpy(ret_val.val_ptr->chars_ptr, val_ptr->chars_ptr, first_n_chars);
  memcpy(ret_val.val_ptr->chars_ptr + first_n_chars,
         other_value.val_ptr->chars_ptr, second_n_chars);
  return ret_val;
}

CHARSTRING CHARSTRING::operator+(const CHARSTRING_ELEMENT& other_value) const
{
  must_bound("Unbound operand of charstring concatenation.");
  other_value.must_bound("Unbound operand of charstring element "
                         "concatenation.");
  CHARSTRING ret_val(val_ptr->n_chars + 1);
  memcpy(ret_val.val_ptr->chars_ptr, val_ptr->chars_ptr, val_ptr->n_chars);
  ret_val.val_ptr->chars_ptr[val_ptr->n_chars] = other_value.get_char();
  return ret_val;
}

UNIVERSAL_CHARSTRING CHARSTRING::operator+
  (const UNIVERSAL_CHARSTRING& other_value) const
{
  must_bound("The left operand of concatenation is an unbound charstring "
    "value.");
  other_value.must_bound("The right operand of concatenation is an unbound "
    "universal charstring value.");
  if (val_ptr->n_chars == 0) return other_value;
  if (other_value.charstring) {
360
    UNIVERSAL_CHARSTRING ret_val(val_ptr->n_chars + other_value.cstr.val_ptr->n_chars, TRUE);
Elemer Lelik's avatar
Elemer Lelik committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
    memcpy(ret_val.cstr.val_ptr->chars_ptr, val_ptr->chars_ptr, val_ptr->n_chars);
    memcpy(ret_val.cstr.val_ptr->chars_ptr + val_ptr->n_chars, other_value.cstr.val_ptr->chars_ptr, other_value.cstr.val_ptr->n_chars);
    return ret_val;
  } else {
    UNIVERSAL_CHARSTRING ret_val(val_ptr->n_chars +
      other_value.val_ptr->n_uchars);
    for (int i = 0; i < val_ptr->n_chars; i++) {
      ret_val.val_ptr->uchars_ptr[i].uc_group = 0;
      ret_val.val_ptr->uchars_ptr[i].uc_plane = 0;
      ret_val.val_ptr->uchars_ptr[i].uc_row = 0;
      ret_val.val_ptr->uchars_ptr[i].uc_cell = val_ptr->chars_ptr[i];
    }
    memcpy(ret_val.val_ptr->uchars_ptr + val_ptr->n_chars,
      other_value.val_ptr->uchars_ptr,
      other_value.val_ptr->n_uchars * sizeof(universal_char));
    return ret_val;
  }
}

UNIVERSAL_CHARSTRING CHARSTRING::operator+
  (const UNIVERSAL_CHARSTRING_ELEMENT& other_value) const
{
  must_bound("The left operand of concatenation is an unbound charstring "
    "value.");
  other_value.must_bound("The right operand of concatenation is an unbound "
    "universal charstring element.");
  if (other_value.str_val.charstring) {
388
    UNIVERSAL_CHARSTRING ret_val(val_ptr->n_chars + 1, TRUE);
Elemer Lelik's avatar
Elemer Lelik committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
    memcpy(ret_val.cstr.val_ptr->chars_ptr, val_ptr->chars_ptr, val_ptr->n_chars);
    ret_val.cstr.val_ptr->chars_ptr[val_ptr->n_chars] = other_value.str_val.cstr.val_ptr->chars_ptr[other_value.uchar_pos];
    return ret_val;
  } else {
    UNIVERSAL_CHARSTRING ret_val(val_ptr->n_chars + 1);
    for (int i = 0; i < val_ptr->n_chars; i++) {
      ret_val.val_ptr->uchars_ptr[i].uc_group = 0;
      ret_val.val_ptr->uchars_ptr[i].uc_plane = 0;
      ret_val.val_ptr->uchars_ptr[i].uc_row = 0;
      ret_val.val_ptr->uchars_ptr[i].uc_cell = val_ptr->chars_ptr[i];
    }
    ret_val.val_ptr->uchars_ptr[val_ptr->n_chars] = other_value.get_uchar();
    return ret_val;
  }
}

CHARSTRING& CHARSTRING::operator+=(char other_value)
{
  must_bound("Appending a character to an unbound charstring value.");
  if (val_ptr->ref_count > 1) {
    charstring_struct *old_ptr = val_ptr;
    old_ptr->ref_count--;
    init_struct(old_ptr->n_chars + 1);
    memcpy(val_ptr->chars_ptr, old_ptr->chars_ptr, old_ptr->n_chars);
    val_ptr->chars_ptr[old_ptr->n_chars] = other_value;
  } else {
    val_ptr = (charstring_struct*)
      Realloc(val_ptr, MEMORY_SIZE(val_ptr->n_chars + 1));
    val_ptr->chars_ptr[val_ptr->n_chars] = other_value;
    val_ptr->n_chars++;
    val_ptr->chars_ptr[val_ptr->n_chars] = '\0';
  }
  return *this;
}

CHARSTRING& CHARSTRING::operator+=(const char *other_value)
{
  must_bound("Appending a string literal to an unbound charstring value.");
  if (other_value != NULL) {
    int other_n_chars = strlen(other_value);
    if (other_n_chars > 0) {
      if (val_ptr->ref_count > 1) {
	charstring_struct *old_ptr = val_ptr;
	old_ptr->ref_count--;
	init_struct(old_ptr->n_chars + other_n_chars);
	memcpy(val_ptr->chars_ptr, old_ptr->chars_ptr, old_ptr->n_chars);
	memcpy(val_ptr->chars_ptr + old_ptr->n_chars, other_value,
	  other_n_chars);
      } else {
	if (other_value >= val_ptr->chars_ptr &&
	    other_value <= val_ptr->chars_ptr + val_ptr->n_chars) {
	  int offset = other_value - val_ptr->chars_ptr;
	  val_ptr = (charstring_struct*)
	    Realloc(val_ptr, MEMORY_SIZE(val_ptr->n_chars + other_n_chars));
	  memcpy(val_ptr->chars_ptr + val_ptr->n_chars,
	    val_ptr->chars_ptr + offset, other_n_chars);
	} else {
	  val_ptr = (charstring_struct*)
	    Realloc(val_ptr, MEMORY_SIZE(val_ptr->n_chars + other_n_chars));
	  memcpy(val_ptr->chars_ptr + val_ptr->n_chars, other_value,
	    other_n_chars);
	}
	val_ptr->n_chars += other_n_chars;
	val_ptr->chars_ptr[val_ptr->n_chars] = '\0';
      }
    }
  }
  return *this;
}

CHARSTRING& CHARSTRING::operator+=(const CHARSTRING& other_value)
{
  must_bound("Appending a charstring value to an unbound charstring value.");
  other_value.must_bound("Appending an unbound charstring value to another "
    "charstring value.");
  int other_n_chars = other_value.val_ptr->n_chars;
  if (other_n_chars > 0) {
    if (val_ptr->n_chars == 0) {
      clean_up();
      val_ptr = other_value.val_ptr;
      val_ptr->ref_count++;
    } else if (val_ptr->ref_count > 1) {
      charstring_struct *old_ptr = val_ptr;
      old_ptr->ref_count--;
      init_struct(old_ptr->n_chars + other_n_chars);
      memcpy(val_ptr->chars_ptr, old_ptr->chars_ptr, old_ptr->n_chars);
      memcpy(val_ptr->chars_ptr + old_ptr->n_chars,
	other_value.val_ptr->chars_ptr, other_n_chars);
    } else {
      val_ptr = (charstring_struct*)
	Realloc(val_ptr, MEMORY_SIZE(val_ptr->n_chars + other_n_chars));
      memcpy(val_ptr->chars_ptr + val_ptr->n_chars,
	other_value.val_ptr->chars_ptr, other_n_chars);
      val_ptr->n_chars += other_n_chars;
      val_ptr->chars_ptr[val_ptr->n_chars] = '\0';
    }
  }
  return *this;
}

CHARSTRING& CHARSTRING::operator+=(const CHARSTRING_ELEMENT& other_value)
{
  must_bound("Appending a charstring element to an unbound charstring value.");
  other_value.must_bound("Appending an unbound charstring element to a "
    "charstring value.");
  if (val_ptr->ref_count > 1) {
    charstring_struct *old_ptr = val_ptr;
    old_ptr->ref_count--;
    init_struct(old_ptr->n_chars + 1);
    memcpy(val_ptr->chars_ptr, old_ptr->chars_ptr, old_ptr->n_chars);
    val_ptr->chars_ptr[old_ptr->n_chars] = other_value.get_char();
  } else {
    val_ptr = (charstring_struct*)
      Realloc(val_ptr, MEMORY_SIZE(val_ptr->n_chars + 1));
    val_ptr->chars_ptr[val_ptr->n_chars] = other_value.get_char();
    val_ptr->n_chars++;
    val_ptr->chars_ptr[val_ptr->n_chars] = '\0';
  }
  return *this;
}

CHARSTRING CHARSTRING::operator<<=(int rotate_count) const
{
  must_bound("Unbound charstring operand of rotate left operator.");
  if (val_ptr->n_chars == 0) return *this;
  if (rotate_count >= 0) {
    rotate_count %= val_ptr->n_chars;
    if (rotate_count == 0) return *this;
    CHARSTRING ret_val(val_ptr->n_chars);
    memcpy(ret_val.val_ptr->chars_ptr, val_ptr->chars_ptr + rotate_count,
           val_ptr->n_chars - rotate_count);
    memcpy(ret_val.val_ptr->chars_ptr + val_ptr->n_chars - rotate_count,
           val_ptr->chars_ptr, rotate_count);
    return ret_val;
  } else return *this >>= (-rotate_count);
}

CHARSTRING CHARSTRING::operator<<=(const INTEGER& rotate_count) const
{
  rotate_count.must_bound("Unbound integer operand of rotate left "
                          "operator.");
  return *this <<= (int)rotate_count;
}

CHARSTRING CHARSTRING::operator>>=(int rotate_count) const
{
  must_bound("Unbound charstring operand of rotate right operator.");
  if (val_ptr->n_chars == 0) return *this;
  if (rotate_count >= 0) {
    rotate_count %= val_ptr->n_chars;
    if (rotate_count == 0) return *this;
    CHARSTRING ret_val(val_ptr->n_chars);
    memcpy(ret_val.val_ptr->chars_ptr, val_ptr->chars_ptr + val_ptr->n_chars -
           rotate_count, rotate_count);
    memcpy(ret_val.val_ptr->chars_ptr + rotate_count, val_ptr->chars_ptr,
           val_ptr->n_chars - rotate_count);
    return ret_val;
  } else return *this <<= (-rotate_count);
}

CHARSTRING CHARSTRING::operator>>=(const INTEGER& rotate_count) const
{
  rotate_count.must_bound("Unbound integer operand of rotate right "
                          "operator.");
  return *this >>= (int)rotate_count;
}

CHARSTRING_ELEMENT CHARSTRING::operator[](int index_value)
{
  if (val_ptr == NULL && index_value == 0) {
    init_struct(1);
    return CHARSTRING_ELEMENT(FALSE, *this, 0);
  } else {
    must_bound("Accessing an element of an unbound charstring value.");
    if (index_value < 0) TTCN_error("Accessing a charstring element using a "
      "negative index (%d).", index_value);
    int n_chars = val_ptr->n_chars;
    if (index_value > n_chars) TTCN_error("Index overflow when accessing a "
      "charstring element: The index is %d, but the string has only %d "
      "characters.", index_value, n_chars);
    if (index_value == n_chars) {
      if (val_ptr->ref_count == 1) {
	val_ptr = (charstring_struct*)
	  Realloc(val_ptr, MEMORY_SIZE(n_chars + 1));
	val_ptr->n_chars++;
	val_ptr->chars_ptr[val_ptr->n_chars] = '\0';
      } else {
	charstring_struct *old_ptr = val_ptr;
	old_ptr->ref_count--;
	init_struct(n_chars + 1);
	memcpy(val_ptr->chars_ptr, old_ptr->chars_ptr, n_chars);
      }
      return CHARSTRING_ELEMENT(FALSE, *this, index_value);
    } else return CHARSTRING_ELEMENT(TRUE, *this, index_value);
  }
}

CHARSTRING_ELEMENT CHARSTRING::operator[](const INTEGER& index_value)
{
  index_value.must_bound("Indexing a charstring value with an unbound integer "
    "value.");
  return (*this)[(int)index_value];
}

const CHARSTRING_ELEMENT CHARSTRING::operator[](int index_value) const
{
  must_bound("Accessing an element of an unbound charstring value.");
  if (index_value < 0) TTCN_error("Accessing a charstring element using a "
    "negative index (%d).", index_value);
  if (index_value >= val_ptr->n_chars) TTCN_error("Index overflow when "
    "accessing a charstring element: The index is %d, but the string has only "
    "%d characters.", index_value, val_ptr->n_chars);
  return CHARSTRING_ELEMENT(TRUE, const_cast<CHARSTRING&>(*this), index_value);
}

const CHARSTRING_ELEMENT CHARSTRING::operator[](const INTEGER& index_value) const
{
  index_value.must_bound("Indexing a charstring value with an unbound integer "
    "value.");
  return (*this)[(int)index_value];
}

CHARSTRING::operator const char*() const
{
  must_bound("Casting an unbound charstring value to const char*.");
  return val_ptr->chars_ptr;
}

int CHARSTRING::lengthof() const
{
  must_bound("Performing lengthof operation on an unbound charstring value.");
  return val_ptr->n_chars;
}

void CHARSTRING::log() const
{
  if (val_ptr != NULL) {
    expstring_t buffer = 0;
    enum { INIT, PCHAR, NPCHAR } state = INIT;
    for (int i = 0; i < val_ptr->n_chars; i++) {
      char c = val_ptr->chars_ptr[i];
      if (TTCN_Logger::is_printable(c)) {
	// the actual character is printable
	switch (state) {
	case NPCHAR: // concatenation sign if previous part was not printable
	  buffer = mputstr(buffer, " & ");
	  // no break
	case INIT: // opening "
	  buffer = mputc(buffer, '"');
	  // no break
	case PCHAR: // the character itself
	  TTCN_Logger::log_char_escaped(c, buffer);
	  break;
	}
	state = PCHAR;
      } else {
	// the actual character is not printable
	switch (state) {
	case PCHAR: // closing " if previous part was printable
	  buffer = mputc(buffer, '"');
	  // no break
	case NPCHAR: // concatenation sign
	  buffer = mputstr(buffer, " & ");
	  // no break
	case INIT: // the character itself
	  buffer = mputprintf(buffer, "char(0, 0, 0, %u)", (unsigned char)c);
	  break;
	}
	state = NPCHAR;
      }
    }
    // final steps
    switch (state) {
    case INIT: // the string was empty
      buffer = mputstr(buffer, "\"\"");
      break;
    case PCHAR: // last character was printable -> closing "
      buffer = mputc(buffer, '"');
      break;
    default:
      break;
    }
    TTCN_Logger::log_event_str(buffer);
    Free(buffer);
  } else {
    TTCN_Logger::log_event_unbound();
  }
}

678
679
boolean CHARSTRING::set_param_internal(Module_Param& param, boolean allow_pattern,
                                       boolean* is_nocase_pattern) {
Elemer Lelik's avatar
Elemer Lelik committed
680
  boolean is_pattern = FALSE;
Elemer Lelik's avatar
Elemer Lelik committed
681
  param.basic_check(Module_Param::BC_VALUE|Module_Param::BC_LIST, "charstring value");
Elemer Lelik's avatar
Elemer Lelik committed
682
  Module_Param_Ptr mp = &param;
683
#ifdef TITAN_RUNTIME_2
Elemer Lelik's avatar
Elemer Lelik committed
684
685
686
  if (param.get_type() == Module_Param::MP_Reference) {
    mp = param.get_referenced_param();
  }
687
#endif
Elemer Lelik's avatar
Elemer Lelik committed
688
  switch (mp->get_type()) {
Elemer Lelik's avatar
Elemer Lelik committed
689
690
691
692
693
694
695
696
697
  case Module_Param::MP_Universal_Charstring:
  case Module_Param::MP_Charstring:
    switch (param.get_operation_type()) {
    case Module_Param::OT_ASSIGN:
      clean_up();
      // no break
    case Module_Param::OT_CONCAT: {
      // The universal charstring will decode the string value if it is UTF-8 encoded
      UNIVERSAL_CHARSTRING ucs;
Elemer Lelik's avatar
Elemer Lelik committed
698
      ucs.set_param(*mp);
Elemer Lelik's avatar
Elemer Lelik committed
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
      if (ucs.charstring) {
        // No special characters were found
        if (is_bound()) {
          *this = *this + ucs.cstr;
        } else {
          *this = ucs.cstr;
        }
      } else {
        // Special characters found -> check if the UTF-8 decoding resulted in any multi-byte characters
        for (int i = 0; i < ucs.val_ptr->n_uchars; ++i) {
          if (0 != ucs.val_ptr->uchars_ptr[i].uc_group ||
              0 != ucs.val_ptr->uchars_ptr[i].uc_plane ||
              0 != ucs.val_ptr->uchars_ptr[i].uc_row) {
            param.error("Type mismatch: a charstring value without multi-octet characters was expected.");
          }
        }
        CHARSTRING new_cs(ucs.val_ptr->n_uchars);
        for (int i = 0; i < ucs.val_ptr->n_uchars; ++i) {
          new_cs.val_ptr->chars_ptr[i] = ucs.val_ptr->uchars_ptr[i].uc_cell;
        }
        if (is_bound()) {
          *this = *this + new_cs;
        } else {
          *this = new_cs;
        }
      }
      break; }
    default:
      TTCN_error("Internal error: CHARSTRING::set_param()");
    }
    break;
Elemer Lelik's avatar
Elemer Lelik committed
730
731
732
733
  case Module_Param::MP_Expression:
    if (mp->get_expr_type() == Module_Param::EXPR_CONCATENATE) {
      // only allow string patterns for the first operand
      CHARSTRING operand1, operand2;
734
735
      is_pattern = operand1.set_param_internal(*mp->get_operand1(), allow_pattern,
        is_nocase_pattern);
Elemer Lelik's avatar
Elemer Lelik committed
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
      operand2.set_param(*mp->get_operand2());
      if (param.get_operation_type() == Module_Param::OT_CONCAT) {
        *this = *this + operand1 + operand2;
      }
      else {
        *this = operand1 + operand2;
      }
    }
    else {
      param.expr_type_error("a charstring");
    }
    break;
  case Module_Param::MP_Pattern:
    if (allow_pattern) {
      *this = CHARSTRING(mp->get_pattern());
      is_pattern = TRUE;
752
753
754
      if (is_nocase_pattern != NULL) {
        *is_nocase_pattern = mp->get_nocase();
      }
Elemer Lelik's avatar
Elemer Lelik committed
755
756
757
      break;
    }
    // else fall through
Elemer Lelik's avatar
Elemer Lelik committed
758
759
  default:
    param.type_error("charstring value");
Elemer Lelik's avatar
Elemer Lelik committed
760
    break;
Elemer Lelik's avatar
Elemer Lelik committed
761
  }
Elemer Lelik's avatar
Elemer Lelik committed
762
763
764
765
766
767
768
  return is_pattern;
}

void CHARSTRING::set_param(Module_Param& param) {
  set_param_internal(param, FALSE);
}

769
#ifdef TITAN_RUNTIME_2
Elemer Lelik's avatar
Elemer Lelik committed
770
771
772
773
774
775
Module_Param* CHARSTRING::get_param(Module_Param_Name& /* param_name */) const
{
  if (!is_bound()) {
    return new Module_Param_Unbound();
  }
  return new Module_Param_Charstring(val_ptr->n_chars, mcopystr(val_ptr->chars_ptr));
Elemer Lelik's avatar
Elemer Lelik committed
776
}
777
#endif
Elemer Lelik's avatar
Elemer Lelik committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798

void CHARSTRING::encode_text(Text_Buf& text_buf) const
{
  must_bound("Text encoder: Encoding an unbound charstring value.");
  int n_chars = val_ptr->n_chars;
  text_buf.push_int(n_chars);
  if (n_chars > 0) text_buf.push_raw(n_chars, val_ptr->chars_ptr);
}

void CHARSTRING::decode_text(Text_Buf& text_buf)
{
  int n_chars = text_buf.pull_int().get_val();
  if (n_chars < 0)
    TTCN_error("Text decoder: invalid length of a charstring.");
  clean_up();
  init_struct(n_chars);
  if (n_chars > 0) text_buf.pull_raw(n_chars, val_ptr->chars_ptr);
}

void CHARSTRING::encode(const TTCN_Typedescriptor_t& p_td,
                        TTCN_Buffer& p_buf,
799
                        int p_coding, ...) const
Elemer Lelik's avatar
Elemer Lelik committed
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
{
  va_list pvar;
  va_start(pvar, p_coding);
  switch(p_coding) {
  case TTCN_EncDec::CT_BER: {
    TTCN_EncDec_ErrorContext ec("While BER-encoding type '%s': ", p_td.name);
    unsigned BER_coding=va_arg(pvar, unsigned);
    BER_encode_chk_coding(BER_coding);
    ASN_BER_TLV_t *tlv=BER_encode_TLV(p_td, BER_coding);
    tlv->put_in_buffer(p_buf);
    ASN_BER_TLV_t::destruct(tlv);
    break;}
  case TTCN_EncDec::CT_RAW: {
    TTCN_EncDec_ErrorContext ec("While RAW-encoding type '%s': ", p_td.name);
    if(!p_td.raw)
      TTCN_EncDec_ErrorContext::error_internal
        ("No RAW descriptor available for type '%s'.", p_td.name);
    RAW_enc_tr_pos rp;
    rp.level=0;
    rp.pos=NULL;
    RAW_enc_tree root(TRUE,NULL,&rp,1,p_td.raw);
    RAW_encode(p_td, root);
    root.put_to_buf(p_buf);
    break;}
  case TTCN_EncDec::CT_TEXT: {
    TTCN_EncDec_ErrorContext ec("While TEXT-encoding type '%s': ", p_td.name);
    if(!p_td.text)
      TTCN_EncDec_ErrorContext::error_internal
        ("No TEXT descriptor available for type '%s'.", p_td.name);
    TEXT_encode(p_td,p_buf);
    break;}
  case TTCN_EncDec::CT_XER: {
    TTCN_EncDec_ErrorContext ec("While XER-encoding type '%s': ", p_td.name);
    unsigned XER_coding=va_arg(pvar, unsigned);
834
    XER_encode(*p_td.xer, p_buf, XER_coding, 0, 0, 0);
Elemer Lelik's avatar
Elemer Lelik committed
835
836
837
838
839
840
841
842
    p_buf.put_c('\n');
    break;}
  case TTCN_EncDec::CT_JSON: {
    TTCN_EncDec_ErrorContext ec("While JSON-encoding type '%s': ", p_td.name);
    if(!p_td.json)
      TTCN_EncDec_ErrorContext::error_internal
        ("No JSON descriptor available for type '%s'.", p_td.name);
    JSON_Tokenizer tok(va_arg(pvar, int) != 0);
843
    JSON_encode(p_td, tok, FALSE);
Elemer Lelik's avatar
Elemer Lelik committed
844
845
    p_buf.put_s(tok.get_buffer_length(), (const unsigned char*)tok.get_buffer());
    break;}
846
847
848
849
850
851
  case TTCN_EncDec::CT_OER: {
    TTCN_EncDec_ErrorContext ec("While OER-encoding type '%s': ", p_td.name);
    if(!p_td.oer)  TTCN_EncDec_ErrorContext::error_internal(
      "No OER descriptor available for type '%s'.", p_td.name);
    OER_encode(p_td, p_buf);
    break;}
Elemer Lelik's avatar
Elemer Lelik committed
852
853
854
855
856
857
858
859
860
  default:
    TTCN_error("Unknown coding method requested to encode type '%s'",
               p_td.name);
  }
  va_end(pvar);
}

void CHARSTRING::decode(const TTCN_Typedescriptor_t& p_td,
                        TTCN_Buffer& p_buf,
861
                        int p_coding, ...)
Elemer Lelik's avatar
Elemer Lelik committed
862
863
{
  va_list pvar;
864
  va_start(pvar, p_coding);
Elemer Lelik's avatar
Elemer Lelik committed
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
  switch(p_coding) {
  case TTCN_EncDec::CT_BER: {
    TTCN_EncDec_ErrorContext ec("While BER-decoding type '%s': ", p_td.name);
    unsigned L_form=va_arg(pvar, unsigned);
    ASN_BER_TLV_t tlv;
    BER_decode_str2TLV(p_buf, tlv, L_form);
    BER_decode_TLV(p_td, tlv, L_form);
    if(tlv.isComplete) p_buf.increase_pos(tlv.get_len());
    break;}
  case TTCN_EncDec::CT_RAW: {
    TTCN_EncDec_ErrorContext ec("While RAW-decoding type '%s': ", p_td.name);
    if(!p_td.raw)
      TTCN_EncDec_ErrorContext::error_internal
        ("No RAW descriptor available for type '%s'.", p_td.name);
    raw_order_t order;
    switch(p_td.raw->top_bit_order){
    case TOP_BIT_LEFT:
      order=ORDER_LSB;
      break;
    case TOP_BIT_RIGHT:
    default:
      order=ORDER_MSB;
    }
    if(RAW_decode(p_td, p_buf, p_buf.get_len()*8, order)<0)
      ec.error(TTCN_EncDec::ET_INCOMPL_MSG,
               "Can not decode type '%s', because invalid or incomplete"
               " message was received"
               , p_td.name);
    break;}
  case TTCN_EncDec::CT_TEXT: {
    Limit_Token_List limit;
    TTCN_EncDec_ErrorContext ec("While TEXT-decoding type '%s': ", p_td.name);
    if(!p_td.text)
      TTCN_EncDec_ErrorContext::error_internal
        ("No TEXT descriptor available for type '%s'.", p_td.name);
    const unsigned char *b=p_buf.get_data();
901
    int null_added=0;
Elemer Lelik's avatar
Elemer Lelik committed
902
    if(b[p_buf.get_len()-1]!='\0'){
903
      null_added=1;
Elemer Lelik's avatar
Elemer Lelik committed
904
905
906
907
908
909
910
911
912
      p_buf.set_pos(p_buf.get_len());
      p_buf.put_zero(8,ORDER_LSB);
      p_buf.rewind();
    }
    if(TEXT_decode(p_td,p_buf,limit)<0)
      ec.error(TTCN_EncDec::ET_INCOMPL_MSG,
               "Can not decode type '%s', because invalid or incomplete"
               " message was received"
               , p_td.name);
913
914
915
916
917
918
    if(null_added){
      size_t actpos=p_buf.get_pos();
      p_buf.set_pos(p_buf.get_len()-1);
      p_buf.cut_end();
      p_buf.set_pos(actpos);
    }
Elemer Lelik's avatar
Elemer Lelik committed
919
920
    break;}
  case TTCN_EncDec::CT_XER: {
Elemer Lelik's avatar
Elemer Lelik committed
921
    TTCN_EncDec_ErrorContext ec("While XER-decoding type '%s': ", p_td.name);
Elemer Lelik's avatar
Elemer Lelik committed
922
923
924
925
926
927
928
929
    unsigned XER_coding=va_arg(pvar, unsigned);
    XmlReaderWrap reader(p_buf);
    int success = reader.Read();
    for (; success==1; success=reader.Read()) {
      int type = reader.NodeType();
      if (type==XML_READER_TYPE_ELEMENT)
	break;
    }
Elemer Lelik's avatar
Elemer Lelik committed
930
    XER_decode(*p_td.xer, reader, XER_coding, XER_NONE, 0);
Elemer Lelik's avatar
Elemer Lelik committed
931
932
933
934
935
936
937
938
939
    size_t bytes = reader.ByteConsumed();
    p_buf.set_pos(bytes);
    break;}
  case TTCN_EncDec::CT_JSON: {
    TTCN_EncDec_ErrorContext ec("While JSON-decoding type '%s': ", p_td.name);
    if(!p_td.json)
      TTCN_EncDec_ErrorContext::error_internal
        ("No JSON descriptor available for type '%s'.", p_td.name);
    JSON_Tokenizer tok((const char*)p_buf.get_data(), p_buf.get_len());
940
    if(JSON_decode(p_td, tok, FALSE, FALSE)<0)
Elemer Lelik's avatar
Elemer Lelik committed
941
942
943
944
945
946
      ec.error(TTCN_EncDec::ET_INCOMPL_MSG,
               "Can not decode type '%s', because invalid or incomplete"
               " message was received"
               , p_td.name);
    p_buf.set_pos(tok.get_buf_pos());
    break;}
947
948
949
950
951
952
953
  case TTCN_EncDec::CT_OER: {
    TTCN_EncDec_ErrorContext ec("While OER-decoding type '%s': ", p_td.name);
    if(!p_td.oer)  TTCN_EncDec_ErrorContext::error_internal(
      "No OER descriptor available for type '%s'.", p_td.name);
    OER_struct p_oer;
    OER_decode(p_td, p_buf, p_oer);
    break;}
Elemer Lelik's avatar
Elemer Lelik committed
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
  default:
    TTCN_error("Unknown coding method requested to decode type '%s'",
               p_td.name);
  }
  va_end(pvar);
}

ASN_BER_TLV_t*
CHARSTRING::BER_encode_TLV(const TTCN_Typedescriptor_t& p_td,
                           unsigned p_coding) const
{
  BER_chk_descr(p_td);
  ASN_BER_TLV_t *new_tlv=BER_encode_chk_bound(is_bound());
  if(!new_tlv) {
    new_tlv=BER_encode_TLV_OCTETSTRING
      (p_coding, val_ptr->n_chars,
       (const unsigned char*)val_ptr->chars_ptr);
  }
  new_tlv=ASN_BER_V2TLV(new_tlv, p_td, p_coding);
  return new_tlv;
}

boolean CHARSTRING::BER_decode_TLV(const TTCN_Typedescriptor_t& p_td,
                                   const ASN_BER_TLV_t& p_tlv,
                                   unsigned L_form)
{
  clean_up();
  BER_chk_descr(p_td);
  ASN_BER_TLV_t stripped_tlv;
  BER_decode_strip_tags(*p_td.ber, p_tlv, L_form, stripped_tlv);
  TTCN_EncDec_ErrorContext ec("While decoding CHARSTRING type: ");
  /* Upper estimation for the length. */
  size_t stripped_tlv_len = stripped_tlv.get_len();
  if (stripped_tlv_len < 2) return FALSE;
  int max_len = stripped_tlv_len - 2;
  init_struct(max_len);
  unsigned int octetnum_start = 0;
  BER_decode_TLV_OCTETSTRING(stripped_tlv, L_form, octetnum_start,
                             val_ptr->n_chars,
                             (unsigned char*)val_ptr->chars_ptr);
  if (val_ptr->n_chars < max_len) {
    if (val_ptr->n_chars == 0) {
      clean_up();
      init_struct(0);
    } else {
      val_ptr = (charstring_struct*)
	Realloc(val_ptr, MEMORY_SIZE(val_ptr->n_chars));
      val_ptr->chars_ptr[val_ptr->n_chars] = '\0';
    }
  }
  return TRUE;
}

int CHARSTRING::TEXT_decode(const TTCN_Typedescriptor_t& p_td,
  TTCN_Buffer& buff, Limit_Token_List& limit, boolean no_err, boolean /*first_call*/)
{
  int decoded_length = 0;
  int str_len = 0;
  clean_up();
  if (p_td.text->begin_decode) {
    int tl;
    if ((tl = p_td.text->begin_decode->match_begin(buff)) < 0) {
      if (no_err) return -1;
      TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_TOKEN_ERR,
        "The specified token '%s' not found for '%s': ",
        (const char*) *(p_td.text->begin_decode), p_td.name);
      return 0;
    }
    decoded_length += tl;
    buff.increase_pos(tl);
  }
  //  never return "not enough bits"
  //  if(buff.get_read_len()<=1 && no_err) return -TTCN_EncDec::ET_LEN_ERR;

  if (p_td.text->select_token) {
    int tl;
    if ((tl = p_td.text->select_token->match_begin(buff)) < 0) {
      if (no_err) return -1;
      else tl = 0;
    }
    str_len = tl;
  }
  else if (   p_td.text->val.parameters
    &&        p_td.text->val.parameters->decoding_params.min_length != -1) {
    str_len = p_td.text->val.parameters->decoding_params.min_length;
  }
  else if (p_td.text->end_decode) {
    int tl;
    if ((tl = p_td.text->end_decode->match_first(buff)) < 0) {
      if (no_err) return -1;
      else tl = 0;
    }
    str_len = tl;
  }
  else if (limit.has_token()) {
    int tl;
    if ((tl = limit.match(buff)) < 0) tl = buff.get_read_len() - 1;
    str_len = tl;
  }
  else {
    str_len = buff.get_read_len() - 1;
  }

  init_struct(str_len);
  memcpy(val_ptr->chars_ptr, buff.get_read_data(), str_len);
  decoded_length += str_len;
  buff.increase_pos(str_len);

  if (  p_td.text->val.parameters
    &&  p_td.text->val.parameters->decoding_params.convert != 0) {
    if (p_td.text->val.parameters->decoding_params.convert == 1) {
      for (int a = 0; a < str_len; a++) {
1066
        val_ptr->chars_ptr[a] = (char)toupper(val_ptr->chars_ptr[a]);
Elemer Lelik's avatar
Elemer Lelik committed
1067
1068
1069
1070
      }
    }
    else {
      for (int a = 0; a < str_len; a++) {
1071
        val_ptr->chars_ptr[a] = (char)tolower(val_ptr->chars_ptr[a]);
Elemer Lelik's avatar
Elemer Lelik committed
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
      }
    }
  }
  if (p_td.text->end_decode) {
    int tl;
    if ((tl = p_td.text->end_decode->match_begin(buff)) < 0) {
      if (no_err) return -1;
      TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_TOKEN_ERR,
        "The specified token '%s' not found for '%s': ",
        (const char*) *(p_td.text->end_decode), p_td.name);
      return 0;
    }
    decoded_length += tl;
    buff.increase_pos(tl);
  }
  return decoded_length;
}

int CHARSTRING::TEXT_encode(const TTCN_Typedescriptor_t& p_td,
                 TTCN_Buffer& buff) const{
  int encoded_length=0;
  if(p_td.text->begin_encode){
    buff.put_cs(*p_td.text->begin_encode);
    encoded_length+=p_td.text->begin_encode->lengthof();
  }
  if(!is_bound()) {
    TTCN_EncDec_ErrorContext::error
      (TTCN_EncDec::ET_UNBOUND, "Encoding an unbound value.");
    if(p_td.text->end_encode){
      buff.put_cs(*p_td.text->end_encode);
      encoded_length+=p_td.text->end_encode->lengthof();
    }
    return encoded_length;
  }

  if(p_td.text->val.parameters==NULL){
    buff.put_cs(*this);
    encoded_length+=val_ptr->n_chars;
  } else {
    int chars_before=0;
    int chars_after=0;
    if(val_ptr->n_chars<p_td.text->val.parameters->coding_params.min_length){
      switch(p_td.text->val.parameters->coding_params.just){
        case -1: //left
          chars_after=p_td.text->
              val.parameters->coding_params.min_length-val_ptr->n_chars;
          break;
        case 0:{  // center
          int pad=p_td.text->
              val.parameters->coding_params.min_length-val_ptr->n_chars;
          chars_after=pad/2;
          chars_before=pad-chars_after;
          break;
          }
        case 1:  // right
        default:
          chars_before=p_td.text->
              val.parameters->coding_params.min_length-val_ptr->n_chars;
          break;
      }
    }
    if(chars_before){
      unsigned char* p=NULL;
      size_t len=chars_before;
      buff.get_end(p,len);
      for(int a=0;a<chars_before;a++) p[a]=(unsigned char)' ';
      buff.increase_length(chars_before);
      encoded_length+=chars_before;
    }

    switch(p_td.text->val.parameters->coding_params.convert){
      case -1:{ //lower_case
        unsigned char* p=NULL;
        size_t len=val_ptr->n_chars;
        buff.get_end(p,len);
        for(int a=0;a<val_ptr->n_chars;a++)
            p[a]=(unsigned char)tolower(val_ptr->chars_ptr[a]);
        buff.increase_length(val_ptr->n_chars);
        break;
        }
      case 0:{  // no conversion
        buff.put_cs(*this);
        break;
        }
      case 1:  // upper_case
      default:
        {
        unsigned char* p=NULL;
        size_t len=val_ptr->n_chars;
        buff.get_end(p,len);
        for(int a=0;a<val_ptr->n_chars;a++)
            p[a]=(unsigned char)toupper(val_ptr->chars_ptr[a]);
        buff.increase_length(val_ptr->n_chars);
        break;
        }
    }
    encoded_length+=val_ptr->n_chars;

    if(chars_after){
      unsigned char* p=NULL;
      size_t len=chars_after;
      buff.get_end(p,len);
      for(int a=0;a<chars_after;a++) p[a]=(unsigned char)' ';
      buff.increase_length(chars_after);
      encoded_length+=chars_after;
    }

  }

  if(p_td.text->end_encode){
    buff.put_cs(*p_td.text->end_encode);
    encoded_length+=p_td.text->end_encode->lengthof();
  }
  return encoded_length;
}

#ifdef TITAN_RUNTIME_2
int CHARSTRING::encode_raw(TTCN_Buffer& p_buf) const
{
  p_buf.put_string(*this);
  return val_ptr ? val_ptr->n_chars : 0;
}
Elemer Lelik's avatar
Elemer Lelik committed
1194
1195
1196
1197
1198
1199
1200
1201
1202

int CHARSTRING::JSON_encode_negtest_raw(JSON_Tokenizer& p_tok) const
{
  if (val_ptr != NULL) {
    p_tok.put_raw_data(val_ptr->chars_ptr, val_ptr->n_chars);
    return val_ptr->n_chars;
  }
  return 0;
}
Elemer Lelik's avatar
Elemer Lelik committed
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
#endif


void xml_escape(const unsigned int masked_c, TTCN_Buffer& p_buf)
{
  size_t len = 6;
  // length of the majority of the names of control characters, +3 for </>
  static const char *escapes[32] = {
    "<nul/>","<soh/>","<stx/>","<etx/>","<eot/>","<enq/>","<ack/>","<bel/>",
    "<bs/>" ,"<tab/>","<lf/>" ,"<vt/>" ,"<ff/>" ,"<cr/>" ,"<so/>" ,"<si/>" ,
    "<dle/>","<dc1/>","<dc2/>","<dc3/>","<dc4/>","<nak/>","<syn/>","<etb/>",
    "<can/>","<em/>" ,"<sub/>","<esc/>","<is4/>","<is3/>","<is2/>","<is1/>",
  };
  unsigned int c = (masked_c & 0x7FFFFFFF); // unmasked

  switch (c) {
  // XML's "own" characters, escaped according to X.680/2002, 11.15.4 b)
  case '<':
    p_buf.put_s(4, (cbyte*)"&lt;");
    break;

  case '>':
    p_buf.put_s(4, (cbyte*)"&gt;");
    break;

  case '&':
    p_buf.put_s(5, (cbyte*)"&amp;");
    break;

    // Control characters, escaped according to X.680/2002, 11.15.5
  case  8: case 11: case 12: case 14: case 15: case 25:
    // the name of these control characters has only two letters
    --len;
    // no break
  case  0: case  1: case  2: case  3: case  4: case  5: case  6: case  7:
  case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23:
  case 24:          case 26: case 27: case 28: case 29: case 30: case 31:
    // 9=TAB 10=LF 13=CR are absent from this block altogether
    p_buf.put_s(len, (cbyte*)escapes[c]);
    break;

  case '\"': // HR58225
    p_buf.put_s(6, (cbyte*)"&quot;");
    break;

  case '\'': // X.693 20.3.13: Titan uses single quotes for attributes;
    // so if they appear in content they must be escaped.
    // Currently this happens even if the string is not an attribute.
    p_buf.put_s(6, (cbyte*)"&apos;");
    break;

  case 9: case 10: case 13:
    c = masked_c; // put the mask back on (makes it >127)
    // no break
  default:
    if (c > 127) { // XML numeric entity, as in X.680/2002 11.15.8
      c &= 0x7FFFFFFF; // take it off again
      // Ensure that an even number of hex digits is produced
      int width = (1 + (c > 0xFF) + (c > 0xFFFF) + (c > 0xFFFFFF)) << 1;
      char escapade[16];
      len = snprintf(escapade, 16, "&#x%0*X;", width, c);
      p_buf.put_s(len, (cbyte*)(escapade+0));
    }
    else { // a plain old, unmolested character
      p_buf.put_c(c);
    }
    break;
  }
}

// Base64 encoder table
extern const char cb64[]=
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

int CHARSTRING::XER_encode(const XERdescriptor_t& p_td,
1278
                 TTCN_Buffer& p_buf, unsigned int flavor, unsigned int /*flavor2*/, int indent, embed_values_enc_struct_t*) const
Elemer Lelik's avatar
Elemer Lelik committed
1279
1280
1281
1282
1283
1284
1285
1286
{
  if(!is_bound()) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_UNBOUND,
      "Encoding an unbound character string value.");
  }
  int exer  = is_exer(flavor |= SIMPLE_TYPE);
  // SIMPLE_TYPE has no influence on is_exer, we set it for later
  int encoded_length=(int)p_buf.get_len();
1287
  boolean do_empty_element = val_ptr==NULL || val_ptr->n_chars == 0;
Elemer Lelik's avatar
Elemer Lelik committed
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356

  flavor &= ~XER_RECOF; // charstring doesn't care

  if (do_empty_element && exer && p_td.dfeValue != 0) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_REPR,
      "An encoded value with DEFAULT-FOR-EMPTY instruction applied should not be empty");
  }
  if (begin_xml(p_td, p_buf, flavor, indent, do_empty_element) == -1) {
    --encoded_length; // it was shortened by one
  }

  if (!do_empty_element) {
    const char * current   = val_ptr->chars_ptr;
    const char * const end = val_ptr->chars_ptr + val_ptr->n_chars;
    const char * to_escape;
    unsigned int mask;
    if (exer && (p_td.xer_bits & XER_ATTRIBUTE)) {
      to_escape = "<&>'\"\x09\x0A\x0D";
      mask = 0x80000000; // guaranteed bigger than any Unicode character
    }
    else {
      to_escape = "<&>'\"";
      mask = 0;
    }

    // If Base64 is needed, use a temporary buffer.
    TTCN_Buffer tmpbuf, &rbuf = (exer && (p_td.xer_bits & BASE_64)) ? tmpbuf : p_buf;

    // This here is an optimization. Only &lt;&amp;&gt; need to be escaped.
    // Contiguous runs of "ordinary" characters are put in the buffer
    // with a single call.
    // TODO: is it really faster ? strpbrk is probably O(nm)
    while ( const char * trouble = strpbrk(current, to_escape) ) {
      rbuf.put_s((size_t)(trouble - current), (cbyte*)current);
      xml_escape(*trouble | mask, rbuf); // escape the troublesome character
      current = trouble+1;
    }

    // put the remainder in the buffer
    rbuf.put_s( (size_t)(end - current), (cbyte*)current);

    if (exer && (p_td.xer_bits & BASE_64)) {
      size_t clear_len = tmpbuf.get_len(); // the length before padding
      // Pad the temporary buffer so i+1 and i+2 don't go outside the buffer
      unsigned char zero[2] = {0,0};
      tmpbuf.put_s(2, zero);
      // Get the buffer after the possible realloc caused by the padding.
      cbyte * in = tmpbuf.get_data();

      // Encode 3 bytes of cleartext into 4 bytes of Base64
      for (size_t i = 0; i < clear_len; i += 3) {
        p_buf.put_c( cb64[ in[i] >> 2 ] );
        p_buf.put_c( cb64[ ((in[i] & 0x03) << 4) | ((in[i+1] & 0xf0) >> 4) ]);
        p_buf.put_c( i+1 < clear_len
          ? cb64[ ((in[i+1] & 0x0f) << 2) | ((in[i+2] & 0xc0) >> 6) ]
                  : '=' );
        p_buf.put_c( i+2 < clear_len ? cb64[ in[i+2] & 0x3f ] : '=' );
      } // next i
    } // if base64
  }

  end_xml(p_td, p_buf, flavor, indent, do_empty_element);
  return (int)p_buf.get_len() - encoded_length;
}

/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
* Public domain from http://iharder.net/base64 */
1357
signed char  base64_decoder_table[256] =
Elemer Lelik's avatar
Elemer Lelik committed
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
{
  -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8
  -5,-5,                                      // Whitespace: Tab and Linefeed
  -9,-9,                                      // Decimal 11 - 12
  -5,                                         // Whitespace: Carriage Return
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26
  -9,-9,-9,-9,-9,                             // Decimal 27 - 31
  -5,                                         // Whitespace: Space
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42
  62,                                         // Plus sign at decimal 43
  -9,-9,-9,                                   // Decimal 44 - 46
  63,                                         // Slash at decimal 47
  52,53,54,55,56,57,58,59,60,61,              // Numbers zero through nine
  -9,-9,-9,                                   // Decimal 58 - 60
  -1,                                         // Equals sign at decimal 61
  -9,-9,-9,                                   // Decimal 62 - 64
  0,1,2,3,4,5,6,7,8,9,10,11,12,13,            // Letters 'A' through 'N'
  14,15,16,17,18,19,20,21,22,23,24,25,        // Letters 'O' through 'Z'
  -9,-9,-9,-9,-9,-9,                          // Decimal 91 - 96
  26,27,28,29,30,31,32,33,34,35,36,37,38,     // Letters 'a' through 'm'
  39,40,41,42,43,44,45,46,47,48,49,50,51,     // Letters 'n' through 'z'
  -9,-9,-9,-9,-9                              // Decimal 123 - 127
  ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,       // Decimal 128 - 139
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243
  -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255
};

unsigned int xlate(cbyte*in, int phase, unsigned char*dest) {
  static unsigned char nbytes[4] = { 3,1,1,2 };
  unsigned char out[4];
  out[0] = in[0] << 2 | in[1] >> 4;
  out[1] = in[1] << 4 | in[2] >> 2;
  out[2] = in[2] << 6 | in[3] >> 0;
  memcpy(dest, out, nbytes[phase]);
  return nbytes[phase];
}

int CHARSTRING::XER_decode(const XERdescriptor_t& p_td, XmlReaderWrap& reader,
Elemer Lelik's avatar
Elemer Lelik committed
1403
                           unsigned int flavor, unsigned int /*flavor2*/, embed_values_dec_struct_t*) {
Elemer Lelik's avatar
Elemer Lelik committed
1404
  int exer = is_exer(flavor);
1405
  
Elemer Lelik's avatar
Elemer Lelik committed
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
  if (exer && (p_td.xer_bits & XER_ATTRIBUTE)) {
    const char * name = verify_name(reader, p_td, exer);
    (void)name;
    const char * value = (const char *)reader.Value();
    // FIXME copy & paste
    *this = value;

    // Let the caller do reader.AdvanceAttribute();
  }
  else {
1416
    boolean omit_tag = exer
Elemer Lelik's avatar
Elemer Lelik committed
1417
      && (p_td.xer_bits & UNTAGGED || flavor & (EMBED_VALUES|XER_LIST|USE_TYPE_ATTR|USE_NIL));
1418
    int success = reader.Ok(), depth = -1;
Elemer Lelik's avatar
Elemer Lelik committed
1419
1420
1421
    for (; success == 1; success = reader.Read()) {
      int type = reader.NodeType();
      if (XML_READER_TYPE_ELEMENT == type) {
1422
1423
1424
1425
1426
        // If our parent is optional and there is an unexpected tag then return and
        // we stay unbound.
        if ((flavor & XER_OPTIONAL) && !check_name((const char*)reader.LocalName(), p_td, exer)) {
          return -1;
        }
Elemer Lelik's avatar
Elemer Lelik committed
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
        verify_name(reader, p_td, exer);
        if (reader.IsEmptyElement()) { // has no text, needs special processing
          if (exer && p_td.dfeValue != 0) {
            *this = *static_cast<const CHARSTRING*>(p_td.dfeValue);
          }
          else init_struct(0);
          reader.Read();
          break; // exit the loop early
        } // if empty element
        // otherwise, not an empty element, stay in the loop
        depth = reader.Depth();
      }
      else if ((depth != -1 || omit_tag)
1440
1441
        && (XML_READER_TYPE_TEXT == type || XML_READER_TYPE_CDATA == type ||
            (omit_tag && XML_READER_TYPE_ATTRIBUTE == type)))
Elemer Lelik's avatar
Elemer Lelik committed
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
        // Process #text node if we already processed the element node, or
        // there is no element node because UNTAGGED is in effect.
      {
        const xmlChar * value = reader.Value();
        size_t num_chars = strlen((const char*)value);

        if (exer && (p_td.xer_bits & BASE_64)) {
          clean_up();
          init_struct(num_chars * 3 / 4);
          xmlChar in[4];

          int phase = 0;
          unsigned char * dest = (unsigned char *)val_ptr->chars_ptr;

          for (size_t o=0; o<num_chars; ++o) {
            xmlChar c = value[o];
            if(c == '=') { // Padding starts; decode last chunk and exit.
              dest += xlate(in,phase, dest);
              break;
            }

            int val = base64_decoder_table[c];
            if(val >= 0)    {
              in[phase] = val;
              phase = (phase + 1) % 4;
              if(phase == 0) {
                dest += xlate(in,phase, dest);
                in[0]=in[1]=in[2]=in[3]=0;
              }
            }
            else if (exer && (flavor & EXIT_ON_ERROR)) {
              clean_up();
              return -1;
            } else {
              TTCN_EncDec_ErrorContext::warning(
                /* if this was an error... TTCN_EncDec::ET_INVAL_MSG,*/
                "Invalid character for Base64 '%02X'", c);
            }
          } // while
          // adjust
          val_ptr->n_chars = (char*)dest - val_ptr->chars_ptr;
        }
        else {
          clean_up();
          init_struct(num_chars);
          memcpy(val_ptr->chars_ptr, value, num_chars);
        } // if base64

        if(!omit_tag) {
          // find the end element
          for (success = reader.Read(); success == 1; success = reader.Read()) {
            type = reader.NodeType();
            if (XML_READER_TYPE_END_ELEMENT == type) {
              verify_end(reader, p_td, depth, exer);
              reader.Read(); // one last time
              break;
            }
          }
        }
        break;
      }
      else if (XML_READER_TYPE_END_ELEMENT == type) {
        if (!omit_tag) {
          verify_end(reader, p_td, depth, exer);
          if (!val_ptr) {
            // We are at our end tag and no content
            if (exer && p_td.dfeValue != 0) {
              *this = *static_cast<const CHARSTRING*>(p_td.dfeValue);
            }
            else init_struct(0); // empty string
          }
          reader.Read();
        }
        break;
      } // if type
    } // next read
  } // if attribute

  if (exer && p_td.whitespace >= WHITESPACE_REPLACE) { // includes _COLLAPSE
    for (int i=0; i<val_ptr->n_chars; ++i) { // first, _REPLACE
      switch (val_ptr->chars_ptr[i]) {
      case 9:  // HORIZONTAL TAB
      case 10: // LINE FEED
      case 13: // CARRIAGE RETURN
        val_ptr->chars_ptr[i] = ' ';
        break;
      default:
        break;
      }
    } // next i

    if (p_td.whitespace >= WHITESPACE_COLLAPSE) {
      char *to;
      const char *from, *end = val_ptr->chars_ptr + val_ptr->n_chars;
      for (from = to = val_ptr->chars_ptr; from < end;) {
        *to = *(from++);
        // If the copied character (*to) was a space,
        // and the next character to be copied (*from) is also a space
        //     (continuous run of spaces)
        //   or this was the first character (leading spaces to be trimmed),
        // then don't advance the destination (will be overwritten).
        if (*to != ' '
          || (from < end && *from != ' ' && to > val_ptr->chars_ptr)) ++to;
      }
      *to = 0;
      val_ptr->n_chars = to - val_ptr->chars_ptr; // truncate
      // TODO maybe realloc after truncation
    } // collapse
  } // if WHITESPACE
  
  return 1;
}

int CHARSTRING::RAW_encode(const TTCN_Typedescriptor_t& p_td,
  RAW_enc_tree& myleaf) const
{
  int bl = val_ptr->n_chars * 8; // bit length
1559
  int align_length = p_td.raw->fieldlength>0 ? p_td.raw->fieldlength - bl : 0;
Elemer Lelik's avatar
Elemer Lelik committed
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
  if (!is_bound()) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_UNBOUND,
      "Encoding an unbound value.");
  }
  if ((bl + align_length) < val_ptr->n_chars * 8) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_LEN_ERR,
      "There is no sufficient bits to encode '%s': ", p_td.name);
    bl = p_td.raw->fieldlength;
    align_length = 0;
  }
  if (myleaf.must_free) Free(myleaf.body.leaf.data_ptr);
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
  if(p_td.raw->fieldlength>=0){
    myleaf.must_free = FALSE;
    myleaf.data_ptr_used = TRUE;
    myleaf.body.leaf.data_ptr = (unsigned char*) val_ptr->chars_ptr;
  } else {
    // NULL terminated
    myleaf.body.leaf.data_ptr = (unsigned char*)Malloc( val_ptr->n_chars + 1 );
    memcpy(myleaf.body.leaf.data_ptr, val_ptr->chars_ptr , val_ptr->n_chars);
    myleaf.body.leaf.data_ptr[val_ptr->n_chars] = 0;
    myleaf.must_free = TRUE;
    myleaf.data_ptr_used = TRUE;
    bl+=8;
  }
Elemer Lelik's avatar
Elemer Lelik committed
1584
1585
  if (p_td.raw->endianness == ORDER_MSB) myleaf.align = -align_length;
  else myleaf.align = align_length;
1586
  myleaf.coding_par.csn1lh = p_td.raw->csn1lh;
Elemer Lelik's avatar
Elemer Lelik committed
1587
1588
1589
1590
1591
  return myleaf.length = bl + align_length;
}

int CHARSTRING::RAW_decode(const TTCN_Typedescriptor_t& p_td,
  TTCN_Buffer& buff, int limit, raw_order_t top_bit_ord, boolean no_err,
1592
  int /*sel_field*/, boolean /*first_call*/, const RAW_Force_Omit* /*force_omit*/)
Elemer Lelik's avatar
Elemer Lelik committed
1593
1594
1595
{
  int prepaddlength = buff.increase_pos_padd(p_td.raw->prepadding);
  limit -= prepaddlength;
1596
  int decode_length = p_td.raw->fieldlength <= 0
Elemer Lelik's avatar
Elemer Lelik committed
1597
    ? (limit / 8) * 8 : p_td.raw->fieldlength;
1598

Elemer Lelik's avatar
Elemer Lelik committed
1599
1600
1601
1602
1603
1604
1605
1606
  if ( decode_length > limit
    || decode_length > (int) buff.unread_len_bit()) {
    if (no_err) return -TTCN_EncDec::ET_LEN_ERR;
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_LEN_ERR,
      "There is not enough bits in the buffer to decode type %s.", p_td.name);
    decode_length = ((limit > (int) buff.unread_len_bit() ? (int)buff.unread_len_bit() : limit) / 8) * 8;
  }
  RAW_coding_par cp;
Kristof Szabados's avatar
Kristof Szabados committed
1607
  boolean orders = p_td.raw->bitorderinoctet == ORDER_MSB;
Elemer Lelik's avatar
Elemer Lelik committed
1608
1609
  if (p_td.raw->bitorderinfield == ORDER_MSB) orders = !orders;
  cp.bitorder = orders ? ORDER_MSB : ORDER_LSB;
Kristof Szabados's avatar
Kristof Szabados committed
1610
  orders = p_td.raw->byteorder == ORDER_MSB;
Elemer Lelik's avatar
Elemer Lelik committed
1611
1612
1613
1614
  if (p_td.raw->bitorderinfield == ORDER_MSB) orders = !orders;
  cp.byteorder = orders ? ORDER_MSB : ORDER_LSB;
  cp.fieldorder = p_td.raw->fieldorder;
  cp.hexorder = ORDER_LSB;
1615
  cp.csn1lh = p_td.raw->csn1lh;
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
  if(p_td.raw->fieldlength >= 0){
    clean_up();
    init_struct(decode_length / 8);
    buff.get_b((size_t) decode_length, (unsigned char*) val_ptr->chars_ptr, cp,
      top_bit_ord);
  } else {
    // NULL terminated
    TTCN_Buffer temp_buff;
    unsigned char ch=0;
    int str_len=0;
    int null_found=0;
    while( str_len<decode_length ){
      buff.get_b(8, &ch, cp, top_bit_ord);
      if(ch == 0 ){
        null_found=1;
        break;
      }
      temp_buff.put_c(ch);
      str_len+=8;
    }
    if(null_found==0){
      return -1;
    }
    temp_buff.get_string(*this);
    decode_length=str_len+8;
  }
1642
1643
  if (p_td.raw->length_restrition != -1 &&
      decode_length > p_td.raw->length_restrition) {
Elemer Lelik's avatar
Elemer Lelik committed
1644
1645
1646
1647
1648
1649
1650
1651
1652
    val_ptr->n_chars = p_td.raw->length_restrition;
    if (p_td.raw->endianness == ORDER_MSB) memmove(val_ptr->chars_ptr,
      val_ptr->chars_ptr + (decode_length / 8 - val_ptr->n_chars),
      val_ptr->n_chars); // sizeof(char) == 1 by definition
  }
  decode_length += buff.increase_pos_padd(p_td.raw->padding);
  return decode_length + prepaddlength;
}

1653
char* CHARSTRING::to_JSON_string(json_string_escaping mode) const
Elemer Lelik's avatar
Elemer Lelik committed
1654
{
1655
  char* json_str = mprintf("\"");
Elemer Lelik's avatar
Elemer Lelik committed
1656
1657
  
  for (int i = 0; i < val_ptr->n_chars; ++i) {
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
    if (mode != ESCAPE_AS_USI) {
      switch(val_ptr->chars_ptr[i]) {
      case '\n':
        json_str = mputstrn(json_str, "\\n", 2);
        break;
      case '\t':
        json_str = mputstrn(json_str, "\\t", 2);
        break;
      case '\r':
        json_str = mputstrn(json_str, "\\r", 2);
        break;
      case '\f':
        json_str = mputstrn(json_str, "\\f", 2);
        break;
      case '\b':
        json_str = mputstrn(json_str, "\\b", 2);
        break;
      case '\"':
        json_str = mputstrn(json_str, "\\\"", 2);
        break;
      case '\\':
        if (mode == ESCAPE_AS_SHORT) {
          json_str = mputstrn(json_str, "\\\\", 2);
          break;
        }
        // fall through (to the default branch) if ESCAPE_AS_TRANSPARENT
      case '/':
        if (mode == ESCAPE_AS_SHORT) {
          json_str = mputstrn(json_str, "\\/", 2);
          break;
        }
        // fall through if ESCAPE_AS_TRANSPARENT
      default:
1691
1692
        if ((val_ptr->chars_ptr[i] >= 0 && val_ptr->chars_ptr[i] <= 0x1F) ||
            val_ptr->chars_ptr[i] == 0x7F) {
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
          // C0 control characters use USI-like escape sequences
          json_str = mputprintf(json_str, "\\u00%X%X",
            val_ptr->chars_ptr[i] / 16, val_ptr->chars_ptr[i] % 16);
        }
        else {
          json_str = mputc(json_str, val_ptr->chars_ptr[i]);
        }
        break;
      }
    }
    else { // ESCAPE_AS_USI
      if (val_ptr->chars_ptr[i] <= 0x20 || val_ptr->chars_ptr[i] == '\"' ||
          val_ptr->chars_ptr[i] == '\\' || val_ptr->chars_ptr[i] == 0x7F) {
        json_str = mputprintf(json_str, "\\u00%X%X",
          val_ptr->chars_ptr[i] / 16, val_ptr->chars_ptr[i] % 16);
      }
      else {
        json_str = mputc(json_str, (char)val_ptr->chars_ptr[i]);
      }
Elemer Lelik's avatar
Elemer Lelik committed
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
    }
  }
  
  json_str = mputc(json_str, '\"');
  return json_str;
}

boolean CHARSTRING::from_JSON_string(const char* p_value, size_t p_value_len, boolean check_quotes)
{
  size_t start = 0;
  size_t end = p_value_len;
  if (check_quotes) {
    start = 1;
    end = p_value_len - 1;
    if (p_value[0] != '\"' || p_value[p_value_len - 1] != '\"') {
1727
      return FALSE;
Elemer Lelik's avatar
Elemer Lelik committed
1728
1729
1730
    }
  }
  
1731
  // The resulting string (its length is less than or equal to end - start)
Elemer Lelik's avatar
Elemer Lelik committed
1732
1733
  char* str = (char*)Malloc(end - start);
  size_t len = 0;
1734
  boolean error = FALSE;
Elemer Lelik's avatar
Elemer Lelik committed
1735
1736
1737
  
  for (size_t i = start; i < end; ++i) {
    if (0 > p_value[i]) {
1738
      error = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
1739
1740
1741
1742
      break;
    }
    if ('\\' == p_value[i]) {
      if (i == end - 1) {
1743
        error = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
        break;
      }
      switch(p_value[i + 1]) {
      case 'n':
        str[len++] = '\n';
        break;
      case 't':
        str[len++] = '\t';
        break;
      case 'r':
        str[len++] = '\r';
        break;
      case 'f':
        str[len++] = '\f';
        break;
      case 'b':
        str[len++] = '\b';
        break;
      case '\\':
        str[len++] = '\\';
        break;
      case '\"':
        str[len++] = '\"';
        break;
      case '/':
        str[len++] = '/';
        break;
      case 'u': {
        if (end - i >= 6 && '0' == p_value[i + 2] && '0' == p_value[i + 3]) {
          unsigned char upper_nibble = char_to_hexdigit(p_value[i + 4]);
          unsigned char lower_nibble = char_to_hexdigit(p_value[i + 5]);
          if (0x07 >= upper_nibble && 0x0F >= lower_nibble) {
            str[len++] = (upper_nibble << 4) | lower_nibble;
            // skip 4 extra characters (the 4 hex digits)
            i += 4;
          } else {
            // error (found something other than hex digits) -> leave the for cycle
            i = end;
1782
            error = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
1783
1784
1785
1786
          }
        } else {
          // error (not enough characters left or the first 2 hex digits are non-null) -> leave the for cycle
          i = end;
1787
          error = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
1788
1789
1790
1791
1792
1793
        }
        break; 
      }
      default:
        // error (invalid escaped character) -> leave the for cycle
        i = end;
1794
        error = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
        break;
      }
      // skip an extra character (the \)
      ++i;
    } else {
      str[len++] = p_value[i];
    } 
    
    if (check_quotes && i == p_value_len - 1) {
      // Special case: the last 2 characters are double escaped quotes ('\\' and '\"')
1805
      error = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
    }
  }
  
  if (!error) {
    clean_up();
    init_struct(len);
    memcpy(val_ptr->chars_ptr, str, len);
    val_ptr->chars_ptr[len] = 0;
  }
  Free(str);
  return !error;
}

1819
int CHARSTRING::JSON_encode(const TTCN_Typedescriptor_t& p_td, JSON_Tokenizer& p_tok, boolean) const
Elemer Lelik's avatar
Elemer Lelik committed
1820
1821
1822
1823
1824
1825
1826
{
  if (!is_bound()) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_UNBOUND,
      "Encoding an unbound charstring value.");
    return -1;
  }
  
1827
  char* tmp_str = to_JSON_string(p_td.json->escaping);  
Elemer Lelik's avatar
Elemer Lelik committed
1828
1829
1830
1831
1832
  int enc_len = p_tok.put_next_token(JSON_TOKEN_STRING, tmp_str);
  Free(tmp_str);
  return enc_len;
}

1833
int CHARSTRING::JSON_decode(const TTCN_Typedescriptor_t& p_td, JSON_Tokenizer& p_tok, boolean p_silent, boolean, int)
Elemer Lelik's avatar
Elemer Lelik committed
1834
1835
1836
1837
{
  json_token_t token = JSON_TOKEN_NONE;
  char* value = 0;
  size_t value_len = 0;
1838
  size_t dec_len = 0;
Elemer Lelik's avatar
Elemer Lelik committed
1839
1840
1841
  boolean use_default = p_td.json->default_value && 0 == p_tok.get_buffer_length();
  if (use_default) {
    // No JSON data in the buffer -> use default value
1842
    value = const_cast<char*>(p_td.json->default_value);
Elemer Lelik's avatar
Elemer Lelik committed
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
    value_len = strlen(value);
  } else {
    dec_len = p_tok.get_next_token(&token, &value, &value_len);
  }
  if (JSON_TOKEN_ERROR == token) {
    JSON_ERROR(TTCN_EncDec::ET_INVAL_MSG, JSON_DEC_BAD_TOKEN_ERROR, "");
    return JSON_ERROR_FATAL;
  }
  else if (JSON_TOKEN_STRING == token || use_default) {
    if (!from_JSON_string(value, value_len, !use_default)) {
      JSON_ERROR(TTCN_EncDec::ET_INVAL_MSG, JSON_DEC_FORMAT_ERROR, "string", "charstring");
      clean_up();
      return JSON_ERROR_FATAL;
    }
  } else {
    return JSON_ERROR_INVALID_TOKEN;
  }
1860
  return (int)dec_len;
Elemer Lelik's avatar
Elemer Lelik committed
1861
1862
}

1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
int CHARSTRING::OER_encode(const TTCN_Typedescriptor_t& p_td, TTCN_Buffer& p_buf) const {
  if (!is_bound()) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_UNBOUND,
      "Encoding an unbound charstring value.");
    return -1;
  }
  
  if (p_td.oer->length == -1) {
    encode_oer_length(lengthof(), p_buf, FALSE);
  }
  p_buf.put_cs(*this);
  return 0;
}
  
int CHARSTRING::OER_decode(const TTCN_Typedescriptor_t& p_td, TTCN_Buffer& p_buf, OER_struct&) {
  size_t bytes;
  if (p_td.oer->length == -1) {
    bytes = decode_oer_length(p_buf, FALSE);
  } else {
    bytes = p_td.oer->length;
  }
  const unsigned char* uc = p_buf.get_read_data();
  init_struct(bytes);
  for (size_t i = 0; i < bytes; i++) {
    val_ptr->chars_ptr[i] = uc[i];
  }
  p_buf.increase_pos(bytes);
  return 0;
}
Elemer Lelik's avatar
Elemer Lelik committed
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966