Skip to content

Add Defaults.Serializable implementation macro #196

Open
@hank121314

Description

@hank121314

Introduction

Create a macro that can automatically implement Defaults.Serializable for user-defined custom structures.

Motivation

Implementing Defaults.Serializable for custom structures every time can be annoying and leads to redundant code.
For nested structures, developers need to implement it for each struct individually.
Having a macro to handle this automatically would greatly improve efficiency and reduce repetitive work.

Detailed design

Here is an example of the macro, currently named @DefaultSerializable.

@DefaultsSerializable
struct User {
  let name: String
  let age: Int
}

// Generated
extension User: Defaults.Serializable {
	static let bridge = UserBridge()

	struct UserBridge: Defaults.Bridge {
		typealias Value = User
		typealias Serializable = [String: String]

		public func serialize(_ value: Value?) -> Serializable? {
			guard let value else {
				return nil
			}

			return [
				"name": value.name,
				"age": value.age
			]
		}

		public func deserialize(_ object: Serializable?) -> Value? {
			guard
				let object,
				let name = object["name"],
				let age = object["age"]
			else {
				return nil
			}

			return User(
				name: name,
				age: age
			)
		}
	}
}

Stage

Since this is a large macro, I would like to split the implementation into the following stages:

Stage 1

Implement @DefaultSerializable only.

Stage 2

Implement common used field attributes such as skip (The member should be an Optional to apply skip attribute).

Stage 3

Implement skip_serializaing_if/skip_deserializaing_if (Not quite sure whether this can be achieved or not; further investigation is needed.)

Stage ?

Implement rename-related fields (though I’m not entirely sure whether this will be useful in our case, as we should always use Defaults to access them 🤔)."

Conclusion

The ultimate goal is to implement all attributes mentioned in the serde attributes.

Note that this is still in the early stages.
Any feedback is welcome!

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions