Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Defaults.Serializable implementation macro #196

Open
hank121314 opened this issue Jan 19, 2025 · 1 comment
Open

Add Defaults.Serializable implementation macro #196

hank121314 opened this issue Jan 19, 2025 · 1 comment
Assignees

Comments

@hank121314
Copy link
Collaborator

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!

@hank121314 hank121314 self-assigned this Jan 19, 2025
@sindresorhus
Copy link
Owner

sindresorhus commented Jan 20, 2025

This would be super useful 👍


Some inspiration:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants