sashite-pin 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e00046935bd19fe218aed6188bc310389c9a93e5e36aad8b91890d36046c4165
4
- data.tar.gz: e90e9430c444175c658262c486eddfe3c09a6e5da2c88b0b1365fb91f14616a0
3
+ metadata.gz: 654a422f7d1d03a9b2e474e6f29644c7d8636cc6a7da60100fc49efa87ccda02
4
+ data.tar.gz: c9548c761f14c4dc76acc1376fda12fa64339bbe7d6b2567b49f205113c89b59
5
5
  SHA512:
6
- metadata.gz: f716220c9d53ba9003712d64c3335f20b395c2174637b2432f43ca01c654dca7586b84f3057747126cf899003478afc071de31cd93e76ce0dc49dd7f7a9f99d5
7
- data.tar.gz: 0aedbcd707733bbd81dd6fa48608a52f66016aec2e63162c5f841cbaf359959d3f902d8dddca2e08848d57dce1f3ccb31e3baeebb791812bea91c678a1f9fe0f
6
+ metadata.gz: fc265f0049d911133c3de8910ed15911a207fcec239aa97d8c4a9766242f2f5ca53d80802e36c9aafeac525eb79a01ef4f3625738f04622db97b210d8094296c
7
+ data.tar.gz: 5a5254e21d89dfec797ce72c62d1a65689c9db5460a91c13edba6360655483b7dd1c0a024c04ee35e5e35971c30e08518b540086112334da0a662d2ea1f3b432
data/README.md CHANGED
@@ -11,6 +11,18 @@
11
11
 
