aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/golang/protobuf/proto/encode.go
blob: 8b84d1b22d4c0933820cb4872e29c918e5429be2 (plain) (blame)
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
382
383
384
385
386
387
388
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

    adium_path = empathy_adium_data_get_path (self->priv->adium_data);

  DEBUG ("Emit theme-changed with: adium_path='%s' "
      "adium_variant='%s'", adium_path, self->priv->adium_variant);

  g_signal_emit (self, signals[THEME_CHANGED], 0, NULL);
  self->priv->emit_changed_idle = 0;

  return FALSE;
}

static void
theme_manager_emit_changed (EmpathyThemeManager *self)
{
  /* We emit the signal in idle callback to be sure we emit it only once
   * in the case both the name and adium_path changed */
  if (self->priv->emit_changed_idle == 0 && !self->priv->in_constructor)
    {
      self->priv->emit_changed_idle = g_idle_add (
        theme_manager_emit_changed_idle_cb, self);
    }
}

static void
theme_manager_view_weak_notify_cb (gpointer data,
    GObject *where_the_object_was)
{
  GList **list = data;

  *list = g_list_remove (*list, where_the_object_was);
}

static void
clear_list_of_views (GList **views)
{
  while (*views)
    {
      g_object_weak_unref ((*views)->data,
               theme_manager_view_weak_notify_cb,
               views);

      *views = g_list_delete_link (*views, *views);
    }
}

static EmpathyThemeAdium *
theme_manager_create_adium_view (EmpathyThemeManager *self)
{
  EmpathyThemeAdium *theme;

  theme = empathy_theme_adium_new (self->priv->adium_data, self->priv->adium_variant);

  self->priv->adium_views = g_list_prepend (self->priv->adium_views, theme);

  g_object_weak_ref (G_OBJECT (theme),
         theme_manager_view_weak_notify_cb,
         &self->priv->adium_views);

  return theme;
}

static void
theme_manager_notify_theme_cb (GSettings *gsettings_chat,
    const gchar *key,
    gpointer user_data)
{
  EmpathyThemeManager *self = EMPATHY_THEME_MANAGER (user_data);
  gchar *theme, *path;

  theme = g_settings_get_string (gsettings_chat, key);

  path = empathy_theme_manager_find_theme (theme);
  if (path == NULL)
    {
      DEBUG ("Can't find theme: %s; fallback to 'Classic'",
          theme);

      path = empathy_theme_manager_find_theme ("Classic");
      if (path == NULL)
        g_critical ("Can't find 'Classic theme");
    }

  /* Load new theme data, we can stop tracking existing views since we
   * won't be able to change them live anymore */
  clear_list_of_views (&self->priv->adium_views);
  tp_clear_pointer (&self->priv->adium_data, empathy_adium_data_unref);
  self->priv->adium_data = empathy_adium_data_new (path);

  theme_manager_emit_changed (self);

  g_free (path);
  g_free (theme);
}

static void
theme_manager_notify_adium_variant_cb (GSettings *gsettings_chat,
    const gchar *key,
    gpointer user_data)
{
  EmpathyThemeManager *self = EMPATHY_THEME_MANAGER (user_data);
  gchar *new_variant;
  GList *l;

  new_variant = g_settings_get_string (gsettings_chat, key);
  if (!tp_strdiff (self->priv->adium_variant, new_variant))
    {
      g_free (new_variant);
      return;
    }

  g_free (self->priv->adium_variant);
  self->priv->adium_variant = new_variant;

  for (l = self->priv->adium_views; l; l = l->next)
    {
      empathy_theme_adium_set_variant (EMPATHY_THEME_ADIUM (l->data),
        self->priv->adium_variant);
    }
}

EmpathyThemeAdium *
empathy_theme_manager_create_view (EmpathyThemeManager *self)
{
  g_return_val_if_fail (EMPATHY_IS_THEME_MANAGER (self), NULL);

  if (self->priv->adium_data != NULL)
    return theme_manager_create_adium_view (self);

  g_return_val_if_reached (NULL);
}

static void
theme_manager_finalize (GObject *object)
{
  EmpathyThemeManager *self = (EmpathyThemeManager *) object;

  g_object_unref (self->priv->gsettings_chat);

  if (self->priv->emit_changed_idle != 0)
    g_source_remove (self->priv->emit_changed_idle);

  clear_list_of_views (&self->priv->adium_views);
  g_free (self->priv->adium_variant);
  tp_clear_pointer (&self->priv->adium_data, empathy_adium_data_unref);

  G_OBJECT_CLASS (empathy_theme_manager_parent_class)->finalize (object);
}

