fan-1.0 /src/sys/dotnet/fanx/serial/ObjEncoder.cs

Language C# Lines 381
MD5 Hash f1ac78d860c104f05bf820f286966e73 Estimated Cost $6,328 (why?)
Repository https://bitbucket.org/bedlaczech/fan-1.0 View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//
// Copyright (c) 2007, Brian Frank and Andy Frank
// Licensed under the Academic Free License version 3.0
//
// History:
//   11 Sep 07  Andy Frank  Creation
//

using System.Collections;
using Fan.Sys;
using Fanx.Util;

namespace Fanx.Serial
{
  /// <summary>
  /// ObjEncoder serializes an object to an output stream.
  /// </summary>
  public class ObjEncoder
  {

  //////////////////////////////////////////////////////////////////////////
  // Static
  //////////////////////////////////////////////////////////////////////////

    public static string encode(object obj)
    {
      StrBufOutStream @out = new StrBufOutStream();
      new ObjEncoder(@out, null).writeObj(obj);
      return @out.@string();
    }

  //////////////////////////////////////////////////////////////////////////
  // Constructor
  //////////////////////////////////////////////////////////////////////////

    public ObjEncoder(OutStream @out, Map options)
    {
      this.@out = @out;
      if (options != null) initOptions(options);
    }

  //////////////////////////////////////////////////////////////////////////
  // Write
  //////////////////////////////////////////////////////////////////////////

    public void writeObj(object obj)
    {
      if (obj == null)
      {
        w("null");
        return;
      }

      if (obj.GetType().FullName[0] == 'S')
      {
        if (obj is bool && (bool)obj)  { w("true");  return; }
        if (obj is bool && !(bool)obj) { w("false"); return; }
        if (obj is double) { FanFloat.encode((double)obj, this); return; }
        if (obj is long)   { FanInt.encode((long)obj, this); return; }
        if (obj is string) { wStrLiteral(obj.ToString(), '"'); return; }
      }

      if (obj.GetType().FullName[0] == 'F')
      {
        if (obj is Boolean && (obj as Boolean).booleanValue())  { w("true"); return; }
        if (obj is Boolean && !(obj as Boolean).booleanValue()) { w("false"); return; }
        if (obj is Double) { FanFloat.encode((obj as Double).doubleValue(), this); return; }
        if (obj is Long)   { FanInt.encode((obj as Long).longValue(), this); return; }
        if (obj is BigDecimal) { FanDecimal.encode((BigDecimal)obj, this); return; }
      }

      if (obj is Literal)
      {
        ((Literal)obj).encode(this);
        return;
      }

      Type type = FanObj.@typeof(obj);
      Serializable ser = (Serializable)type.facet(Sys.SerializableType, false);
      if (ser != null)
      {
        if (ser.m_simple)
          writeSimple(type, obj);
        else
          writeComplex(type, obj, ser);
      }
      else
      {
        if (skipErrors)
          w("null /* Not serializable: ").w(type.qname()).w(" */");
        else
          throw IOErr.make("Not serializable: " + type).val;
      }
    }

  //////////////////////////////////////////////////////////////////////////
  // Simple
  //////////////////////////////////////////////////////////////////////////

    private void writeSimple(Type type, object obj)
    {
      wType(type).w('(').wStrLiteral(FanObj.toStr(obj), '"').w(')');
    }

  //////////////////////////////////////////////////////////////////////////
  // Complex
  //////////////////////////////////////////////////////////////////////////

    private void writeComplex(Type type, object obj, Serializable ser)
    {
      wType(type);

      bool first = true;
      object defObj = null;
      if (skipDefaults) defObj = FanObj.@typeof(obj).make();

      List fields = type.fields();
      for (int i=0; i<fields.sz(); ++i)
      {
        Field f = (Field)fields.get(i);

        // skip static, transient, and synthetic (once) fields
        if (f.isStatic() || f.isSynthetic() || f.hasFacet(Sys.TransientType))
          continue;

        // get the value
        object val = f.get(obj);

        // if skipping defaults
        if (defObj != null)
        {
          object defVal = f.get(defObj);
          if (OpUtil.compareEQ(val, defVal)) continue;
        }

        // if first then open braces
        if (first) { w('\n').wIndent().w('{').w('\n'); level++; first = false; }

        // field name =
        wIndent().w(f.name()).w('=');

        // field value
        curFieldType = f.type().toNonNullable();
        writeObj(val);
        curFieldType = null;

        w('\n');
      }

      // if collection
      if (ser.m_collection)
        first = writeCollectionItems(type, obj, first);

      // if we output fields, then close braces
      if (!first) { level--; wIndent().w('}'); }
    }

  //////////////////////////////////////////////////////////////////////////
  // Collection (@collection)
  //////////////////////////////////////////////////////////////////////////

    private bool writeCollectionItems(Type type, object obj, bool first)
    {
      // lookup each method
      Method m = type.method("each", false);
      if (m == null) throw IOErr.make("Missing " + type.qname() + ".each").val;

      // call each(it)
      EachIterator it = new EachIterator(this, first);
      m.invoke(obj, new object[] { it });
      return it.first;
    }

    static FuncType eachIteratorType = new FuncType(new Type[] { Sys.ObjType }, Sys.VoidType);

