ronantakizawa/codereview-bench huggingface dataset:
Repository: napi-rs/napi-rs
File: crates/build/src/lib.rs (Rust)

Code before:
      .expect("CARGO_PKG_NAME is not set")
      .to_uppercase()
      .replace("-", "_")
  );

  let target_env = env::var("CARGO_CFG_TARGET_ENV").expect("CARGO_CFG_TARGET_ENV is not set");
  let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH is not set");

  match env::var("CARGO_CFG_TARGET_OS").as_deref() {
    Ok("macos") => {
      macos::setup();
    }
    Ok("android") => if android::setup().is_ok() {},
    Ok("wasi") => {
      wasi::setup();
    }
    Ok("windows") => {
      if let Ok("gnu") = env::var("CARGO_CFG_TARGET_ENV").as_deref() {
        windows::setup_gnu();
      }
    }
    Ok("linux") => {
      if target_env == "gnu" && target_arch == "x86_64" {
        if let Ok(version) = rustc_version::version() {
          // https://blog.rust-lang.org/2025/09/01/rust-lld-on-1.90.0-stable/
          if version.major >= 1 && version.minor >= 90 {}
        }
      }
    }
    _ => {}
  }
}


Review comment (suggestion):
Won't work for version like `2.0`


```suggestion
          if (version.major > 1) || (version.major == 1 && version.minor >= 90) {}
```

Code after:
      .to_uppercase()
      .replace("-", "_")
  );

  let target_env = env::var("CARGO_CFG_TARGET_ENV").expect("CARGO_CFG_TARGET_ENV is not set");
  let target_os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS is not set");

  match target_os.as_str() {
    "android" => if android::setup().is_ok() {},
    "wasi" => {
      wasi::setup();
    }
    "windows" => {
      if let Ok("gnu") = env::var("CARGO_CFG_TARGET_ENV").as_deref() {
        windows::setup_gnu();
      }
    }
    _ => {}
  }

  if (target_env == "gnu" && target_os != "windows") || target_os == "freebsd" {
    // https://sourceware.org/bugzilla/show_bug.cgi?id=21032
    // https://sourceware.org/bugzilla/show_bug.cgi?id=21031
    // https://github.com/rust-lang/rust/issues/134820
    // pthread_key_create() destructors and segfault after a DSO unloading
    println!("cargo:rustc-link-arg=-Wl,-z,nodelete");
  }
}
Repository: napi-rs/napi-rs
File: examples/napi/__tests__/values.spec.ts (TypeScript)

Code before:
  getExternal,
  mutateExternal,
  createExternalString,
  createExternalRef,
  xxh2,
  xxh3,
  xxh64Alias,
  tsRename,
  acceptArraybuffer,
  acceptSlice,
  u8ArrayToArray,
  i8ArrayToArray,
  u16ArrayToArray,
  i16ArrayToArray,
  u32ArrayToArray,
  i32ArrayToArray,
  u64ArrayToArray,
  i64ArrayToArray,
  f32ArrayToArray,
  f64ArrayToArray,
  acceptUint8ClampedSlice,
  acceptUint8ClampedSliceAndBufferSlice,
  convertU32Array,
  createExternalTypedArray,
  mutateTypedArray,
  receiveAllOptionalObject,
  objectGetNamedPropertyShouldPerformTypecheck,
  fnReceivedAliased,
  ALIAS,
  appendBuffer,
  returnNull,
  returnUndefined,
  Dog,
  Bird,
  Assets,
  receiveStrictObject,
  receiveClassOrNumber,
  JsClassForEither,
  receiveMutClassOrNumber,
  getStrFromObject,
  testSerdeRoundtrip,
  testSerdeBigNumberPrecision,
  testSerdeBufferBytes,
  getBigintJsonValue,
  createObjWithProperty,
  receiveObjectOnlyFromJs,
  dateToNumber,
  chronoUtcDateToMillis,
  chronoLocalDateToMillis,
  chronoDateWithTimezoneToMillis,
  chronoDateFixtureReturn1,

Review comment (suggestion):
Inconsistent naming: The imported function name should be `mutateArrayBuffer` (with capital 'B') to follow camelCase conventions and match similar functions in the codebase like `arrayBufferFromData` and `arrayBufferFromExternal`. Currently it's `mutateArraybuffer` with lowercase 'b'.
```suggestion
  mutateArrayBuffer,
```