static void
empathy_theme_manager_class_init (EmpathyThemeManagerClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  signals[THEME_CHANGED] = g_signal_new ("theme-changed",
      G_OBJECT_CLASS_TYPE (object_class),
      G_SIGNAL_RUN_LAST,
      0,
      NULL, NULL,
      g_cclosure_marshal_generic,
      G_TYPE_NONE,
      0);

  g_type_class_add_private (object_class, sizeof (EmpathyThemeManagerPriv));

  object_class->finalize = theme_manager_finalize;
}

static void
empathy_theme_manager_init (EmpathyThemeManager *self)
{
  self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
    EMPATHY_TYPE_THEME_MANAGER, EmpathyThemeManagerPriv);

  self->priv->in_constructor = TRUE;

  self->priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);

  /* Take the adium path/variant and track changes */
  g_signal_connect (self->priv->gsettings_chat,
      "changed::" EMPATHY_PREFS_CHAT_THEME,
      G_CALLBACK (theme_manager_notify_theme_cb), self);

  theme_manager_notify_theme_cb (self->priv->gsettings_chat,
      EMPATHY_PREFS_CHAT_THEME, self);

  g_signal_connect (self->priv->gsettings_chat,
      "changed::" EMPATHY_PREFS_CHAT_THEME_VARIANT,
      G_CALLBACK (theme_manager_notify_adium_variant_cb), self);

  theme_manager_notify_adium_variant_cb (self->priv->gsettings_chat,
      EMPATHY_PREFS_CHAT_THEME_VARIANT, self);

  self->priv->in_constructor = FALSE;
}

EmpathyThemeManager *
empathy_theme_manager_dup_singleton (void)
{
  static EmpathyThemeManager *manager = NULL;

  if (manager == NULL)
    {
      manager = g_object_new (EMPATHY_TYPE_THEME_MANAGER, NULL);
      g_object_add_weak_pointer (G_OBJECT (manager), (gpointer *) &manager);

      return manager;
    }

  return g_object_ref (manager);
}

static void
find_themes (GHashTable *hash,
    const gchar *dirpath)
{
  GDir *dir;
  GError *error = NULL;
  const gchar *name = NULL;
  GHashTable *info = NULL;

  dir = g_dir_open (dirpath, 0, &error);
  if (dir != NULL)
    {
      name = g_dir_read_name (dir);

      while (name != NULL)
        {
          gchar *path;

          path = g_build_path (G_DIR_SEPARATOR_S, dirpath, name, NULL);
          if (empathy_adium_path_is_valid (path))
            {
              info = empathy_adium_info_new (path);

              if (info != NULL)
                {
                  g_hash_table_insert (hash,
                      empathy_theme_manager_dup_theme_name_from_path (path),
                      info);
                }
            }

          g_free// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors.  All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provid
      g_error_free (error);
    }
}

GList *
empathy_theme_manager_get_adium_themes (void)
{
  /* Theme name -> GHashTable info */
  GHashTable *hash;
  GList *result;
  gchar *path = NULL;
  const gchar *const *paths = NULL;
  gint i = 0;
  const gchar *dir;

  hash = g_hash_table_new_full (g_str_hash, g_str_equal,
      g_free, (GDestroyNotify) g_hash_table_unref);

  /* Start from the more general locations (the system) to the more specific
   * ones ($HOME, EMPATHY_SRCDIR) so the more specific themes will override
   * the more general ones.*/

  /* System */
  paths = g_get_system_data_dirs ();
  for (i = 0; paths[i] != NULL; i++)
    {
      path = g_build_path (G_DIR_SEPARATOR_S, paths[i],
        "adium/message-styles", NULL);

      find_themes (hash, path);
      g_free (path);
    }

  /* Home */
  path = g_build_path (G_DIR_SEPARATOR_S, g_get_user_data_dir (),
      "adium/message-styles", NULL);

  find_themes (hash, path);
  g_free (path);

  /* EMPATHY_SRCDIR */
  dir = g_getenv ("EMPATHY_SRCDIR");
  if (dir != NULL)
    {
      path = g_build_path (G_DIR_SEPARATOR_S, dir, "data/themes/", NULL);

      find_themes (hash, path);
      g_free (path);
    }

  /* Pass ownership of the info hash table to the list */
  result = g_list_copy_deep (g_hash_table_get_values (hash),
      (GCopyFunc) g_hash_table_ref, NULL);

  g_hash_table_unref (hash);

  return result;
}

gchar *
empathy_theme_manager_find_theme (const gchar *name)
{
  gchar *path;
  const gchar * const *paths;
  gint i;

  /* look in EMPATHY_SRCDIR */
  path = g_strjoin (NULL,
      g_getenv ("EMPATHY_SRCDIR"),
      "/data/themes/",
      name,
      ".AdiumMessageStyle",
      NULL);

  DEBUG ("Trying '%s'", path);

  if (empathy_adium_path_is_valid (path))
    return path;

  g_free (path);

  /* look in user dir */
  path = g_strjoin (NULL,
      g_get_user_data_dir (),
      "/adium/message-styles/",
      name,
      ".AdiumMessageStyle",
      NULL);

  DEBUG ("Trying '%s'", path);

  if (empathy_adium_path_is_valid (path))
    return path;

  g_free (path);

  /* look in system dirs */
  paths = g_get_system_data_dirs ();

  for (i = 0; paths[i] != NULL; i++)
    {
      path = g_strjoin (NULL,
          paths[i],
          "/adium/message-styles/",
          name,
          ".AdiumMessageStyle",
          NULL);

      DEBUG ("Trying '%s'", path);

      if (empathy_adium_path_is_valid (path))
        return path;

      g_free (path);
    }

  return NULL;
}

gchar *
empathy_theme_manager_dup_theme_name_from_path (const gchar *path)
{
  gchar *fullname, *result;
  gchar **tmp;

  if (path == NULL)
    return NULL;

  fullname = g_path_get_basename (path);
  if (!g_str_has_suffix (fullname, ".AdiumMessageStyle"))
    return NULL;

  tmp = g_strsplit (fullname, ".AdiumMessageStyle", 0);
  result = g_strdup (tmp[0]);

  g_strfreev (tmp);
  return result;
}
      uint8(x>>40),
        uint8(x>>48),
        uint8(x>>56))
    return nil
}

func sizeFixed64(x uint64) int {
    return 8
}

// EncodeFixed32 writes a 32-bit integer to the Buffer.
// This is the format for the
// fixed32, sfixed32, and float protocol buffer types.
func (p *Buffer) EncodeFixed32(x uint64) error {
    p.buf = append(p.buf,
        uint8(x),
        uint8(x>>8),
        uint8(x>>16),
        uint8(x>>24))
    return nil
}

func sizeFixed32(x uint64) int {
    return 4
}

// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
// to the Buffer.
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) EncodeZigzag64(x uint64) error {
    // use signed number to get arithmetic right shift.
    return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63)))
}

func sizeZigzag64(x uint64) int {
    return sizeVarint((x << 1) ^ uint64((int64(x) >> 63)))
}

// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
// to the Buffer.
// This is the format used for the sint32 protocol buffer type.
func (p *Buffer) EncodeZigzag32(x uint64) error {
    // use signed number to get arithmetic right shift.
    return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
}

func sizeZigzag32(x uint64) int {
    return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
}

// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
// This is the format used for the bytes protocol buffer
// type and for embedded messages.
func (p *Buffer) EncodeRawBytes(b []byte) error {
    p.EncodeVarint(uint64(len(b)))
    p.buf = append(p.buf, b...)
    return nil
}

func sizeRawBytes(b []byte) int {
    return sizeVarint(uint64(len(b))) +
        len(b)
}

// EncodeStringBytes writes an encoded string to the Buffer.
// This is the format used for the proto2 string type.
func (p *Buffer) EncodeStringBytes(s string) error {
    p.EncodeVarint(uint64(len(s)))
    p.buf = append(p.buf, s...)
    return nil
}

func sizeStringBytes(s string) int {
    return sizeVarint(uint64(len(s))) +
        len(s)
}

// Marshaler is the interface representing objects that can marshal themselves.
type Marshaler interface {
    Marshal() ([]byte, error)
}

// Marshal takes the protocol buffer
// and encodes it into the wire format, returning the data.
func Marshal(pb Message) ([]byte, error) {
    // Can the object marshal itself?
    if m, ok := pb.(Marshaler); ok {
        return m.Marshal()
    }
    p := NewBuffer(nil)
    err := p.Marshal(pb)
    if p.buf == nil && err == nil {
        // Return a non-nil slice on success.
        return []byte{}, nil
    }
    return p.buf, err
}

