Skip to content

Commit

Permalink
feat: add zero parser (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
krafugo committed Aug 23, 2023
1 parent 8caf06f commit 0f82d2d
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions pkg/parsers/zero/zero.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package zero

import (
"encoding/json"
"os"
)

type ZeroProgram struct {
Builtins map[string]int64 `json:"builtins"`
Code string `json:"code"`
DebugInfo DebugInfo `json:"debug_info"`
Prime string `json:"prime"`
Version string `json:"version"`
}

type DebugInfo struct {
InstructionOffsets []int64 `json:"instruction_offsets"`
SourceCode string `json:"source_code"`
SourcePath string `json:"source_path"`
}

func (z ZeroProgram) MarshalToFile(filepath string) error {
// Marshal Output struct into JSON bytes
data, err := json.MarshalIndent(z, "", " ")
if err != nil {
return err
}

// Write JSON bytes to file
err = os.WriteFile(filepath, data, 0o644)
if err != nil {
return err
}

return nil
}

func ZeroProgramFromFile(filepath string) (zero *ZeroProgram, err error) {
content, err := os.ReadFile(filepath)
if err != nil {
return
}
return ZeroProgramFromJSON(content)
}

func ZeroProgramFromJSON(content json.RawMessage) (*ZeroProgram, error) {
var zero ZeroProgram
return &zero, json.Unmarshal(content, &zero)
}

func (z *ZeroProgram) MarshalJSON() ([]byte, error) {
return json.Marshal(z)
}

func (z *ZeroProgram) UnmarshalJSON(data []byte) error {
type zero ZeroProgram // create new type identical to ZeroProgram
var zTemp zero // create variable of new type

// Unmarshal data into zTemp
if err := json.Unmarshal(data, &zTemp); err != nil {
return err
}

// Copy data from zTemp to z
*z = ZeroProgram(zTemp)

return nil
}

0 comments on commit 0f82d2d

Please sign in to comment.