Code after:
  getExternal,
  mutateExternal,
  createExternalString,
  createExternalRef,
  xxh2,
  xxh3,
  xxh64Alias,
  tsRename,
  acceptArraybuffer,
  acceptSlice,
  u8ArrayToArray,
  i8ArrayToArray,
  u16ArrayToArray,
  i16ArrayToArray,
  u32ArrayToArray,
  i32ArrayToArray,
  u64ArrayToArray,
  i64ArrayToArray,
  f32ArrayToArray,
  f64ArrayToArray,
  acceptUint8ClampedSlice,
  acceptUint8ClampedSliceAndBufferSlice,
  convertU32Array,
  createExternalTypedArray,
  mutateTypedArray,
  mutateArraybuffer,
  receiveAllOptionalObject,
  objectGetNamedPropertyShouldPerformTypecheck,
  fnReceivedAliased,
  ALIAS,
  appendBuffer,
  returnNull,
  returnUndefined,
  Dog,
  Bird,
  Assets,
  receiveStrictObject,
  receiveClassOrNumber,
  JsClassForEither,
  receiveMutClassOrNumber,
  getStrFromObject,
  testSerdeRoundtrip,
  testSerdeBigNumberPrecision,
  testSerdeBufferBytes,
  getBigintJsonValue,
  createObjWithProperty,
  receiveObjectOnlyFromJs,
  dateToNumber,
  chronoUtcDateToMillis,
  chronoLocalDateToMillis,
  chronoDateWithTimezoneToMillis,
Repository: napi-rs/napi-rs
File: examples/napi/__tests__/values.spec.ts (TypeScript)

Code before:
})

test('mutate TypedArray', (t) => {
  if (process.env.WASI_TEST) {
    t.pass()
    return
  }
  const input = new Float32Array([1, 2, 3, 4, 5])
  mutateTypedArray(input)
  t.deepEqual(input, new Float32Array([2.0, 4.0, 6.0, 8.0, 10.0]))
})

test('deref uint8 array', (t) => {
  t.is(
    derefUint8Array(new Uint8Array([1, 2]), new Uint8ClampedArray([3, 4])),
    4,
  )
})

test('accept untyped typed array', (t) => {
  t.is(acceptUntypedTypedArray(new Uint8Array([1, 2, 3])), 3n)
})

test('async', async (t) => {
  if (process.env.WASI_TEST) {
    t.pass()
    return
  }
  const bufPromise = readFileAsync(join(__dirname, '../package.json'))
  await t.notThrowsAsync(bufPromise)
  const buf = await bufPromise
  const { name } = JSON.parse(buf.toString())
  t.is(name, '@examples/napi')

  await t.throwsAsync(() => readFileAsync('some_nonexist_path.file'))
})

test('within async runtime', (t) => {
  t.notThrows(() => withinAsyncRuntimeIfAvailable())
})

test('panic in async fn', async (t) => {
  if (!process.env.SKIP_UNWIND_TEST && !process.env.WASI_TEST) {
    await t.throwsAsync(() => panicInAsync(), {
      message: 'panic in async function',
    })
  } else {
    t.pass('no unwind runtime')
  }
})


Review comment (suggestion):
Inconsistent naming: The function call should be `mutateArrayBuffer` (with capital 'B') to follow camelCase conventions and match similar functions in the codebase like `arrayBufferFromData` and `arrayBufferFromExternal`. Currently it's `mutateArraybuffer` with lowercase 'b'.
```suggestion
  mutateArrayBuffer(input)
```

Code after:
  )
})

test('mutate TypedArray', (t) => {
  if (process.env.WASI_TEST) {
    t.pass()
    return
  }
  const input = new Float32Array([1, 2, 3, 4, 5])
  mutateTypedArray(input)
  t.deepEqual(input, new Float32Array([2.0, 4.0, 6.0, 8.0, 10.0]))
})

test('mutate ArrayBuffer', (t) => {
  if (process.env.WASI_TEST) {
    t.pass()
    return
  }
  const input = new ArrayBuffer(5)
  const view = new Uint8Array(input)
  view[0] = 1
  view[1] = 2
  view[2] = 3
  view[3] = 4
  view[4] = 5
  mutateArraybuffer(input)
  t.deepEqual(view, new Uint8Array([2, 4, 6, 8, 10]))
})

test('deref uint8 array', (t) => {
  t.is(
    derefUint8Array(new Uint8Array([1, 2]), new Uint8ClampedArray([3, 4])),
    4,
  )
})

test('accept untyped typed array', (t) => {
  t.is(acceptUntypedTypedArray(new Uint8Array([1, 2, 3])), 3n)
})