// EncodeMessage writes the protocol buffer to the Buffer,
// prefixed by a varint-encoded length.
func (p *Buffer) EncodeMessage(pb Message) error {
    t, base, err := getbase(pb)
    if structPointer_IsNil(base) {
        return ErrNil
    }
    if err == nil {
        var state errorState
        err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
    }
    return err
}

// Marshal takes the protocol buffer
// and encodes it into the wire format, writing the result to the
// Buffer.
func (p *Buffer) Marshal(pb Message) error {
    // Can the object marshal itself?
    if m, ok := pb.(Marshaler); ok {
        data, err := m.Marshal()
        p.buf = append(p.buf, data...)
        return err
    }

    t, base, err := getbase(pb)
    if structPointer_IsNil(base) {
        return ErrNil
    }
    if err == nil {
        err = p.enc_struct(GetProperties(t.Elem()), base)
    }

    if collectStats {
        (stats).Encode++ // Parens are to work around a goimports bug.
    }

    if len(p.buf) > maxMarshalSize {
        return ErrTooLarge
    }
    return err
}

// Size returns the encoded size of a protocol buffer.
func Size(pb Message) (n int) {
    // Can the object marshal itself?  If so, Size is slow.
    // TODO: add Size to Marshaler, or add a Sizer interface.
    if m, ok := pb.(Marshaler); ok {
        b, _ := m.Marshal()
        return len(b)
    }

    t, base, err := getbase(pb)
    if structPointer_IsNil(base) {
        return 0
    }
    if err == nil {
        n = size_struct(GetProperties(t.Elem()), base)
    }

    if collectStats {
        (stats).Size++ // Parens are to work around a goimports bug.
    }

    return
}

// Individual type encoders.

// Encode a bool.
func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
    v := *structPointer_Bool(base, p.field)
    if v == nil {
        return ErrNil
    }
    x := 0
    if *v {
        x = 1
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
    v := *structPointer_BoolVal(base, p.field)
    if !v {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, 1)
    return nil
}

func size_bool(p *Properties, base structPointer) int {
    v := *structPointer_Bool(base, p.field)
    if v == nil {
        return 0
    }
    return len(p.tagcode) + 1 // each bool takes exactly one byte
}

func size_proto3_bool(p *Properties, base structPointer) int {
    v := *structPointer_BoolVal(base, p.field)
    if !v && !p.oneof {
        return 0
    }
    return len(p.tagcode) + 1 // each bool takes exactly one byte
}

// Encode an int32.
func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return ErrNil
    }
    x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
    v := structPointer_Word32Val(base, p.field)
    x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
    if x == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func size_int32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return 0
    }
    x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

func size_proto3_int32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32Val(base, p.field)
    x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
    if x == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

// Encode a uint32.
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return ErrNil
    }
    x := word32_Get(v)
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
    v := structPointer_Word32Val(base, p.field)
    x := word32Val_Get(v)
    if x == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func size_uint32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return 0
    }
    x := word32_Get(v)
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

func size_proto3_uint32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32Val(base, p.field)
    x := word32Val_Get(v)
    if x == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

// Encode an int64.
func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
    v := structPointer_Word64(base, p.field)
    if word64_IsNil(v) {
        return ErrNil
    }
    x := word64_Get(v)
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, x)
    return nil
}

func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
    v := structPointer_Word64Val(base, p.field)
    x := word64Val_Get(v)
    if x == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, x)
    return nil
}

func size_int64(p *Properties, base structPointer) (n int) {
    v := structPointer_Word64(base, p.field)
    if word64_IsNil(v) {
        return 0
    }
    x := word64_Get(v)
    n += len(p.tagcode)
    n += p.valSize(x)
    return
}

func size_proto3_int64(p *Properties, base structPointer) (n int) {
    v := structPointer_Word64Val(base, p.field)
    x := word64Val_Get(v)
    if x == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += p.valSize(x)
    return
}

// Encode a string.
func (o *Buffer) enc_string(p *Properties, base structPointer) error {
    v := *structPointer_String(base, p.field)
    if v == nil {
        return ErrNil
    }
    x := *v
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeStringBytes(x)
    return nil
}

func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
    v := *structPointer_StringVal(base, p.field)
    if v == "" {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeStringBytes(v)
    return nil
}

