| 93 | } |
| 94 | |
| 95 | // Same nesting limit as serde_json, which the reference safetensors loader |
| 96 | // uses to parse the header. Without a limit, a deeply nested value recurses |
| 97 | // until the native stack is exhausted. |
| 98 | constexpr size_t kMaxSkippedJsonDepth = 128; |
| 99 | |
| 100 | void skip_json_value(const std::string & text, size_t & pos, size_t depth = 0) { |
| 101 | skip_ws(text, pos); |
| 102 | if (pos >= text.size()) { |
| 103 | throw std::runtime_error("unexpected end of json while skipping value"); |
| 104 | } |
| 105 | if (depth >= kMaxSkippedJsonDepth) { |
| 106 | throw std::runtime_error("json value nested too deeply while skipping value"); |
| 107 | } |
| 108 | const char ch = text[pos]; |
| 109 | if (ch == '"') { |
| 110 | (void)parse_string(text, pos); |
| 111 | return; |
| 112 | } |
| 113 | if (ch == '{') { |
| 114 | ++pos; |
| 115 | while (true) { |
| 116 | skip_ws(text, pos); |
| 117 | if (pos < text.size() && text[pos] == '}') { |
| 118 | ++pos; |
| 119 | return; |
| 120 | } |
| 121 | (void)parse_string(text, pos); |
| 122 | expect_char(text, pos, ':'); |
| 123 | skip_json_value(text, pos, depth + 1); |
| 124 | skip_ws(text, pos); |
| 125 | if (pos < text.size() && text[pos] == ',') { |
| 126 | ++pos; |
| 127 | continue; |
| 128 | } |
| 129 | if (pos < text.size() && text[pos] == '}') { |
| 130 | ++pos; |
| 131 | return; |
| 132 | } |
| 133 | throw std::runtime_error("invalid json object while skipping value"); |
| 134 | } |
| 135 | } |
| 136 | if (ch == '[') { |
| 137 | ++pos; |
| 138 | while (true) { |
| 139 | skip_ws(text, pos); |
| 140 | if (pos < text.size() && text[pos] == ']') { |
| 141 | ++pos; |
| 142 | return; |
| 143 | } |
| 144 | skip_json_value(text, pos, depth + 1); |
| 145 | skip_ws(text, pos); |
| 146 | if (pos < text.size() && text[pos] == ',') { |
| 147 | ++pos; |
| 148 | continue; |
| 149 | } |
| 150 | if (pos < text.size() && text[pos] == ']') { |
| 151 | ++pos; |
| 152 | return; |
nothing calls this directly
no test coverage detected