test('async', async (t) => {
  if (process.env.WASI_TEST) {
    t.pass()
    return
  }
  const bufPromise = readFileAsync(join(__dirname, '../package.json'))
  await t.notThrowsAsync(bufPromise)
  const buf = await bufPromise
  const { name } = JSON.parse(buf.toString())
  t.is(name, '@examples/napi')
Repository: napi-rs/napi-rs
File: crates/backend/src/typegen.rs (Rust)

Code before:
        .map(|l| {
          if l.trim().is_empty() {
            String::new()
          } else if l.len() >= min_indent {
            l[min_indent..].to_owned()
          } else {
            l.to_owned()
          }
        })
        .collect()
    } else {
      Vec::new()
    }
  }
}

impl Display for JSDoc {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    if self.blocks.is_empty() {
      return Ok(());
    }

    if self.blocks.len() == 1 && self.blocks[0].len() == 1 {
      return writeln!(f, "/** {} */", self.blocks[0][0]);
    }

    writeln!(f, "/**")?;
    for (i, block) in self.blocks.iter().enumerate() {
      for line in block {
        writeln!(f, " * {line}")?;
      }
      if i + 1 != self.blocks.len() {
        writeln!(f, " *")?;
      }
    }
    writeln!(f, " */")
  }
}

impl Display for TypeDef {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    let js_mod = if let Some(js_mod) = &self.js_mod {
      format!(", \"js_mod\": \"{js_mod}\"")
    } else {
      "".to_string()
    };
    let original_name = if let Some(original_name) = &self.original_name {
      format!(", \"original_name\": \"{original_name}\"")
    } else {
      "".to_string()
    };

Review comment (bug):
The new `escape_comment_close` function lacks unit tests. Consider adding test cases to verify:
1. Basic escaping: `"*/"` → `"*\\/"`
2. Multiple occurrences: `"*/*/"`→ `"*\\/*\\/"`
3. Mixed content: `"test */ more"` → `"test *\\/ more"`
4. Edge case with no `*/`: `"normal comment"` → `"normal comment"`

This would ensure the escaping logic is correct and prevent regressions.

Code after:
        .map(|l| {
          if l.trim().is_empty() {
            String::new()
          } else if l.len() >= min_indent {
            l[min_indent..].to_owned()
          } else {
            l.to_owned()
          }
        })
        .collect()
    } else {
      Vec::new()
    }
  }
}

impl Display for JSDoc {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    if self.blocks.is_empty() {
      return Ok(());
    }

    // Escape `*/` sequences to prevent premature comment termination
    fn escape_comment_close(s: &str) -> String {
      s.replace("*/", "*\\/")
    }

    if self.blocks.len() == 1 && self.blocks[0].len() == 1 {
      return writeln!(f, "/** {} */", escape_comment_close(&self.blocks[0][0]));
    }

    writeln!(f, "/**")?;
    for (i, block) in self.blocks.iter().enumerate() {
      for line in block {
        writeln!(f, " * {}", escape_comment_close(line))?;
      }
      if i + 1 != self.blocks.len() {
        writeln!(f, " *")?;
      }
    }
    writeln!(f, " */")
  }
}

impl Display for TypeDef {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    let js_mod = if let Some(js_mod) = &self.js_mod {
      format!(", \"js_mod\": \"{js_mod}\"")
    } else {
      "".to_string()
    };
Repository: nautechsystems/nautilus_trader
File: nautilus_trader/adapters/binance/futures/data.py (Python)

Code before:
            self._handle_data(book_snapshot)

    def _handle_trade(self, raw: bytes) -> None:
        # NOTE @trade is an undocumented endpoint for Futures exchanges
        msg = self._decoder_futures_trade_msg.decode(raw)
        instrument_id: InstrumentId = self._get_cached_instrument_id(msg.data.s)
        trade_tick: TradeTick = msg.data.parse_to_trade_tick(
            instrument_id=instrument_id,
            ts_init=self._clock.timestamp_ns(),
        )
        self._handle_data(trade_tick)

    def _handle_mark_price(self, raw: bytes) -> None:
        msg = self._decoder_futures_mark_price_msg.decode(raw)
        instrument_id: InstrumentId = self._get_cached_instrument_id(msg.data.s)
        data = msg.data.parse_to_binance_futures_mark_price_update(
            instrument_id=instrument_id,
            ts_init=self._clock.timestamp_ns(),
        )
        data_type = DataType(
            BinanceFuturesMarkPriceUpdate,
            metadata={"instrument_id": instrument_id},
        )
        generic = CustomData(data_type=data_type, data=data)
        self._handle_data(generic)


Review comment (suggestion):
Good call leaving this in, so we don't immediately break by changing to the first class `MarkPriceUpdate`.
I'll make sure to deprecate this one in the release notes for a cycle.

Code after:
        else:
            self._handle_data(book_snapshot)