func size_string(p *Properties, base structPointer) (n int) {
    v := *structPointer_String(base, p.field)
    if v == nil {
        return 0
    }
    x := *v
    n += len(p.tagcode)
    n += sizeStringBytes(x)
    return
}

func size_proto3_string(p *Properties, base structPointer) (n int) {
    v := *structPointer_StringVal(base, p.field)
    if v == "" && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += sizeStringBytes(v)
    return
}

// All protocol buffer fields are nillable, but be careful.
func isNil(v reflect.Value) bool {
    switch v.Kind() {
    case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
        return v.IsNil()
    }
    return false
}

// Encode a message struct.
func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
    var state errorState
    structp := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(structp) {
        return ErrNil
    }

    // Can the object marshal itself?
    if p.isMarshaler {
        m := structPointer_Interface(structp, p.stype).(Marshaler)
        data, err := m.Marshal()
        if err != nil && !state.shouldContinue(err, nil) {
            return err
        }
        o.buf = append(o.buf, p.tagcode...)
        o.EncodeRawBytes(data)
        return state.err
    }

    o.buf = append(o.buf, p.tagcode...)
    return o.enc_len_struct(p.sprop, structp, &state)
}

func size_struct_message(p *Properties, base structPointer) int {
    structp := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(structp) {
        return 0
    }

    // Can the object marshal itself?
    if p.isMarshaler {
        m := structPointer_Interface(structp, p.stype).(Marshaler)
        data, _ := m.Marshal()
        n0 := len(p.tagcode)
        n1 := sizeRawBytes(data)
        return n0 + n1
    }

    n0 := len(p.tagcode)
    n1 := size_struct(p.sprop, structp)
    n2 := sizeVarint(uint64(n1)) // size of encoded length
    return n0 + n1 + n2
}

// Encode a group struct.
func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
    var state errorState
    b := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(b) {
        return ErrNil
    }

    o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
    err := o.enc_struct(p.sprop, b)
    if err != nil && !state.shouldContinue(err, nil) {
        return err
    }
    o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
    return state.err
}

func size_struct_group(p *Properties, base structPointer) (n int) {
    b := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(b) {
        return 0
    }

    n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
    n += size_struct(p.sprop, b)
    n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
    return
}

// Encode a slice of bools ([]bool).
func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return ErrNil
    }
    for _, x := range s {
        o.buf = append(o.buf, p.tagcode...)
        v := uint64(0)
        if x {
            v = 1
        }
        p.valEnc(o, v)
    }
    return nil
}

func size_slice_bool(p *Properties, base structPointer) int {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return 0
    }
    return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
}

// Encode a slice of bools ([]bool) in packed format.
func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
    for _, x := range s {
        v := uint64(0)
        if x {
            v = 1
        }
        p.valEnc(o, v)
    }
    return nil
}

func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return 0
    }
    n += len(p.tagcode)
    n += sizeVarint(uint64(l))
    n += l // each bool takes exactly one byte
    return
}

// Encode a slice of bytes ([]byte).
func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
    s := *structPointer_Bytes(base, p.field)
    if s == nil {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeRawBytes(s)
    return nil
}

func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
    s := *structPointer_Bytes(base, p.field)
    if len(s) == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeRawBytes(s)
    return nil
}

func size_slice_byte(p *Properties, base structPointer) (n int) {
    s := *structPointer_Bytes(base, p.field)
    if s == nil && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += sizeRawBytes(s)
    return
}

func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
    s := *structPointer_Bytes(base, p.field)
    if len(s) == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += sizeRawBytes(s)
    return
}

// Encode a slice of int32s ([]int32).
func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        p.valEnc(o, uint64(x))
    }
    return nil
}

func size_slice_int32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    for i := 0; i < l; i++ {
        n += len(p.tagcode)
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        n += p.valSize(uint64(x))
    }
    return
}

// Encode a slice of int32s ([]int32) in packed format.
func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    // TODO: Reuse a Buffer.
    buf := NewBuffer(nil)
    for i := 0; i < l; i++ {
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        p.valEnc(buf, uint64(x))
    }

    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(len(buf.buf)))
    o.buf = append(o.buf, buf.buf...)
    return nil
}

func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    var bufSize int
    for i := 0; i < l; i++ {
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        bufSize += p.valSize(uint64(x))
    }

    n += len(p.tagcode)
    n += sizeVarint(uint64(bufSize))
    n += bufSize
    return
}

