๐Ÿ“ฆ apache / fory

๐Ÿ“„ type-system.md ยท 450 lines
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---
title: FDL Type System
sidebar_position: 3
id: fdl_type_system
license: |
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
---

This document describes the FDL type system and how types map to each target language.

## Overview

FDL provides a rich type system designed for cross-language compatibility:

- **Primitive Types**: Basic scalar types (integers, floats, strings, etc.)
- **Enum Types**: Named integer constants
- **Message Types**: Structured compound types
- **Collection Types**: Lists and maps
- **Nullable Types**: Optional/nullable variants

## Primitive Types

### Boolean

```proto
bool is_active = 1;
```

| Language | Type                  | Notes              |
| -------- | --------------------- | ------------------ |
| Java     | `boolean` / `Boolean` | Primitive or boxed |
| Python   | `bool`                |                    |
| Go       | `bool`                |                    |
| Rust     | `bool`                |                    |
| C++      | `bool`                |                    |

### Integer Types

FDL provides fixed-width signed integers:

| FDL Type | Size   | Range             |
| -------- | ------ | ----------------- |
| `int8`   | 8-bit  | -128 to 127       |
| `int16`  | 16-bit | -32,768 to 32,767 |
| `int32`  | 32-bit | -2^31 to 2^31 - 1 |
| `int64`  | 64-bit | -2^63 to 2^63 - 1 |

**Language Mapping:**

| FDL     | Java    | Python         | Go      | Rust  | C++       |
| ------- | ------- | -------------- | ------- | ----- | --------- |
| `int8`  | `byte`  | `pyfory.int8`  | `int8`  | `i8`  | `int8_t`  |
| `int16` | `short` | `pyfory.int16` | `int16` | `i16` | `int16_t` |
| `int32` | `int`   | `pyfory.int32` | `int32` | `i32` | `int32_t` |
| `int64` | `long`  | `pyfory.int64` | `int64` | `i64` | `int64_t` |

**Examples:**

```proto
message Counters {
    int8 tiny = 1;
    int16 small = 2;
    int32 medium = 3;
    int64 large = 4;
}
```

**Python Type Hints:**

Python's native `int` is arbitrary precision, so FDL uses type wrappers for fixed-width integers:

```python
from pyfory import int8, int16, int32

@dataclass
class Counters:
    tiny: int8
    small: int16
    medium: int32
    large: int  # int64 maps to native int
```

### Floating-Point Types

| FDL Type  | Size   | Precision     |
| --------- | ------ | ------------- |
| `float32` | 32-bit | ~7 digits     |
| `float64` | 64-bit | ~15-16 digits |

**Language Mapping:**

| FDL       | Java     | Python           | Go        | Rust  | C++      |
| --------- | -------- | ---------------- | --------- | ----- | -------- |
| `float32` | `float`  | `pyfory.float32` | `float32` | `f32` | `float`  |
| `float64` | `double` | `pyfory.float64` | `float64` | `f64` | `double` |

**Example:**

```proto
message Coordinates {
    float64 latitude = 1;
    float64 longitude = 2;
    float32 altitude = 3;
}
```

### String Type

UTF-8 encoded text:

```proto
string name = 1;
```

| Language | Type          | Notes                 |
| -------- | ------------- | --------------------- |
| Java     | `String`      | Immutable             |
| Python   | `str`         |                       |
| Go       | `string`      | Immutable             |
| Rust     | `String`      | Owned, heap-allocated |
| C++      | `std::string` |                       |

### Bytes Type

Raw binary data:

```proto
bytes data = 1;
```

| Language | Type                   | Notes     |
| -------- | ---------------------- | --------- |
| Java     | `byte[]`               |           |
| Python   | `bytes`                | Immutable |
| Go       | `[]byte`               |           |
| Rust     | `Vec<u8>`              |           |
| C++      | `std::vector<uint8_t>` |           |

### Temporal Types

#### Date

Calendar date without time:

```proto
date birth_date = 1;
```

| Language | Type                             | Notes                   |
| -------- | -------------------------------- | ----------------------- |
| Java     | `java.time.LocalDate`            |                         |
| Python   | `datetime.date`                  |                         |
| Go       | `time.Time`                      | Time portion ignored    |
| Rust     | `chrono::NaiveDate`              | Requires `chrono` crate |
| C++      | `fory::serialization::LocalDate` |                         |

#### Timestamp

Date and time with nanosecond precision:

```proto
timestamp created_at = 1;
```