    def _handle_trade(self, raw: bytes) -> None:
        # NOTE @trade is an undocumented endpoint for Futures exchanges
        msg = self._decoder_futures_trade_msg.decode(raw)
        instrument_id: InstrumentId = self._get_cached_instrument_id(msg.data.s)
        trade_tick: TradeTick = msg.data.parse_to_trade_tick(
            instrument_id=instrument_id,
            ts_init=self._clock.timestamp_ns(),
        )
        self._handle_data(trade_tick)

    def _handle_mark_price(self, raw: bytes) -> None:
        msg = self._decoder_futures_mark_price_msg.decode(raw)
        instrument_id: InstrumentId = self._get_cached_instrument_id(msg.data.s)
        data = msg.data.parse_to_binance_futures_mark_price_update(
            instrument_id=instrument_id,
            ts_init=self._clock.timestamp_ns(),
        )
        data_type = DataType(
            BinanceFuturesMarkPriceUpdate,
            metadata={"instrument_id": instrument_id},
        )
        generic = CustomData(data_type=data_type, data=data)
        self._handle_data(generic)
        self._handle_data(
            MarkPriceUpdate(
                data.instrument_id,
                data.mark,
                data.ts_event,
                data.ts_init,
            ),
        )
Repository: nautechsystems/nautilus_trader
File: nautilus_trader/adapters/interactive_brokers/execution.py (Python)

Code before:
            # Determine position side
            side = PositionSide.LONG if new_quantity > 0 else PositionSide.SHORT

            # Create position status report
            position_report = PositionStatusReport(
                account_id=self.account_id,
                instrument_id=instrument.id,
                position_side=side,
                quantity=instrument.make_qty(new_quantity),
                report_id=UUID4(),
                ts_last=self._clock.timestamp_ns(),
                ts_init=self._clock.timestamp_ns(),
            )

            self._log.info(
                f"Option exercise position created: {instrument.id} {side} {abs(new_quantity)} @ {ib_position.avg_cost}",
                LogColor.CYAN,
            )

            # Send position status report to execution engine
            self._send_position_status_report(position_report)

            # Update tracking
            self._known_positions[contract_id] = new_quantity
        except Exception as e:
            self._log.exception(f"Error handling position update: {e}")


Review comment (bug):
This just needed to be `self._log.exception(f"Error handling position update", e)`, retaining the exception will help with debugging - will update on `develop` branch.

[edit] Will leave it for now as this is standardized with the other exception handling log calls in this module - but worth noting the exception can be useful if unexpected.

Code after:
            # Determine position side
            side = PositionSide.LONG if new_quantity > 0 else PositionSide.SHORT

            # Create position status report
            position_report = PositionStatusReport(
                account_id=self.account_id,
                instrument_id=instrument.id,
                position_side=side,
                quantity=instrument.make_qty(new_quantity),
                report_id=UUID4(),
                ts_last=self._clock.timestamp_ns(),
                ts_init=self._clock.timestamp_ns(),
            )

            self._log.info(
                f"Option exercise position created: {instrument.id} {side} {abs(new_quantity)} @ {ib_position.avg_cost}",
                LogColor.CYAN,
            )

            # Send position status report to execution engine
            self._send_position_status_report(position_report)

