1 #include <stddef.h>
2 #if HAVE_MALLOC_H
3 #include <malloc.h>
4 #endif
5 #if HAVE_UNISTD_H
6 #include <unistd.h>
7 #endif
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 #include <freehdl/fire-types.h>
13
fire_xmalloc(size_t s)14 static void *fire_xmalloc (size_t s)
15 {
16 static char msg[] = "virtual memory exhausted\n";
17 void *mem = malloc (s);
18 if (mem == NULL)
19 {
20 write (2, msg, sizeof(msg)-1);
21 exit (1);
22 }
23 return mem;
24 }
25
IR_String(const IR_Character * chars,int l)26 IR_String::IR_String (const IR_Character *chars, int l)
27 {
28 rep = (strrep *) fire_xmalloc (sizeof(strrep)+sizeof(IR_Character)*l);
29 rep->len = l;
30 rep->ref_count = 1;
31 memcpy (rep->chars, chars, sizeof(IR_Character)*l);
32 rep->chars[l] = '\0';
33 }
34
IR_String(const char * chars)35 IR_String::IR_String (const char *chars)
36 {
37 int l = strlen (chars);
38 rep = (strrep *) fire_xmalloc (sizeof(strrep)+sizeof(IR_Character)*l);
39 rep->len = l;
40 rep->ref_count = 1;
41 memcpy (rep->chars, chars, sizeof(IR_Character)*l);
42 rep->chars[l] = '\0';
43 }
44
IR_String(const IR_String & str)45 IR_String::IR_String (const IR_String &str)
46 {
47 rep = str.rep;
48 rep->ref_count++;
49 }
50
~IR_String()51 IR_String::~IR_String ()
52 {
53 if(--rep->ref_count == 0)
54 free (rep);
55 }
56
57 IR_String &
operator =(const IR_String & str)58 IR_String::operator= (const IR_String &str)
59 {
60 str.rep->ref_count++;
61 if (--rep->ref_count == 0)
62 free (rep);
63 rep = str.rep;
64 return *this;
65 }
66
67 char *
to_chars()68 IR_String::to_chars ()
69 {
70 for (int i = 0; i < rep->len; i++)
71 if (rep->chars[i] == '\0')
72 abort ();
73 return (char *)rep->chars;
74 }
75
76 std::ostream&
operator <<(std::ostream & o,IR_String & str)77 operator<< (std::ostream& o, IR_String& str)
78 {
79 return o << str.to_chars();
80 }
81
82 void
fire_print_bool(void * mem)83 fire_print_bool (void *mem)
84 {
85 printf ("%s", (*(bool *)mem)? "true":"false");
86 }
87
88 void
fire_print_int(void * mem)89 fire_print_int (void *mem)
90 {
91 printf ("%d", *(int *)mem);
92 }
93
94 void
fire_print_string(void * mem)95 fire_print_string (void *mem)
96 {
97 printf ("\"%s\"", *(char **)mem);
98 }
99
100 void
fire_print_IR_String(void * mem)101 fire_print_IR_String (void *mem)
102 {
103 printf ("\"%s\"", (*(IR_String *)mem).to_chars());
104 }
105