// Encode a slice of uint32s ([]uint32).
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        x := s.Index(i)
        p.valEnc(o, uint64(x))
    }
    return nil
}

func size_slice_uint32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    for i := 0; i < l; i++ {
        n += len(p.tagcode)
        x := s.Index(i)
        n += p.valSize(uint64(x))
    }
    return
}

// Encode a slice of uint32s ([]uint32) in packed format.
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    // TODO: Reuse a Buffer.
    buf := NewBuffer(nil)
    for i := 0; i < l; i++ {
        p.valEnc(buf, uint64(s.Index(i)))
    }

    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(len(buf.buf)))
    o.buf = append(o.buf, buf.buf...)
    return nil
}

func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    var bufSize int
    for i := 0; i < l; i++ {
        bufSize += p.valSize(uint64(s.Index(i)))
    }

    n += len(p.tagcode)
    n += sizeVarint(uint64(bufSize))
    n += bufSize
    return
}

// Encode a slice of int64s ([]int64).
func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        p.valEnc(o, s.Index(i))
    }
    return nil
}

func size_slice_int64(p *Properties, base structPointer) (n int) {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    for i := 0; i < l; i++ {
        n += len(p.tagcode)
        n += p.valSize(s.Index(i))
    }
    return
}

// Encode a slice of int64s ([]int64) in packed format.
func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    // TODO: Reuse a Buffer.
    buf := NewBuffer(nil)
    for i := 0; i < l; i++ {
        p.valEnc(buf, s.Index(i))
    }

    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(len(buf.buf)))
    o.buf = append(o.buf, buf.buf...)
    return nil
}

func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    var bufSize int
    for i := 0; i < l; i++ {
        bufSize += p.valSize(s.Index(i))
    }

    n += len(p.tagcode)
    n += sizeVarint(uint64(bufSize))
    n += bufSize
    return
}

// Encode a slice of slice of bytes ([][]byte).
func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
    ss := *structPointer_BytesSlice(base, p.field)
    l := len(ss)
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        o.EncodeRawBytes(ss[i])
    }
    return nil
}

func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
    ss := *structPointer_BytesSlice(base, p.field)
    l := len(ss)
    if l == 0 {
        return 0
    }
    n += l * len(p.tagcode)
    for i := 0; i < l; i++ {
        n += sizeRawBytes(ss[i])
    }
    return
}

// Encode a slice of strings ([]string).
func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
    ss := *structPointer_StringSlice(base, p.field)
    l := len(ss)
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        o.EncodeStringBytes(ss[i])
    }
    return nil
}

func size_slice_string(p *Properties, base structPointer) (n int) {
    ss := *structPointer_StringSlice(base, p.field)
    l := len(ss)
    n += l * len(p.tagcode)
    for i := 0; i < l; i++ {
        n += sizeStringBytes(ss[i])
    }
    return
}

// Encode a slice of message structs ([]*struct).
func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
    var state errorState
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()

    for i := 0; i < l; i++ {
        structp := s.Index(i)
        if structPointer_IsNil(structp) {
            return errRepeatedHasNil
        }

        // Can the object marshal itself?
        if p.isMarshaler {
            m := structPointer_Interface(structp, p.stype).(Marshaler)
            data, err := m.Marshal()
            if err != nil && !state.shouldContinue(err, nil) {
                return err
            }
            o.buf = append(o.buf, p.tagcode...)
            o.EncodeRawBytes(data)
            continue
        }

        o.buf = append(o.buf, p.tagcode...)
        err := o.enc_len_struct(p.sprop, structp, &state)
        if err != nil && !state.shouldContinue(err, nil) {
            if err == ErrNil {
                return errRepeatedHasNil
            }
            return err
        }
    }
    return state.err
}

func size_slice_struct_message(p *Properties, base structPointer) (n int) {
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()
    n += l * len(p.tagcode)
    for i := 0; i < l; i++ {
        structp := s.Index(i)
        if structPointer_IsNil(structp) {
            return // return the size up to this point
        }

        // Can the object marshal itself?
        if p.isMarshaler {
            m := structPointer_Interface(structp, p.stype).(Marshaler)
            data, _ := m.Marshal()
            n += sizeRawBytes(data)
            continue
        }

        n0 := size_struct(p.sprop, structp)
        n1 := sizeVarint(uint64(n0)) // size of encoded length
        n += n0 + n1
    }
    return
}