            # Update tracking
            self._known_positions[contract_id] = new_quantity
        except Exception as e:
            self._log.error(f"Error handling position update: {e}")
Repository: nautechsystems/nautilus_trader
File: crates/adapters/bybit/src/http/models.rs (Rust)

Code before:
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
pub type BybitTickersOptionResponse = BybitListResponse<BybitTickerOption>;

/// Unified ticker data structure containing common fields across all product types.
///
/// This simplified ticker structure is designed to work across SPOT, LINEAR, and OPTION products,
/// containing only the most commonly used fields.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit")
)]
pub struct BybitTickerData {
    pub symbol: Ustr,
    pub bid1_price: String,
    pub bid1_size: String,
    pub ask1_price: String,
    pub ask1_size: String,
    pub last_price: String,
    pub high_price24h: String,
    pub low_price24h: String,
    pub turnover24h: String,
    pub volume24h: String,
    pub open_interest: Option<String>,
    pub funding_rate: Option<String>,
    pub next_funding_time: Option<String>,
    pub mark_price: Option<String>,
    pub index_price: Option<String>,
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitTickerData {
    #[getter]
    #[must_use]
    pub fn symbol(&self) -> &str {
        self.symbol.as_str()
    }

    #[getter]
    #[must_use]
    pub fn bid1_price(&self) -> &str {
        &self.bid1_price
    }

    #[getter]
    #[must_use]
    pub fn bid1_size(&self) -> &str {
        &self.bid1_size
    }

Review comment (bug):
These need `#[serde(default)]` (like the one you added for `usd_index_price` above) or serialization will fail at runtime when they're missing.

Code after:
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
pub type BybitTickersOptionResponse = BybitListResponse<BybitTickerOption>;

/// Unified ticker data structure containing common fields across all product types.
///
/// This simplified ticker structure is designed to work across SPOT, LINEAR, and OPTION products,
/// containing only the most commonly used fields.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit")
)]
pub struct BybitTickerData {
    pub symbol: Ustr,
    pub bid1_price: String,
    pub bid1_size: String,
    pub ask1_price: String,
    pub ask1_size: String,
    pub last_price: String,
    pub high_price24h: String,
    pub low_price24h: String,
    pub turnover24h: String,
    pub volume24h: String,
    #[serde(default)]
    pub open_interest: Option<String>,
    #[serde(default)]
    pub funding_rate: Option<String>,
    #[serde(default)]
    pub next_funding_time: Option<String>,
    #[serde(default)]
    pub mark_price: Option<String>,
    #[serde(default)]
    pub index_price: Option<String>,
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitTickerData {
    #[getter]
    #[must_use]
    pub fn symbol(&self) -> &str {
        self.symbol.as_str()
    }

    #[getter]
    #[must_use]
    pub fn bid1_price(&self) -> &str {
        &self.bid1_price
    }
Repository: nautechsystems/nautilus_trader
File: nautilus_trader/adapters/interactive_brokers/common.py (Python)

Code before:
        "STK",
        "OPT",
        "FUT",
        "FOP",
        "CONTFUT",
        "CRYPTO",
        "CFD",
        "CMDTY",
        "IND",
        "BAG",
        "",
    ] = ""
    conId: int = 0
    exchange: str = ""
    primaryExchange: str = ""
    symbol: str = ""
    localSymbol: str = ""
    currency: str = ""
    tradingClass: str = ""

    # options and futures
    lastTradeDateOrContractMonth: str = ""
    lastTradeDate: str = ""
    multiplier: str = ""

    # options
    strike: float = 0.0
    right: str = ""

    # If set to true, contract details requests and historical data queries can be performed pertaining
    # to expired futures contracts. Expired options or other instrument types are not available.
    includeExpired: bool = False

    # common
    secIdType: str = ""
    secId: str = ""
    description: str = ""
    issuerId: str = ""

    # combos
    comboLegsDescrip: str = ""
    comboLegs: list[ComboLeg] | None = None
    deltaNeutralContract: DeltaNeutralContract | None = None

    # nautilus specific parameters
    build_futures_chain: bool | None = None
    build_options_chain: bool | None = None
    options_chain_exchange: str | None = None
    min_expiry_days: int | None = None
    max_expiry_days: int | None = None


Review comment (bug):
```suggestion
    # options
    # If strike is unspecified, it must pass through to ibapi as empty string.
    # Defaulting to 0 or None causes a bug, due to how ibapi handles input validation:
    # https://github.com/nautechsystems/nautilus_ibapi/blob/3028409bd8552e1829abf756a91302c5510d4267/ibapi/client.py#L590
    strike: float | str = ""
```

Code after:
        "STK",
        "OPT",
        "FUT",
        "FOP",
        "CONTFUT",
        "CRYPTO",
        "CFD",
        "CMDTY",
        "IND",
        "BAG",
        "",
    ] = ""
    conId: int = 0
    exchange: str = ""
    primaryExchange: str = ""
    symbol: str = ""
    localSymbol: str = ""
    currency: str = ""
    tradingClass: str = ""

    # options and futures
    lastTradeDateOrContractMonth: str = ""
    lastTradeDate: str = ""
    multiplier: str = ""

    # options
    strike: float | str = ""
    right: str = ""

    # If set to true, contract details requests and historical data queries can be performed pertaining
    # to expired futures contracts. Expired options or other instrument types are not available.
    includeExpired: bool = False

    # common
    secIdType: str = ""
    secId: str = ""
    description: str = ""
    issuerId: str = ""

    # combos
    comboLegsDescrip: str = ""
    comboLegs: list[ComboLeg] | None = None
    deltaNeutralContract: DeltaNeutralContract | None = None

    # nautilus specific parameters
    build_futures_chain: bool | None = None
    build_options_chain: bool | None = None
    options_chain_exchange: str | None = None
    min_expiry_days: int | None = None
    max_expiry_days: int | None = None