12
12
  This library implements the [PIN Specification v1.0.0](https://sashite.dev/specs/pin/1.0.0/).
13
13
 
14
+ PIN is a compact, ASCII-only token format encoding a **Piece Identity**: the tuple (**Piece Name**, **Piece Side**, **Piece State**, **Terminal Status**). Case encodes side, an optional `+`/`-` prefix encodes state, and an optional `^` suffix marks terminal pieces.
15
+
16
+ ### Implementation Constraints
17
+
18
+ | Constraint | Value | Rationale |
19
+ |------------|-------|-----------|
20
+ | Token length | 1–3 characters | `[+-]?[A-Za-z]\^?` per spec |
21
+ | Character space | 312 tokens | 26 abbreviations × 2 sides × 3 states × 2 terminal |
22
+ | Instance pool | 312 objects | All identifiers are pre-instantiated and frozen |
23
+
24
+ The closed domain of 312 possible values enables a flyweight architecture with zero allocation on the hot path.
25
+
14
26
  ## Installation
15
27
 
16
28
  ```ruby
@@ -53,40 +65,73 @@ pin = Sashite::Pin.parse("+K^")
53
65
  pin.state # => :enhanced
54
66
  pin.terminal? # => true
55
67
 
68
+ # Returns a cached instance — no allocation
69
+ Sashite::Pin.parse("+K^").equal?(Sashite::Pin.parse("+K^")) # => true
70
+
56
71
  # Invalid input raises ArgumentError
57
72
  Sashite::Pin.parse("invalid") # => raises ArgumentError
58
73
  ```
59
74
 
75
+ ### Safe Parsing (String → Identifier | nil)
76
+
77
+ Parse without raising exceptions. Returns `nil` on invalid input.
78
+
79
+ ```ruby
80
+ # Valid input returns an Identifier
81
+ Sashite::Pin.safe_parse("K") # => #<Sashite::Pin::Identifier K>
82
+ Sashite::Pin.safe_parse("+R^") # => #<Sashite::Pin::Identifier +R^>
83
+
84
+ # Invalid input returns nil — no exception allocated
85
+ Sashite::Pin.safe_parse("") # => nil
86
+ Sashite::Pin.safe_parse("invalid") # => nil
87
+ Sashite::Pin.safe_parse(nil) # => nil
88
+ ```
89
+
90
+ ### Fetching by Components (Symbol, Symbol, ... → Identifier)
91
+
92
+ Retrieve a cached identifier directly by components, bypassing string parsing entirely.
93
+
94
+ ```ruby
95
+ # Direct lookup — no string parsing, no allocation
96
+ Sashite::Pin.fetch(:K, :first) # => #<Sashite::Pin::Identifier K>
97
+ Sashite::Pin.fetch(:R, :second, :enhanced) # => #<Sashite::Pin::Identifier +r>
98
+ Sashite::Pin.fetch(:K, :first, :normal, terminal: true) # => #<Sashite::Pin::Identifier K^>
99
+
100
+ # Same cached instance as parse
101
+ Sashite::Pin.fetch(:K, :first).equal?(Sashite::Pin.parse("K")) # => true
102
+
103
+ # Invalid components raise ArgumentError
104
+ Sashite::Pin.fetch(:KK, :first) # => raises ArgumentError
105
+ Sashite::Pin.fetch(:K, :third) # => raises ArgumentError
106
+ ```
107
+
60
108
  ### Formatting (Identifier → String)
61
109
 
62
110
  Convert an `Identifier` back to a PIN string.
63
111
 
64
112
  ```ruby
65
- # From Identifier object
66
- pin = Sashite::Pin::Identifier.new(:K, :first)
67
- pin.to_s # => "K"
68
-
69
- # With attributes
70
- pin = Sashite::Pin::Identifier.new(:R, :second, :enhanced)
71
- pin.to_s # => "+r"
113
+ pin = Sashite::Pin.parse("+K^")
114
+ pin.to_s # => "+K^"
72
115
 
73
- pin = Sashite::Pin::Identifier.new(:K, :first, :normal, terminal: true)
74
- pin.to_s # => "K^"
116
+ pin = Sashite::Pin.parse("r")
117
+ pin.to_s # => "r"
75
118
  ```
76
119
 
77
120
  ### Validation
78
121
 
79
122
  ```ruby
80
- # Boolean check
123
+ # Boolean check (never raises)
124
+ # Uses an exception-free code path internally for performance.
81
125
  Sashite::Pin.valid?("K") # => true
82
126
  Sashite::Pin.valid?("+R") # => true
83
127
  Sashite::Pin.valid?("K^") # => true
84
128
  Sashite::Pin.valid?("invalid") # => false
129
+ Sashite::Pin.valid?(nil) # => false
85
130
  ```
86
131
 
87
132
  ### Transformations
88
133
 
89
- All transformations return new immutable instances.
134
+ All transformations return cached instances from the flyweight pool — no new object is ever allocated.
90
135
 
91
136
  ```ruby
92
137
  pin = Sashite::Pin.parse("K")
@@ -108,6 +153,9 @@ pin.with_abbr(:Q).to_s # => "Q"
108
153
  pin.with_side(:second).to_s # => "k"
109
154
  pin.with_state(:enhanced).to_s # => "+K"
110
155
  pin.with_terminal(true).to_s # => "K^"
156
+
157
+ # Transformations return cached instances
158
+ pin.enhance.equal?(Sashite::Pin.parse("+K")) # => true
111
159
  ```
112
160
 
113
161
  ### Queries
@@ -137,24 +185,57 @@ pin.same_terminal?(other) # => false
137
185
 
138
186
  ## API Reference
139
187
 
140
- ### Types
188
+ ### Module Methods
189
+
190
+ ```ruby
191
+ # Parses a PIN string into a cached Identifier.
192
+ # Returns a pre-instantiated, frozen instance.
193
+ # Raises ArgumentError if the string is not valid.
194
+ #
195
+ # @param string [String] PIN string
196
+ # @return [Identifier]
197
+ # @raise [ArgumentError] if invalid
198
+ def Sashite::Pin.parse(string)
199
+
200
+ # Parses a PIN string without raising.
201
+ # Returns a cached Identifier on success, nil on failure.
202
+ # Never allocates exception objects or captures backtraces.
203
+ #
204
+ # @param string [String] PIN string
205
+ # @return [Identifier, nil]
206
+ def Sashite::Pin.safe_parse(string)
207
+
208
+ # Retrieves a cached Identifier by components.
209
+ # Bypasses string parsing entirely — direct hash lookup.
210
+ # Raises ArgumentError if components are invalid.
211
+ #
212
+ # @param abbr [Symbol] Piece abbreviation (:A through :Z)
213
+ # @param side [Symbol] Piece side (:first or :second)
214
+ # @param state [Symbol] Piece state (:normal, :enhanced, or :diminished)
215
+ # @param terminal [Boolean] Terminal status
216
+ # @return [Identifier]
217
+ # @raise [ArgumentError] if invalid
218
+ def Sashite::Pin.fetch(abbr, side, state = :normal, terminal: false)
219
+
220
+ # Reports whether string is a valid PIN.
221
+ # Never raises; returns false for any invalid input.
222
+ # Uses an exception-free code path internally for performance.
223
+ #
224
+ # @param string [String] PIN string
225
+ # @return [Boolean]
226
+ def Sashite::Pin.valid?(string)
227
+ ```
228
+
229
+ ### Identifier
141
230
 
142
231
  ```ruby
143
232
  # Identifier represents a parsed PIN with all attributes.
233
+ # All instances are frozen and pre-instantiated — never construct directly,
234
+ # use Sashite::Pin.parse, .safe_parse, or .fetch instead.
144
235
  class Sashite::Pin::Identifier
145
- # Creates an Identifier from attributes.
146
- # Raises ArgumentError if attributes are invalid.
147
- #
148
- # @param abbr [Symbol] Piece name abbreviation (:A to :Z)
149
- # @param side [Symbol] Piece side (:first or :second)
150
- # @param state [Symbol] Piece state (:normal, :enhanced, or :diminished)
151
- # @param terminal [Boolean] Terminal status
152
- # @return [Identifier]
153
- def initialize(abbr, side, state = :normal, terminal: false)
154
-
155
236
  # Returns the piece name abbreviation (always uppercase symbol).
156
237
  #
157
- # @return [Symbol]
238
+ # @return [Symbol] :A through :Z
158
239
  def abbr
159
240
 
160
241
  # Returns the piece side.
@@ -179,40 +260,9 @@ class Sashite::Pin::Identifier
179
260
  end
180
261
  ```
181
262
 
182
- ### Constants
183
-
184
- ```ruby
185
- Sashite::Pin::Constants::VALID_ABBRS # => [:A, :B, ..., :Z]
186
- Sashite::Pin::Constants::VALID_SIDES # => [:first, :second]
187
- Sashite::Pin::Constants::VALID_STATES # => [:normal, :enhanced, :diminished]
188
- Sashite::Pin::Constants::MAX_STRING_LENGTH # => 3
189
- ```
190
-
191
- ### Parsing
192
-
193
- ```ruby
194
- # Parses a PIN string into an Identifier.
195
- # Raises ArgumentError if the string is not valid.
196
- #
197
- # @param string [String] PIN string
198
- # @return [Identifier]
199
- # @raise [ArgumentError] if invalid
200
- def Sashite::Pin.parse(string)
201
- ```
202
-
203
- ### Validation
204
-
205
- ```ruby
206
- # Reports whether string is a valid PIN.
207
- #
208
- # @param string [String] PIN string
209
- # @return [Boolean]
210
- def Sashite::Pin.valid?(string)
211
- ```
212
-
213
263
  ### Transformations
214
264
 
215
- All transformations return new `Sashite::Pin::Identifier` instances:
265
+ All transformations return cached `Sashite::Pin::Identifier` instances from the flyweight pool:
216
266
 
217
267
  ```ruby
218
268
  # State transformations
@@ -256,9 +306,18 @@ def same_state?(other) # => Boolean
256
306
  def same_terminal?(other) # => Boolean
257
307
  ```
258
308
 
309
+ ### Constants
310
+
311
+ ```ruby
312
+ Sashite::Pin::Constants::VALID_ABBRS # => [:A, :B, ..., :Z]
313
+ Sashite::Pin::Constants::VALID_SIDES # => [:first, :second]
314
+ Sashite::Pin::Constants::VALID_STATES # => [:normal, :enhanced, :diminished]
315
+ Sashite::Pin::Constants::MAX_STRING_LENGTH # => 3
316
+ ```
317
+
259
318
  ### Errors
260
319
 
261
- All parsing and validation errors raise `ArgumentError` with descriptive messages:
320
+ All errors raise `ArgumentError` with descriptive messages:
262
321
 
263
322
  | Message | Cause |
264
323
  |---------|-------|
@@ -270,13 +329,30 @@ All parsing and validation errors raise `ArgumentError` with descriptive message
270
329
 
271
330
  ## Design Principles
272
331
 
273
- - **Bounded values**: Explicit validation of abbreviations, sides, and states
274
- - **Object-oriented**: `Identifier` class enables methods and encapsulation
332
+ - **Spec conformance**: Strict adherence to PIN v1.0.0
333
+ - **Flyweight identifiers**: All 312 possible instances are pre-built and frozen; parsing, fetching, and transformations return cached objects with zero allocation
334
+ - **Performance-oriented internals**: Exception-free validation path; exceptions only at the public API boundary
275
335
  - **Ruby idioms**: `valid?` predicate, `to_s` conversion, `ArgumentError` for invalid input
276
- - **Immutable identifiers**: Frozen instances prevent mutation
277
- - **Transformation methods**: Return new instances for attribute changes
336
+ - **Immutable identifiers**: All instances are frozen after creation
278
337
  - **No dependencies**: Pure Ruby standard library only
279
338
 
339
+ ### Performance Architecture
340
+
341
+ PIN has a closed domain of exactly 312 valid tokens (26 letters × 2 cases × 3 states × 2 terminal). The implementation exploits this constraint through three complementary strategies.
342
+
343
+ **Flyweight instance pool** — All 312 `Identifier` objects are pre-instantiated and frozen at load time. `parse`, `safe_parse`, `fetch`, and all transformation methods return these cached instances via hash lookup. No `Identifier` is ever allocated after the module loads. This makes PIN essentially free to call from EPIN, FEEN, or any other hot loop — every call is a hash lookup returning a pre-existing frozen object.
344
+
345
+ **Dual-path parsing** — Parsing is split into two layers to avoid using exceptions for control flow:
346
+
347
+ - **Validation layer** — `safe_parse` performs all validation and returns the cached `Identifier` on success, or `nil` on failure, without raising, without allocating exception objects, and without capturing backtraces.
348
+ - **Public API layer** — `parse` calls `safe_parse` internally. On failure, it raises `ArgumentError` exactly once, at the boundary. `valid?` calls `safe_parse` and returns a boolean directly, never raising.
349
+
350
+ **Zero-allocation transformations** — Every transformation method (`flip`, `enhance`, `diminish`, `terminal`, `with_abbr`, etc.) computes the target component values and performs a direct lookup into the instance pool. The result is always a cached object — transformations never allocate. Chaining like `pin.enhance.flip.terminal` performs three hash lookups and zero allocations.
351
+
352
+ **Direct component lookup** — `fetch` bypasses string parsing entirely. Given components `(:K, :first, :enhanced, terminal: true)`, it performs a single hash lookup into the instance pool. This is the fastest path for callers that already have structured data (e.g., EPIN's internal construction from parsed components).
353
+
354
+ This architecture ensures that PIN never becomes a bottleneck when called from higher-level parsers like EPIN or FEEN, where it may be invoked hundreds of times per position.
355
+
280
356
  ## Related Specifications
281
357
 
282
358
  - [Game Protocol](https://sashite.dev/game-protocol/) — Conceptual foundation
@@ -2,11 +2,16 @@
2
2
 
3
3
  module Sashite
4
4
  module Pin
5
- # Constants for PIN (Piece Identifier Notation).
5
+ # Performance-oriented constants for PIN (Piece Identifier Notation).
6
6
  #
7
- # This module defines the valid values for PIN attributes.
7
+ # All lookups are O(1) frozen Hashes. Byte-level constants eliminate
8
+ # repeated method calls in the parser hot path.
8
9
  module Constants
9
- # Valid piece name abbreviations (uppercase symbols A-Z).
10
+ # ====================================================================
11
+ # Domain values
12
+ # ====================================================================
13
+
14
+ # Valid piece name abbreviations (uppercase symbols :A..:Z).
10
15
  VALID_ABBRS = %i[A B C D E F G H I J K L M N O P Q R S T U V W X Y Z].freeze
11
16
 
12
17
  # Valid player sides.
@@ -15,21 +20,54 @@ module Sashite
15
20
  # Valid piece states.
16
21
  VALID_STATES = %i[normal enhanced diminished].freeze
17
22
 
18
- # Maximum length of a valid PIN string.
19
- # Corresponds to "+K^" (state modifier + letter + terminal marker).
20
- MAX_STRING_LENGTH = 3
23
+ # ====================================================================
24
+ # O(1) validation lookups (frozen Hashes faster than Array#include?)
25
+ # ====================================================================
26
+
27
+ # { :A => true, :B => true, … :Z => true }
28
+ ABBR_SET = VALID_ABBRS.each_with_object({}) { |a, h| h[a] = true }.freeze
29
+
30
+ # { :first => true, :second => true }
31
+ SIDE_SET = VALID_SIDES.each_with_object({}) { |s, h| h[s] = true }.freeze
21
32
 
22
- # State modifier for enhanced state.
23
- ENHANCED_PREFIX = "+"
33
+ # { :normal => true, :enhanced => true, :diminished => true }
34
+ STATE_SET = VALID_STATES.each_with_object({}) { |s, h| h[s] = true }.freeze
24
35
 
25
- # State modifier for diminished state.
36
+ # ====================================================================
37
+ # String fragments (frozen, reused by Identifier#to_s)
38
+ # ====================================================================
39
+
40
+ ENHANCED_PREFIX = "+"
26
41
  DIMINISHED_PREFIX = "-"
42
+ TERMINAL_SUFFIX = "^"
43
+ EMPTY_STRING = ""
44
+
45
+ # ====================================================================
46
+ # Byte constants (used by Parser for zero-allocation character checks)
47
+ # ====================================================================
48
+
49
+ # State modifier bytes
50
+ BYTE_PLUS = 0x2B # '+'
51
+ BYTE_MINUS = 0x2D # '-'
52
+
53
+ # Terminal marker byte
54
+ BYTE_CARET = 0x5E # '^'
55
+
56
+ # ASCII letter ranges
57
+ BYTE_UPPER_A = 0x41 # 'A'
58
+ BYTE_UPPER_Z = 0x5A # 'Z'
59
+ BYTE_LOWER_A = 0x61 # 'a'
60
+ BYTE_LOWER_Z = 0x7A # 'z'
61
+
62
+ # Case conversion offset (lowercase - uppercase = 32)
63
+ CASE_OFFSET = 0x20
27
64
 
28
- # Empty string (no modifier).
29
- EMPTY_STRING = ""
65
+ # ====================================================================
66
+ # Token length
67
+ # ====================================================================
30
68
 
31
- # Terminal marker suffix.
32
- TERMINAL_SUFFIX = "^"
69
+ # Maximum byte length of a valid PIN string: "+K^"
70
+ MAX_BYTE_LENGTH = 3
33
71
  end
34
72
  end
35
73
  end
@@ -5,21 +5,18 @@ module Sashite
5
5
  module Errors
6
6
  class Argument < ::ArgumentError
7
7
  # Centralized error messages for PIN parsing and validation.
8
- #
9
- # @example
10
- # raise Errors::Argument, Messages::EMPTY_INPUT
11
8
  module Messages
12
9
  # Parsing errors
13
- EMPTY_INPUT = "empty input"
14
- INPUT_TOO_LONG = "input exceeds 3 characters"
10
+ EMPTY_INPUT = "empty input"
11
+ INPUT_TOO_LONG = "input exceeds 3 characters"
15
12
  MUST_CONTAIN_ONE_LETTER = "must contain exactly one letter"
16
- INVALID_STATE_MODIFIER = "invalid state modifier"
13
+ INVALID_STATE_MODIFIER = "invalid state modifier"
17
14
  INVALID_TERMINAL_MARKER = "invalid terminal marker"
18
15
 
19
- # Validation errors (constructor)
20
- INVALID_ABBR = "abbr must be a symbol from :A to :Z"
21
- INVALID_SIDE = "side must be :first or :second"
22
- INVALID_STATE = "state must be :normal, :enhanced, or :diminished"
16
+ # Validation errors (constructor / fetch)
17
+ INVALID_ABBR = "abbr must be a symbol from :A to :Z"
18
+ INVALID_SIDE = "side must be :first or :second"
19
+ INVALID_STATE = "state must be :normal, :enhanced, or :diminished"
23
20
  INVALID_TERMINAL = "terminal must be true or false"
24
21
  end
25
22
  end
@@ -6,9 +6,6 @@ module Sashite
6
6
  module Pin
7
7
  module Errors
8
8
  # Error raised when PIN parsing or validation fails.
9
- #
10
- # @example
11
- # raise Argument, Argument::Messages::EMPTY_INPUT
12
9
  class Argument < ::ArgumentError
13
10
  end
14
11
  end