// Encode a slice of group structs ([]*struct).
func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
    var state errorState
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()

    for i := 0; i < l; i++ {
        b := s.Index(i)
        if structPointer_IsNil(b) {
            return errRepeatedHasNil
        }

        o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))

        err := o.enc_struct(p.sprop, b)

        if err != nil && !state.shouldContinue(err, nil) {
            if err == ErrNil {
                return errRepeatedHasNil
            }
            return err
        }

        o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
    }
    return state.err
}

func size_slice_struct_group(p *Properties, base structPointer) (n int) {
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()

    n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
    n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
    for i := 0; i < l; i++ {
        b := s.Index(i)
        if structPointer_IsNil(b) {
            return // return size up to this point
        }

        n += size_struct(p.sprop, b)
    }
    return
}

// Encode an extension map.
func (o *Buffer) enc_map(p *Properties, base structPointer) error {
    exts := structPointer_ExtMap(base, p.field)
    if err := encodeExtensionsMap(*exts); err != nil {
        return err
    }

    return o.enc_map_body(*exts)
}

func (o *Buffer) enc_exts(p *Properties, base structPointer) error {
    exts := structPointer_Extensions(base, p.field)

    v, mu := exts.extensionsRead()
    if v == nil {
        return nil
    }

    mu.Lock()
    defer mu.Unlock()
    if err := encodeExtensionsMap(v); err != nil {
        return err
    }

    return o.enc_map_body(v)
}

func (o *Buffer) enc_map_body(v map[int32]Extension) error {
    // Fast-path for common cases: zero or one extensions.
    if len(v) <= 1 {
        for _, e := range v {
            o.buf = append(o.buf, e.enc...)
        }
        return nil
    }

    // Sort keys to provide a deterministic encoding.
    keys := make([]int, 0, len(v))
    for k := range v {
        keys = append(keys, int(k))
    }
    sort.Ints(keys)

    for _, k := range keys {
        o.buf = append(o.buf, v[int32(k)].enc...)
    }
    return nil
}

func size_map(p *Properties, base structPointer) int {
    v := structPointer_ExtMap(base, p.field)
    return extensionsMapSize(*v)
}

func size_exts(p *Properties, base structPointer) int {
    v := structPointer_Extensions(base, p.field)
    return extensionsSize(v)
}

// Encode a map field.
func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
    var state errorState // XXX: or do we need to plumb this through?

    /*
        A map defined as
            map<key_type, value_type> map_field = N;
        is encoded in the same way as
            message MapFieldEntry {
                key_type key = 1;
                value_type value = 2;
            }
            repeated MapFieldEntry map_field = N;
    */

    v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
    if v.Len() == 0 {
        return nil
    }

    keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)

    enc := func() error {
        if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
            return err
        }
        if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil {
            return err
        }
        return nil
    }

    // Don't sort map keys. It is not required by the spec, and C++ doesn't do it.
    for _, key := range v.MapKeys() {
        val := v.MapIndex(key)

        keycopy.Set(key)
        valcopy.Set(val)

        o.buf = append(o.buf, p.tagcode...)
        if err := o.enc_len_thing(enc, &state); err != nil {
            return err
        }
    }
    return nil
}

func size_new_map(p *Properties, base structPointer) int {
    v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V

    keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)

    n := 0
    for _, key := range v.MapKeys() {
        val := v.MapIndex(key)
        keycopy.Set(key)
        valcopy.Set(val)

        // Tag codes for key and val are the responsibility of the sub-sizer.
        keysize := p.mkeyprop.size(p.mkeyprop, keybase)
        valsize := p.mvalprop.size(p.mvalprop, valbase)
        entry := keysize + valsize
        // Add on tag code and length of map entry itself.
        n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry
    }
    return n
}

// mapEncodeScratch returns a new reflect.Value matching the map's value type,
// and a structPointer suitable for passing to an encoder or sizer.
func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
    // Prepare addressable doubly-indirect placeholders for the key and value types.
    // This is needed because the element-type encoders expect **T, but the map iteration produces T.

    keycopy = reflect.New(mapType.Key()).Elem()                 // addressable K
    keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
    keyptr.Set(keycopy.Addr())                                  //
    keybase = toStructPointer(keyptr.Addr())                    // **K

    // Value types are more varied and require special handling.
    switch mapType.Elem().Kind() {
    case reflect.Slice:
        // []byte
        var dummy []byte
        valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
        valbase = toStructPointer(valcopy.Addr())
    case reflect.Ptr:
        // message; the generated field type is map[K]*Msg (so V is *Msg),
        // so we only need one level of indirection.
        valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
        valbase = toStructPointer(valcopy.Addr())
    default:
        // everything else
        valcopy = reflect.New(mapType.Elem()).Elem()                // addressable V
        valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
        valptr.Set(valcopy.Addr())                                  //
        valbase = toStructPointer(valptr.Addr())                    // **V
    }
    return
}