| Language | Type                             | Notes                   |
| -------- | -------------------------------- | ----------------------- |
| Java     | `java.time.Instant`              | UTC-based               |
| Python   | `datetime.datetime`              |                         |
| Go       | `time.Time`                      |                         |
| Rust     | `chrono::NaiveDateTime`          | Requires `chrono` crate |
| C++      | `fory::serialization::Timestamp` |                         |

## Enum Types

Enums define named integer constants:

```proto
enum Priority [id=100] {
    LOW = 0;
    MEDIUM = 1;
    HIGH = 2;
    CRITICAL = 3;
}
```

**Language Mapping:**

| Language | Implementation                          |
| -------- | --------------------------------------- |
| Java     | `enum Priority { LOW, MEDIUM, ... }`    |
| Python   | `class Priority(IntEnum): LOW = 0, ...` |
| Go       | `type Priority int32` with constants    |
| Rust     | `#[repr(i32)] enum Priority { ... }`    |
| C++      | `enum class Priority : int32_t { ... }` |

**Java:**

```java
public enum Priority {
    LOW,
    MEDIUM,
    HIGH,
    CRITICAL;
}
```

**Python:**

```python
class Priority(IntEnum):
    LOW = 0
    MEDIUM = 1
    HIGH = 2
    CRITICAL = 3
```

**Go:**

```go
type Priority int32

const (
    PriorityLow      Priority = 0
    PriorityMedium   Priority = 1
    PriorityHigh     Priority = 2
    PriorityCritical Priority = 3
)
```

**Rust:**

```rust
#[derive(ForyObject, Debug, Clone, PartialEq, Default)]
#[repr(i32)]
pub enum Priority {
    #[default]
    Low = 0,
    Medium = 1,
    High = 2,
    Critical = 3,
}
```

**C++:**

```cpp
enum class Priority : int32_t {
    LOW = 0,
    MEDIUM = 1,
    HIGH = 2,
    CRITICAL = 3,
};
FORY_ENUM(Priority, LOW, MEDIUM, HIGH, CRITICAL);
```

## Message Types

Messages are structured types composed of fields:

```proto
message User [id=101] {
    string id = 1;
    string name = 2;
    int32 age = 3;
}
```

**Language Mapping:**

| Language | Implementation                      |
| -------- | ----------------------------------- |
| Java     | POJO class with getters/setters     |
| Python   | `@dataclass` class                  |
| Go       | Struct with exported fields         |
| Rust     | Struct with `#[derive(ForyObject)]` |
| C++      | Struct with `FORY_STRUCT` macro     |

## Collection Types

### List (repeated)

The `repeated` modifier creates a list:

```proto
repeated string tags = 1;
repeated User users = 2;
```

**Language Mapping:**

| FDL               | Java            | Python       | Go         | Rust          | C++                        |
| ----------------- | --------------- | ------------ | ---------- | ------------- | -------------------------- |
| `repeated string` | `List<String>`  | `List[str]`  | `[]string` | `Vec<String>` | `std::vector<std::string>` |
| `repeated int32`  | `List<Integer>` | `List[int]`  | `[]int32`  | `Vec<i32>`    | `std::vector<int32_t>`     |
| `repeated User`   | `List<User>`    | `List[User]` | `[]User`   | `Vec<User>`   | `std::vector<User>`        |

**List modifiers:**

| FDL                        | Java                                           | Python                                  | Go                      | Rust                  | C++                                       |
| -------------------------- | ---------------------------------------------- | --------------------------------------- | ----------------------- | --------------------- | ----------------------------------------- |
| `optional repeated string` | `List<String>` + `@ForyField(nullable = true)` | `Optional[List[str]]`                   | `[]string` + `nullable` | `Option<Vec<String>>` | `std::optional<std::vector<std::string>>` |
| `repeated optional string` | `List<String>` (nullable elements)             | `List[Optional[str]]`                   | `[]*string`             | `Vec<Option<String>>` | `std::vector<std::optional<std::string>>` |
| `ref repeated User`        | `List<User>` + `@ForyField(ref = true)`        | `List[User]` + `pyfory.field(ref=True)` | `[]User` + `ref`        | `Arc<Vec<User>>`\*    | `std::shared_ptr<std::vector<User>>`      |
| `repeated ref User`        | `List<User>`                                   | `List[User]`                            | `[]*User` + `ref=false` | `Vec<Arc<User>>`\*    | `std::vector<std::shared_ptr<User>>`      |

\*Use `[(fory).thread_safe_pointer = false]` to generate `Rc` instead of `Arc` in Rust.

### Map

Maps with typed keys and values:

```proto
map<string, int32> counts = 1;
map<string, User> users = 2;
```

**Language Mapping:**

| FDL                  | Java                   | Python            | Go                 | Rust                    | C++                              |
| -------------------- | ---------------------- | ----------------- | ------------------ | ----------------------- | -------------------------------- |
| `map<string, int32>` | `Map<String, Integer>` | `Dict[str, int]`  | `map[string]int32` | `HashMap<String, i32>`  | `std::map<std::string, int32_t>` |
| `map<string, User>`  | `Map<String, User>`    | `Dict[str, User]` | `map[string]User`  | `HashMap<String, User>` | `std::map<std::string, User>`    |

**Key Type Restrictions:**

Map keys should be hashable types:

- `string` (most common)
- Integer types (`int8`, `int16`, `int32`, `int64`)
- `bool`

Avoid using messages or complex types as keys.

## Nullable Types

The `optional` modifier makes a field nullable:

```proto
message Profile {
    string name = 1;              // Required
    optional string bio = 2;      // Nullable
    optional int32 age = 3;       // Nullable integer
}
```

**Language Mapping:**

| FDL               | Java       | Python          | Go        | Rust             | C++                          |
| ----------------- | ---------- | --------------- | --------- | ---------------- | ---------------------------- |
| `optional string` | `String`\* | `Optional[str]` | `*string` | `Option<String>` | `std::optional<std::string>` |
| `optional int32`  | `Integer`  | `Optional[int]` | `*int32`  | `Option<i32>`    | `std::optional<int32_t>`     |

\*Java uses boxed types with `@ForyField(nullable = true)` annotation.

**Default Values:**

| Type               | Default Value       |
| ------------------ | ------------------- |
| Non-optional types | Language default    |
| Optional types     | `null`/`None`/`nil` |

## Reference Types

The `ref` modifier enables reference tracking:

```proto
message TreeNode {
    string value = 1;
    ref TreeNode parent = 2;
    repeated ref TreeNode children = 3;
}
```

**Use Cases:**

1. **Shared References**: Same object referenced from multiple places
2. **Circular References**: Object graphs with cycles
3. **Large Objects**: Avoid duplicate serialization

**Language Mapping:**

| FDL        | Java     | Python | Go                     | Rust        | C++                     |
| ---------- | -------- | ------ | ---------------------- | ----------- | ----------------------- |
| `ref User` | `User`\* | `User` | `*User` + `fory:"ref"` | `Arc<User>` | `std::shared_ptr<User>` |

\*Java uses `@ForyField(ref = true)` annotation.

Rust uses `Arc` by default; set `[(fory).thread_safe_pointer = false]` to use `Rc`.

## Type Compatibility Matrix

This matrix shows which type conversions are safe across languages:

| From โ†’ To   | bool | int8 | int16 | int32 | int64 | float32 | float64 | string |
| ----------- | ---- | ---- | ----- | ----- | ----- | ------- | ------- | ------ |
| **bool**    | โœ“    | โœ“    | โœ“     | โœ“     | โœ“     | -       | -       | -      |
| **int8**    | -    | โœ“    | โœ“     | โœ“     | โœ“     | โœ“       | โœ“       | -      |
| **int16**   | -    | -    | โœ“     | โœ“     | โœ“     | โœ“       | โœ“       | -      |
| **int32**   | -    | -    | -     | โœ“     | โœ“     | -       | โœ“       | -      |
| **int64**   | -    | -    | -     | -     | โœ“     | -       | -       | -      |
| **float32** | -    | -    | -     | -     | -     | โœ“       | โœ“       | -      |
| **float64** | -    | -    | -     | -     | -     | -       | โœ“       | -      |
| **string**  | -    | -    | -     | -     | -     | -       | -       | โœ“      |

โœ“ = Safe conversion, - = Not recommended

## Best Practices

### Choosing Integer Types

- Use `int32` as the default for most integers
- Use `int64` for large values (timestamps, IDs)
- Use `int8`/`int16` only when storage size matters

### String vs Bytes

- Use `string` for text data (UTF-8)
- Use `bytes` for binary data (images, files, encrypted data)

### Optional vs Required

- Use `optional` when the field may legitimately be absent
- Default to required fields for better type safety
- Document why a field is optional

### Reference Tracking

- Use `ref` only when needed (shared/circular references)
- Reference tracking adds overhead
- Test with realistic data to ensure correctness

### Collections

- Prefer `repeated` for ordered sequences
- Use `map` for key-value lookups
- Consider message types for complex map values