    internal class EachIterator : Func.Indirect1
    {
      internal EachIterator(ObjEncoder encoder, bool first)
        : base(eachIteratorType)
      {
        this.encoder = encoder;
        this.first = first;
      }
      public override object call(object obj)
      {
        if (first) { encoder.w('\n').wIndent().w('{').w('\n'); encoder.level++; first = false; }
        encoder.wIndent();
        encoder.writeObj(obj);
        encoder.w(',').w('\n');
        return null;
      }
      private ObjEncoder encoder;
      internal bool first;
    }

  //////////////////////////////////////////////////////////////////////////
  // List
  //////////////////////////////////////////////////////////////////////////

    public void writeList(List list)
    {
      // get of type
      Type of = list.of();

      // decide if we're going output as single or multi-line format
      bool nl = isMultiLine(of);

      // figure out if we can use an inferred type
      bool inferred = false;
      if (curFieldType != null && curFieldType.fits(Sys.ListType))
      {
        inferred = true;
      }

      // clear field type, so it doesn't get used for inference again
      curFieldType = null;

      // if we don't have an inferred type, then prefix of type
      if (!inferred) wType(of);

      // handle empty list
      int size = list.sz();
      if (size == 0) { w("[,]"); return; }

      // items
      if (nl) w('\n').wIndent();
      w('[');
      level++;
      for (int i=0; i<size; ++i)
      {
        if (i > 0) w(',');
         if (nl) w('\n').wIndent();
        writeObj(list.get(i));
      }
      level--;
      if (nl) w('\n').wIndent();
      w(']');
    }

  //////////////////////////////////////////////////////////////////////////
  // Map
  //////////////////////////////////////////////////////////////////////////

    public void writeMap(Map map)
    {
      // get k,v type
      MapType t = (MapType)map.@typeof();

      // decide if we're going output as single or multi-line format
      bool nl = isMultiLine(t.m_k) || isMultiLine(t.m_v);

      // figure out if we can use an inferred type
      bool inferred = false;
      if (curFieldType != null && curFieldType.fits(Sys.MapType))
      {
        inferred = true;
      }

      // clear field type, so it doesn't get used for inference again
      curFieldType = null;

      // if we don't have an inferred type, then prefix of type
      if (!inferred) wType(t);

      // handle empty map
      if (map.isEmpty()) { w("[:]"); return; }

      // items
      level++;
      w('[');
      bool first = true;
      IDictionaryEnumerator en = map.pairsIterator();
      while (en.MoveNext())
      {
        if (first) first = false; else w(',');
        if (nl) w('\n').wIndent();
        object key = en.Key;
        object val = en.Value;
        writeObj(key); w(':'); writeObj(val);
      }
      w(']');
      level--;
    }

    private bool isMultiLine(Type t)
    {
      return t.pod() != Sys.m_sysPod;
    }

  //////////////////////////////////////////////////////////////////////////
  // Output
  //////////////////////////////////////////////////////////////////////////

    public ObjEncoder wType(Type t)
    {
      return w(t.signature());
    }

    public ObjEncoder wStrLiteral(string s, char quote)
    {
      int len = s.Length;
      w(quote);
      // NOTE: these escape sequences are duplicated in FanStr.toCode()
      for (int i=0; i<len; ++i)
      {
        char c = s[i];
        switch (c)
        {
          case '\n': w('\\').w('n'); break;
          case '\r': w('\\').w('r'); break;
          case '\f': w('\\').w('f'); break;
          case '\t': w('\\').w('t'); break;
          case '\\': w('\\').w('\\'); break;
          case '"':  if (quote == '"') w('\\').w('"'); else w(c); break;
          case '`':  if (quote == '`') w('\\').w('`'); else w(c); break;
          case '$':  w('\\').w('$'); break;
          default:   w(c); break;
        }
      }
      return w(quote);
    }

    public ObjEncoder wIndent()
    {
      int num = level*indent;
      for (int i=0; i<num; ++i) w(' ');
      return this;
    }

    public ObjEncoder w(string s)
    {
      int len = s.Length;
      for (int i=0; i<len; ++i)
        @out.writeChar(s[i]);
      return this;
    }

    public ObjEncoder w(char ch)
    {
      @out.writeChar(ch);
      return this;
    }

  //////////////////////////////////////////////////////////////////////////
  // Options
  //////////////////////////////////////////////////////////////////////////

    private void initOptions(Map options)
    {
      indent = option(options, "indent", indent);
      skipDefaults = option(options, "skipDefaults", skipDefaults);
      skipErrors = option(options, "skipErrors", skipErrors);
    }

    private static int option(Map options, string name, int def)
    {
      Long val = (Long)options.get(name);
      if (val == null) return def;
      return val.intValue();
    }

    private static bool option(Map options, string name, bool def)
    {
      Boolean val = (Boolean)options.get(name);
      if (val == null) return def;
      return val.booleanValue();
    }

  //////////////////////////////////////////////////////////////////////////
  // Fields
  //////////////////////////////////////////////////////////////////////////

    OutStream @out;
    int level  = 0;
    int indent = 0;
    bool skipDefaults = false;
    bool skipErrors = false;
    Type curFieldType;

  }
}
Back to Top