// Encode a struct.
func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
    var state errorState
    // Encode fields in tag order so that decoders may use optimizations
    // that depend on the ordering.
    // https://developers.google.com/protocol-buffers/docs/encoding#order
    for _, i := range prop.order {
        p := prop.Prop[i]
        if p.enc != nil {
            err := p.enc(o, p, base)
            if err != nil {
                if err == ErrNil {
                    if p.Required && state.err == nil {
                        state.err = &RequiredNotSetError{p.Name}
                    }
                } else if err == errRepeatedHasNil {
                    // Give more context to nil values in repeated fields.
                    return errors.New("repeated field " + p.OrigName + " has nil element")
                } else if !state.shouldContinue(err, p) {
                    return err
                }
            }
            if len(o.buf) > maxMarshalSize {
                return ErrTooLarge
            }
        }
    }

    // Do oneof fields.
    if prop.oneofMarshaler != nil {
        m := structPointer_Interface(base, prop.stype).(Message)
        if err := prop.oneofMarshaler(m, o); err == ErrNil {
            return errOneofHasNil
        } else if err != nil {
            return err
        }
    }

    // Add unrecognized fields at the end.
    if prop.unrecField.IsValid() {
        v := *structPointer_Bytes(base, prop.unrecField)
        if len(o.buf)+len(v) > maxMarshalSize {
            return ErrTooLarge
        }
        if len(v) > 0 {
            o.buf = append(o.buf, v...)
        }
    }

    return state.err
}

func size_struct(prop *StructProperties, base structPointer) (n int) {
    for _, i := range prop.order {
        p := prop.Prop[i]
        if p.size != nil {
            n += p.size(p, base)
        }
    }

    // Add unrecognized fields at the end.
    if prop.unrecField.IsValid() {
        v := *structPointer_Bytes(base, prop.unrecField)
        n += len(v)
    }

    // Factor in any oneof fields.
    if prop.oneofSizer != nil {
        m := structPointer_Interface(base, prop.stype).(Message)
        n += prop.oneofSizer(m)
    }

    return
}

var zeroes [20]byte // longer than any conceivable sizeVarint

// Encode a struct, preceded by its encoded length (as a varint).
func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
    return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
}

// Encode something, preceded by its encoded length (as a varint).
func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
    iLen := len(o.buf)
    o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
    iMsg := len(o.buf)
    err := enc()
    if err != nil && !state.shouldContinue(err, nil) {
        return err
    }
    lMsg := len(o.buf) - iMsg
    lLen := sizeVarint(uint64(lMsg))
    switch x := lLen - (iMsg - iLen); {
    case x > 0: // actual length is x bytes larger than the space we reserved
        // Move msg x bytes right.
        o.buf = append(o.buf, zeroes[:x]...)
        copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
    case x < 0: // actual length is x bytes smaller than the space we reserved
        // Move msg x bytes left.
        copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
        o.buf = o.buf[:len(o.buf)+x] // x is negative
    }
    // Encode the length in the reserved space.
    o.buf = o.buf[:iLen]
    o.EncodeVarint(uint64(lMsg))
    o.buf = o.buf[:len(o.buf)+lMsg]
    return state.err
}

// errorState maintains the first error that occurs and updates that error
// with additional context.
type errorState struct {
    err error
}

// shouldContinue reports whether encoding should continue upon encountering the
// given error. If the error is RequiredNotSetError, shouldContinue returns true
// and, if this is the first appearance of that error, remembers it for future
// reporting.
//
// If prop is not nil, it may update any error with additional context about the
// field with the error.
func (s *errorState) shouldContinue(err error, prop *Properties) bool {
    // Ignore unset required fields.
    reqNotSet, ok := err.(*RequiredNotSetError)
    if !ok {
        return false
    }
    if s.err == nil {
        if prop != nil {
            err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
        }
        s.err = err
    }
    return true
}